mxc-sdk 1.0.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Rootless private networking for Bubblewrap proxy mode.

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, 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, OnceLock};
use std::thread;
use std::time::{Duration, Instant};

use crate::mxc_common::filesystem_resolve::{resolve_mount_order, FsIntent};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainerPolicy, ProxyAddress, ProxyHostPin};
use nix::errno::Errno;
use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag};
use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
use nix::unistd::{access, dup2, pipe2, AccessFlags};
use tempfile::TempDir;

use crate::bwrap_common::bwrap_command::COMMAND_TAIL;
use crate::bwrap_common::network_rules::{
    payload_file_name, render_filter_payloads, EgressPlan, IngressPlan, RuleFamily,
};
use crate::bwrap_common::probe_exec;

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 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 long host list 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 eight 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";
/// 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;
/// Brings up the private network, then closes it down to the proxy before the
/// workload runs.
///
/// Ordering is the security property: the readiness signal is written only
/// after every rule is installed, and `set -e` turns a failed rule into
/// supervisor death rather than an unenforced sandbox. Rules are applied here
/// because that needs `CAP_NET_ADMIN` in the owning user namespace, which the
/// supervisor holds (`--keep-caps`) and the caller does not.
const SUPERVISOR_SCRIPT: &str = r#"
set -eu
state_dir="$1"
lock_wait="$2"
# Inherited descriptors are remapped to fixed numbers by the parent (see
# `remap_descriptors`): 3 is the parent's PID pipe, 4 is slirp's exit pipe.
# They are hardcoded rather than passed in argv because /bin/sh is dash on
# Debian/Ubuntu, which rejects a *variable* descriptor >= 10 ("Bad fd number")
# at parse time -- a failure that depends on how many files the parent happens
# to hold open, so it surfaces nondeterministically and never in unit tests.
printf ready > "$state_dir/userns.ready"
# Block on the parent-owned PID pipe rather than polling for a file: if the
# parent dies before it can publish the PID, the read ends at EOF and this
# supervisor exits instead of spinning forever as an orphan.
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

# slirp signals readiness internally so the supervisor, not slirp, decides when
# the sandbox is ready -- the rules below must be in place first. Descriptor 9
# is safe to hardcode: the parent hands this child exactly 0-4, so nothing else
# can be sitting on it.
exec 9> "$state_dir/slirp.internal"
slirp4netns --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

ns="/proc/$child_pid/ns/net"
# Network filtering in both directions, programmed here because it needs
# CAP_NET_ADMIN in the owning user namespace, which this supervisor holds
# (`--keep-caps`) and the caller does not.
#
# Each family's rules arrive as one or more `iptables-restore` transactions,
# numbered so this glob applies them in order. Both built-in hooks travel in
# the *last* transaction of a family, so a hook is never live over a partially
# built chain and the rules cannot be observed half-installed. Splitting is
# forced by the kernel: one restore is one bounded netlink transaction, and a
# large host list would otherwise exceed it and install nothing. The payloads
# are rendered in Rust from parsed addresses, so nothing here echoes caller
# text.
#
# -w matters only on the legacy backend, the one that takes a lock: nsenter
# enters the network namespace but not the mount namespace, so concurrent
# sandboxes contend for the *host's* /run/xtables.lock, and set -e turns a lost
# race into a dead supervisor. nf_tables takes no lock and ignores the wait.
# A backend that cannot take the lock at all is refused by probe_dependencies.
# -n keeps the restore additive, so it never clears a table it did not write
# and so a later transaction appends to the chain an earlier one declared.
#
# A rejected transaction applies nothing, so a host that cannot support a rule
# fails closed here rather than starting an unenforced sandbox. The most likely
# cause is worth naming, because iptables reports it only as "Invalid argument".
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."
for payload in "$state_dir"/rules.v4.*; do
    nsenter --net="$ns" -- iptables-restore -w "$lock_wait" -n "$payload" || { echo "$conntrack_hint" >&2; exit 1; }
done
# No IPv6 payload is written when the kernel has no IPv6 stack (see
# `rule_families`), and an unmatched glob expands to itself. IPv4 has no such
# guard, so a missing IPv4 payload still fails the restore and kills the
# supervisor.
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

# Signalled by path, not through a descriptor: this is a plain file the parent
# polls, so it needs no shell redirection and cannot hit dash's fd limit.
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,
}

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, String> {
        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
    }

    /// 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<(), String>) {
        let asked_to_resolve = Cell::new(false);
        let checked = Self::resolve_with(configured, |_, _| {
            asked_to_resolve.set(true);
            Err(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, String>,
    ) -> Result<Self, String> {
        if configured.port() == 0 {
            return Err("Bubblewrap: proxy-only egress requires a non-zero proxy port".to_string());
        }
        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 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()
                ));
            }
            return Err(ipv6_unsupported(host));
        }

        if is_reserved_loopback_name {
            return 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, String> {
    let query = host.to_string();
    let waited = with_deadline(RESOLVE_TIMEOUT_LABEL, RESOLVE_TIMEOUT, move || {
        lookup_ipv4(&query, port)
    })
    .map_err(|error| {
        format!("Bubblewrap: could not start the lookup of proxy host '{host}': {error}")
    })?;

    match waited {
        Ok(resolved) => resolved,
        Err(mpsc::RecvTimeoutError::Timeout) => Err(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(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, String> {
    let resolved: Vec<IpAddr> = (host, port)
        .to_socket_addrs()
        .map_err(|error| {
            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(format!(
            "Bubblewrap: proxy host '{host}' did not resolve to any address."
        ))
    } else {
        Err(ipv6_unsupported(host))
    }
}

/// 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>,
}

impl BwrapStartup {
    /// 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: &mut 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 let Some(status) = child
                .try_wait()
                .map_err(|error| format!("Bubblewrap: failed to inspect bwrap startup: {error}"))?
            {
                return Err(format!(
                    "Bubblewrap: bwrap exited before publishing child information ({status})"
                ));
            }
            if Instant::now() >= deadline {
                return Err("Bubblewrap: timed out waiting for bwrap child information".into());
            }
            thread::sleep(Duration::from_millis(10));
        }
    }

    /// Allow Bubblewrap to execute the workload after networking is ready.
    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.",
    );
}

/// A same-UID user-namespace supervisor and its `slirp4netns` process.
pub(crate) struct ProxyNetworkNamespace {
    state_dir: TempDir,
    supervisor: Child,
    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>,
    /// Handle to the supervisor's user namespace, passed to bwrap as
    /// `--userns`. Released once bwrap owns it; see [`Self::userns_handed_off`].
    userns: Option<File>,
    /// Hosts file mounted over `/etc/hosts`, when the endpoint is a hostname.
    hosts: Option<PathBuf>,
    /// 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 {
    /// Create the capability-retaining namespace supervisor.
    ///
    /// `plan` is the outbound filtering posture the sandbox runs under once the
    /// supervisor signals readiness; anything it does not accept is dropped.
    /// `ingress` is the matching inbound posture. `pin` is the hosts-file entry
    /// the sandbox needs to agree with the plan, which only a hostname proxy
    /// endpoint produces.
    ///
    /// Callers reach this only after `BwrapRunner::validate` has already run
    /// [`probe_dependencies`], so the probe is not repeated here.
    pub(crate) fn start(
        plan: &EgressPlan,
        ingress: &IngressPlan,
        pin: Option<&ProxyHostPin>,
        logger: &mut Logger,
        script_timeout_ms: u32,
    ) -> 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) =
            pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
        let (pid_reader, pid_writer) =
            pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
        let (liveness_reader, liveness_writer) =
            pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
        set_nonblocking(liveness_reader.as_raw_fd())?;

        let mut command = Command::new("unshare");
        command
            .args([
                "--user",
                "--map-current-user",
                "--keep-caps",
                "--",
                "sh",
                "-c",
                SUPERVISOR_SCRIPT,
                "mxc-bwrap-proxy-supervisor",
            ])
            .arg(state_dir.path())
            .arg(XTABLES_LOCK_WAIT.as_secs().to_string())
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::from(stderr));
        // 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_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,
        ) {
            terminate_child(&mut supervisor);
            return Err(error);
        }

        let userns_path = format!("/proc/{}/ns/user", supervisor.id());
        let userns = match File::open(&userns_path) {
            Ok(file) => file,
            Err(error) => {
                terminate_child(&mut supervisor);
                return Err(format!(
                    "Bubblewrap: failed to open proxy user namespace {userns_path}: {error}"
                ));
            }
        };
        logger.log_line("Bubblewrap: created rootless proxy network namespace supervisor");

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

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

    /// 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 (info_reader, info_writer) =
            pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
        let (gate_reader, gate_writer) =
            pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;

        let userns = self
            .userns
            .as_ref()
            .ok_or_else(|| "Bubblewrap: proxy user namespace is already handed off".to_string())?;

        if let Some(hosts) = &self.hosts {
            let path = hosts
                .to_str()
                .ok_or_else(|| "Bubblewrap: proxy hosts pin path is not valid UTF-8".to_string())?;
            if insert_hosts_bind(args, path)? {
                logger.log_line(
                    "Bubblewrap: the proxy host pin overrides an earlier mount of \
                     /etc/hosts; the sandbox sees the pinned file",
                );
            }
        }

        let runtime_args = [
            "--userns".to_string(),
            userns.as_raw_fd().to_string(),
            "--info-fd".to_string(),
            info_writer.as_raw_fd().to_string(),
            "--block-fd".to_string(),
            gate_reader.as_raw_fd().to_string(),
        ];
        args.splice(0..0, runtime_args);

        Ok(BwrapStartup {
            inheritable: vec![
                userns.as_raw_fd(),
                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),
        })
    }

    /// Drop this process's handle to the user namespace once bwrap holds it.
    ///
    /// The namespace itself stays alive through the supervisor, which is a
    /// member of it. Releasing here bounds the window in which a concurrent
    /// spawn could pick the descriptor up to the bwrap spawn itself, rather
    /// than the whole sandbox lifetime.
    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 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",
            rule_install_timeout(self.transactions, self.script_timeout_ms),
        )?;
        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.try_wait() {
            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.try_wait() {
            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.try_wait() {
                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"))
                    ));
                    terminate_child(&mut self.supervisor);
                    return;
                }
                Err(error) => {
                    logger.log_line(&format!(
                        "WARNING: Bubblewrap: failed to inspect slirp4netns shutdown: {error}"
                    ));
                    terminate_child(&mut self.supervisor);
                    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}"))
        }
    }
}

/// Arguments 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), which would otherwise surface deep
/// inside supervisor startup. Both namespaces are requested together, mirroring
/// the `CLONE_NEWUSER|CLONE_NEWNET` bwrap asks for, and via `sh -c :` because
/// the supervisor itself runs as `sh -c`.
const PRIVATE_NAMESPACE_PROBE_ARGS: [&str; 8] = [
    "--user",
    "--map-current-user",
    "--keep-caps",
    "--net",
    "--",
    "sh",
    "-c",
    ":",
];

/// 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,
    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, 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, use_case: PrivateNetworkUse) -> String {
    let requirement = use_case.requirement();
    // 126/127 are the exec-failure codes `unshare` propagates (EACCES and
    // ENOENT). A PATH lookup can produce either, and both mean the namespaces
    // worked and `sh` is what could not start.
    if status.code().is_some_and(shell_failed_to_start) {
        return format!(
            "Bubblewrap: {requirement} requires 'sh' on PATH inside the sandbox namespace \
             (the proxy supervisor runs as 'sh -c'), which this host could not start. \
             Install a POSIX shell or {}.",
            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) -> 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 fs::read_to_string(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
}

/// 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 {
    resolve_mount_order(policy)
        .iter()
        .rfind(|mount| covers_hosts_file(&mount.path))
        .is_some_and(|mount| mount.intent == FsIntent::Denied)
}

/// Whether `path` is the sandbox hosts file or a directory holding it.
fn covers_hosts_file(path: &str) -> bool {
    let path = path.trim_end_matches('/');
    path == SANDBOX_HOSTS_PATH
        || SANDBOX_HOSTS_PATH
            .strip_prefix(path)
            .is_some_and(|rest| rest.starts_with('/'))
}

/// Splice the pinned-hosts 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
/// `/etc/hosts`. Returns `true` when an earlier mount already targeted
/// `/etc/hosts`, so the caller can report that the pin overrides it.
/// 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())
}

fn insert_hosts_bind(args: &mut Vec<String>, hosts_path: &str) -> Result<bool, String> {
    let separator = command_separator(args)?;
    let overrides = args[..separator]
        .iter()
        .any(|arg| arg == SANDBOX_HOSTS_PATH);
    args.splice(
        separator..separator,
        [
            "--ro-bind".to_string(),
            hosts_path.to_string(),
            SANDBOX_HOSTS_PATH.to_string(),
        ],
    );
    Ok(overrides)
}

/// What pulled this request into a private network namespace.
///
/// The dependency probe is shared by proxy-only egress and firewall
/// enforcement, but the remedy it should suggest is not: telling a caller who
/// set `enforcementMode: "firewall"` to "omit network.proxy" names a field they
/// never set. Carries the caller's own words into every probe message.
///
/// The two are mutually exclusive — the parser rejects a proxy combined with a
/// firewall mode — so a request always maps to exactly one.
#[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 => "network.proxy",
            Self::FirewallEnforcement => "network.enforcementMode='firewall'",
        }
    }

    /// What the caller can drop to stop needing these dependencies.
    fn remedy(self) -> &'static str {
        match self {
            Self::ProxyOnlyEgress => "omit network.proxy",
            Self::FirewallEnforcement => "select a different network.enforcementMode",
        }
    }

    /// 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_runner`]: schema 0.8 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 still probes before it launches.
///
/// 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),
        )
    })
}

/// 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();
    }
}

pub(crate) fn probe_dependencies(use_case: PrivateNetworkUse) -> Result<(), String> {
    static PROBED: OnceLock<()> = OnceLock::new();

    probe_dependencies_caching(
        &PROBED,
        use_case,
        ProbeBudget::unbounded(),
        real_probe_command,
    )
}

/// [`probe_dependencies`] against a caller-supplied cache, so the reuse rules
/// are testable without a process-global `OnceLock`.
///
/// Only the tool and version checks are cached, and only on success: a failure
/// usually means the operator has not installed slirp4netns yet. The
/// namespace-allocation check stays outside, because unlike a package on PATH
/// the kernel's answer changes under a running process.
fn probe_dependencies_caching<F>(
    cache: &OnceLock<()>,
    use_case: PrivateNetworkUse,
    budget: ProbeBudget,
    command: F,
) -> Result<(), String>
where
    F: Fn(&str, &[&str]) -> Command,
{
    if cache.get().is_none() {
        probe_stable_dependencies(use_case, budget, &command)?;
        let _ = cache.set(());
    }

    check_private_namespaces(
        command("unshare", &PRIVATE_NAMESPACE_PROBE_ARGS),
        use_case,
        budget,
    )
}

/// Tools the in-namespace rules are programmed with: `(binary, probe flag,
/// whether its backend must also be checked)`.
///
/// `iptables` / `ip6tables` are probed even though the supervisor only runs the
/// `-restore` variants: they carry the version banner the backend decision
/// reads, and ship in the same package. Over-strict is safe here; under-strict
/// would let a launch fail on a host the pre-flight called supported.
const RULE_TOOL_PROBES: [(&str, &str, bool); 5] = [
    ("nsenter", "--version", false),
    ("iptables", "--version", true),
    ("ip6tables", "--version", true),
    ("iptables-restore", "--version", true),
    ("ip6tables-restore", "--version", true),
];

/// Whether a dependency probe covers a command [`SUPERVISOR_SCRIPT`] invokes.
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SupervisorCommandCoverage {
    /// `probe_dependencies_uncached` refuses the host when this is missing.
    Probed,
    /// Deliberately unprobed, with the reason.
    Exempt(&'static str),
}

/// Digest of the reviewed [`SUPERVISOR_SCRIPT`], line-ending independent.
/// Bumping it acknowledges that the command list below was re-checked.
#[cfg(test)]
const EXPECTED_SUPERVISOR_SCRIPT_DIGEST: u64 = 0x5855_540d_dc42_997c;

/// Every external command [`SUPERVISOR_SCRIPT`] runs, and how the pre-flight
/// walk accounts for it.
#[cfg(test)]
const SUPERVISOR_EXTERNAL_COMMANDS: &[(&str, SupervisorCommandCoverage)] = &[
    ("slirp4netns", SupervisorCommandCoverage::Probed),
    ("nsenter", SupervisorCommandCoverage::Probed),
    ("iptables-restore", SupervisorCommandCoverage::Probed),
    ("ip6tables-restore", SupervisorCommandCoverage::Probed),
    (
        "sleep",
        SupervisorCommandCoverage::Exempt(
            "coreutils; cannot realistically be absent on a host that already \
             has util-linux and iptables",
        ),
    ),
];

/// 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: &str, args: &[&str]) -> Command {
    let mut command = Command::new(program);
    command.args(args);
    command
}

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

fn probe_dependencies_with<F>(
    use_case: PrivateNetworkUse,
    budget: ProbeBudget,
    command: F,
) -> Result<(), String>
where
    F: Fn(&str, &[&str]) -> Command,
{
    probe_stable_dependencies(use_case, budget, &command)?;
    check_private_namespaces(
        command("unshare", &PRIVATE_NAMESPACE_PROBE_ARGS),
        use_case,
        budget,
    )
}

/// 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,
    command: &F,
) -> Result<(), String>
where
    F: Fn(&str, &[&str]) -> Command,
{
    let requirement = use_case.requirement();
    let slirp = run_probe(
        command("slirp4netns", &["--version"]),
        "slirp4netns",
        budget,
    )
    .map_err(|error| {
        format!(
            "Bubblewrap: {requirement} requires 'slirp4netns' on PATH: {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 =
        run_probe(command("unshare", &["--help"]), "unshare", budget).map_err(|error| {
            format!("Bubblewrap: {requirement} requires util-linux 'unshare' on 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"
        ));
    }

    // The in-namespace rules are programmed with these, so a host missing them
    // must fail here rather than deep inside supervisor startup.
    for (binary, probe, has_backend) in RULE_TOOL_PROBES {
        let output = run_probe(command(binary, &[probe]), binary, budget).map_err(|error| {
            format!(
                "Bubblewrap: {requirement} requires '{binary}' on PATH to enforce {}: {error}",
                use_case.mechanism()
            )
        })?;
        if !output.status.success() {
            return Err(format!(
                "Bubblewrap: {requirement} requires a working '{binary}' installation \
                 ({binary} {probe} exited with {})",
                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,
                &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,
    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(),
        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 Child,
    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.try_wait().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.
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(())
        });
    }
}

/// 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}"))
}

fn terminate_child(child: &mut Child) {
    let _ = child.kill();
    let _ = child.wait();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::NetworkEnforcementCompatibility;

    /// 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");

        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, String> {
        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.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();

        assert!(
            error.contains("proxy.corp.invalid"),
            "error should name the offending 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.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.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()).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()).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()).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, "/tmp/pin/hosts").unwrap();

        let pin = args
            .windows(3)
            .position(|window| window == ["--ro-bind", "/tmp/pin/hosts", 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, "/tmp/pin/hosts").unwrap());

        let mut untouched = vec!["--ro-bind-try".to_string()];
        untouched.extend(command_tail());
        assert!(!insert_hosts_bind(&mut untouched, "/tmp/pin/hosts").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, "/tmp/pin/hosts").is_err());
    }

    /// 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, "/tmp/pin/hosts").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", "/tmp/pin/hosts", 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("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("-- iptables-restore ");
        script_offset("-- 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("-- 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("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| line.contains("-- iptables ") || line.contains("-- ip6tables ")),
            "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);
    }

    /// A plan whose rule count is what the test cares about. Sized through the
    /// public constructor so the count matches what the supervisor installs.
    fn plan_with_rule_count(count: usize) -> EgressPlan {
        let mut request = crate::mxc_common::models::ExecutionRequest {
            network_enforcement_compatibility: NetworkEnforcementCompatibility::Strict,
            ..Default::default()
        };
        request.policy.allowed_hosts = (0..count)
            .map(|n| format!("10.0.{}.{}", n / 256, n % 256))
            .collect();
        EgressPlan::for_policy(&request).expect("literal addresses must build a plan")
    }

    /// 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}"
        );
    }

    /// `unshare` runs `sh` via a PATH lookup, so an exec failure 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), 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), PrivateNetworkUse::ProxyOnlyEgress);

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

    fn on_path(tool: &str) -> bool {
        Command::new("sh")
            .args(["-c", &format!("command -v {tool} >/dev/null 2>&1")])
            .status()
            .is_ok_and(|status| status.success())
    }

    fn namespaces_are_available() -> bool {
        Command::new("unshare")
            .args([
                "--user",
                "--map-current-user",
                "--keep-caps",
                "--net",
                "--",
                "sh",
                "-c",
                ":",
            ])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
    }

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

    /// 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 probe_dependencies_uncached probes every \
             binary the script runs (including those passed to `nsenter --`), 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(name),
                "SUPERVISOR_EXTERNAL_COMMANDS lists '{name}', but SUPERVISOR_SCRIPT no longer \
                 runs it; drop the entry"
            );
        }
    }

    /// Every command marked `Probed` must really be one the walk refuses a host
    /// over, otherwise the annotation is decorative.
    #[test]
    fn commands_marked_probed_are_in_the_dependency_walk() {
        // The walk's full set: the two checked directly, plus the rule tooling.
        let mut probed: Vec<&str> = vec!["slirp4netns", "unshare"];
        probed.extend(RULE_TOOL_PROBES.iter().map(|(binary, _, _)| *binary));

        for (name, coverage) in SUPERVISOR_EXTERNAL_COMMANDS {
            if *coverage == SupervisorCommandCoverage::Probed {
                assert!(
                    probed.contains(name),
                    "'{name}' is marked Probed 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() {
        for binary in ["nsenter", "iptables-restore", "ip6tables-restore"] {
            assert!(
                SUPERVISOR_SCRIPT.contains(binary),
                "expected the supervisor to run '{binary}'"
            );
            assert!(
                RULE_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_but_re_checks_namespaces() {
        use std::cell::RefCell;

        let log = RefCell::new(Vec::new());
        let counting = |program: &str, args: &[&str]| {
            log.borrow_mut()
                .push(format!("{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 cache = OnceLock::new();
        let run = |use_case| {
            let _ =
                probe_dependencies_caching(&cache, use_case, ProbeBudget::unbounded(), counting);
            (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_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!(
            after_second.1 > after_first.1 && after_other_use_case.1 > after_second.1,
            "the namespace check must run on every call, warm cache or not: {after_first:?} \
             then {after_second:?} then {after_other_use_case:?}"
        );
    }

    /// 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 cache = OnceLock::new();
        let failing = |_: &str, _: &[&str]| {
            attempts.set(attempts.get() + 1);
            let mut command = Command::new("sh");
            command.args(["-c", "exit 1"]);
            command
        };

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

        probe_dependencies_caching(
            &cache,
            PrivateNetworkUse::ProxyOnlyEgress,
            ProbeBudget::unbounded(),
            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,
            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,
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
            )
            .expect_err("an exec failure must fail the walk");

            assert!(error.contains("'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,
            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 command = real_probe_command("unshare", &PRIVATE_NAMESPACE_PROBE_ARGS);
        assert_eq!(command.get_program(), "unshare");

        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 as `sh -c`, so the probe must exercise that.
        assert!(
            args.windows(2)
                .any(|pair| pair[0] == "sh" && pair[1] == "-c"),
            "the probe must run the supervisor's shell, got: {args:?}"
        );
    }

    /// A stand-in for the whole dependency walk: every tool succeeds with the
    /// banner the walk demands, except `missing`, which is not on PATH.
    ///
    /// 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_where_only(missing: Option<&'static str>) -> impl Fn(&str, &[&str]) -> Command {
        move |program, _args| {
            if Some(program) == missing {
                // A name that cannot exist on PATH, so the spawn fails with
                // ENOENT exactly as a genuinely absent tool would.
                return Command::new("mxc-probe-absent-tool-for-tests");
            }
            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: &str, override_script: Option<&str>) -> Command {
        let script = override_script.unwrap_or(match 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(),
                walk_where_only(None),
            ),
            Ok(())
        );
    }

    /// 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",
            "nsenter",
            "iptables",
            "ip6tables",
            "iptables-restore",
            "ip6tables-restore",
        ] {
            let error = probe_dependencies_with(
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
                walk_where_only(Some(tool)),
            )
            .expect_err("a missing tool must fail the walk");

            assert!(
                error.contains(tool),
                "a missing '{tool}' must be named, got: {error}"
            );
            assert!(
                error.contains("network.proxy"),
                "the refusal must name the config that required it, got: {error}"
            );
        }
    }

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

        assert!(error.contains("enforcementMode"), "got: {error}");
        assert!(!error.contains("omit network.proxy"), "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 factory = |program: &str, _args: &[&str]| {
            if program == "nsenter" {
                return walk_stub_for(program, Some("exit 3"));
            }
            walk_stub_for(program, None)
        };

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

        assert!(error.contains("nsenter"), "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: &str, _args: &[&str]| {
                if program == "unshare" {
                    return walk_stub_for(program, Some(banner));
                }
                walk_stub_for(program, None)
            };

            let error = probe_dependencies_with(
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
                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; 8] = [
            "slirp4netns",
            "unshare",
            "sh",
            "nsenter",
            "iptables",
            "ip6tables",
            "iptables-restore",
            "ip6tables-restore",
        ];
        let missing: Vec<&str> = CHECKED_TOOLS
            .into_iter()
            .filter(|tool| !on_path(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",
                "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",
            "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}"
        );
    }

    /// Firewall enforcement shares this probe with proxy-only egress, so a
    /// missing dependency used to advise a caller to "omit network.proxy" --
    /// a field a firewall-only request never set. The advice must name what
    /// 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",
            "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("network.proxy"),
            "a firewall-only request must not be told about a field it never set: {error}"
        );
        assert!(
            error.contains("network.enforcementMode='firewall'"),
            "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",
            "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("network.proxy") && !error.contains("enforcementMode"),
            "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",
                "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",
                "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
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%-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
echo $$ > "$MXC_TEST_SLIRP_PID"
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,
        child: Child,
        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.try_wait().expect("try_wait") {
                    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.try_wait().expect("try_wait") {
                    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.kill();
            let _ = self.child.wait();
            // `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 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");
        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 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");

        // The stubs shadow the real tools; the rest of PATH still supplies the
        // coreutils the script uses (`sleep`, `cat`).
        let path = format!(
            "{}:{}",
            bin.display(),
            std::env::var("PATH").unwrap_or_default()
        );
        let mut command = Command::new("sh");
        command
            .args(["-c", SUPERVISOR_SCRIPT, "mxc-test-supervisor"])
            .arg(&state)
            .arg("1")
            .env("PATH", path)
            .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_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 = command.spawn().expect("spawn supervisor");
        drop(exit_reader);
        drop(pid_reader);

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

    /// 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 host 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,
                "a {rule_count}-rule policy 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 "))
            .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!(" -d 10.0.{}.{} ", index / 256, index % 256);
            assert!(
                rule.contains(&expected),
                "rule {index} arrived out of order: {rule}"
            );
        }
    }

    /// 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_block_policy_accepts_only_its_allowlist_and_closes_both_families() {
        let mut request = crate::mxc_common::models::ExecutionRequest::default();
        request.policy.default_network_policy = crate::mxc_common::models::NetworkPolicy::Block;
        request.policy.allowed_hosts = vec!["203.0.113.7".into(), "2001:db8::/32".into()];
        let plan = EgressPlan::for_policy(&request).expect("literals must build a plan");

        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 203.0.113.7 -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_blocklist_before_the_open_terminal() {
        let mut request = crate::mxc_common::models::ExecutionRequest::default();
        request.policy.default_network_policy = crate::mxc_common::models::NetworkPolicy::Allow;
        request.policy.blocked_hosts = vec!["198.51.100.0/24".into()];
        request.policy.allowed_hosts = vec!["198.51.100.9".into()];
        let plan = EgressPlan::for_policy(&request).expect("literals must build a plan");

        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 -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 mut request = crate::mxc_common::models::ExecutionRequest::default();
        request.policy.default_network_policy = crate::mxc_common::models::NetworkPolicy::Block;
        request.policy.allowed_hosts = vec!["203.0.113.7".into()];
        let plan = EgressPlan::for_policy(&request).expect("literals must build a plan");

        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()
            .expect("spawn supervisor");

        ProxyNetworkNamespace {
            state_dir,
            supervisor,
            exit_writer: None,
            pid_writer: None,
            userns: None,
            hosts: None,
            liveness_reader: None,
            transactions: 0,
            script_timeout_ms: 0,
        }
    }

    fn await_exit(namespace: &mut ProxyNetworkNamespace) {
        let deadline = Instant::now() + Duration::from_secs(20);
        while Instant::now() < deadline {
            if namespace.supervisor.try_wait().expect("try_wait").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"
        );
    }
}