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

//! Builds the `bwrap` CLI argument vector from an [`ExecutionRequest`].
//!
//! This module is platform-agnostic: it only produces a `Vec<String>` of
//! arguments without spawning any processes, so it compiles and can be
//! unit-tested on every host (Windows, macOS, Linux).

use std::collections::HashSet;

use crate::mxc_common::filesystem_resolve::FsIntent;
use crate::mxc_common::models::{
    ContainerPolicy, ExecutionRequest, NetworkAction, NetworkEnforcementCompatibility,
    NetworkEnforcementMode, NetworkPolicy, ProxyAddress,
};
use crate::mxc_common::proxy_env::{is_managed_proxy_key, PROXY_SET_KEYS};

/// The fixed prefix of the command bwrap is asked to run.
///
/// `build_args` appends this last, so its position identifies where the
/// options end -- unlike a bare `--` token, which a caller-supplied
/// environment value can also be. Shared so the two cannot drift apart.
pub(crate) const COMMAND_TAIL: [&str; 3] = ["--", "sh", "-c"];

/// Read-only host paths bind-mounted into every Bubblewrap sandbox as the
/// deny-by-default baseline. Mirrors the seatbelt backend's
/// `SYSTEM_READ_ALLOW` (`src/backends/seatbelt/common/src/profile_builder.rs`):
/// just enough of the host for a shell, the dynamic linker, libc, and
/// system tools to work. Everything else — including the caller's `$HOME`,
/// `/root`, `/opt`, `/var`, `/sys`, `/mnt`, `/media`, and the rest of
/// `/run` — is invisible until the caller opts in via `readonlyPaths` /
/// `readwritePaths`.
///
/// Notes:
/// - Missing paths are silently skipped because the runner emits these
///   via `--ro-bind-try` (e.g. `/lib32` does not exist on x86_64-only
///   systems; `/run/systemd/resolve` does not exist on hosts without
///   systemd-resolved).
/// - On merged-usr distros (modern Debian, Ubuntu, Fedora, Arch) the
///   top-level `/bin`, `/sbin`, `/lib*` entries are symlinks pointing
///   under `/usr`. `bwrap` follows the source-side symlink, so the
///   bind-mount still succeeds and the sandbox sees `/bin/sh` etc.
/// - We deliberately do NOT bind `/usr` wholesale: that would expose
///   `/usr/local`, which contains locally-installed (and sometimes
///   user-managed) software. Callers who need `/usr/local` must list it
///   explicitly in `readonlyPaths`.
/// - We deliberately do NOT bind `/run` wholesale: `/run/user/<uid>`
///   holds the caller's D-Bus session socket, keyring sockets, and
///   ssh-agent socket. We only bind the well-known DNS stub-resolver
///   directories so name resolution still works when `/etc/resolv.conf`
///   is a symlink (the default on systemd-resolved hosts).
/// - To keep DNS working when `/etc/resolv.conf` points *outside* those
///   dirs, we also synthesise a `/var/run -> /run` compat symlink (for
///   `/var/run/...`-routed targets — older RHEL/CentOS-era and some
///   container images) and `--ro-bind-try` `/mnt/wsl/resolv.conf` (for
///   WSL). Neither exposes host `/var` or `/mnt` contents — only the
///   resolver path itself.
/// - `/etc` is bound whole because cherry-picking files (`passwd`,
///   `nsswitch.conf`, `ssl/`, `ld.so.conf*`, …) is fragile and breaks
///   tools that read other config files. Files with sensitive contents
///   (`/etc/shadow`, `/etc/sudoers`, `/etc/ssh/ssh_host_*_key`) are mode
///   `0400` / `0640` root and remain unreadable to a non-root caller —
///   user-namespace UID mapping does not bypass kernel DAC.
const BASELINE_RO_BIND_PATHS: &[&str] = &[
    // Top-level executable / library dirs (symlinks under /usr on
    // merged-usr distros, real directories on Alpine and older Debian).
    "/bin",
    "/sbin",
    "/lib",
    "/lib32",
    "/lib64",
    "/libx32",
    // /usr subpaths — aligned with seatbelt's baseline, intentionally
    // excluding /usr/local.
    "/usr/bin",
    "/usr/sbin",
    "/usr/lib",
    "/usr/lib32",
    "/usr/lib64",
    "/usr/libexec",
    "/usr/share",
    // System configuration (ld.so config, certs, resolv.conf, hosts,
    // passwd, group, machine-id, …). See module-level note on DAC.
    "/etc",
    // DNS stub-resolver directories. /etc/resolv.conf is usually a
    // symlink into one of these on modern Linux distros (systemd-resolved
    // / NetworkManager / resolvconf). We bind the narrow subdirectories
    // rather than all of /run to avoid exposing /run/user/<uid>.
    "/run/systemd/resolve",
    "/run/NetworkManager",
    "/run/resolvconf",
    // WSL generates its resolv.conf here and points /etc/resolv.conf at
    // it. Bind just this single file (not /mnt) so DNS works under WSL
    // without exposing the Windows drive mounts. Skipped on non-WSL hosts
    // because the baseline is emitted via `--ro-bind-try`.
    "/mnt/wsl/resolv.conf",
];

/// The networking behavior Bubblewrap applies for one execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ResolvedNetworkMode {
    /// A private network namespace with no external connectivity.
    Isolated,
    /// The host network namespace without MXC firewall filtering.
    Shared,
    /// Pre-0.8 cooperative proxy routing in the host network namespace.
    LegacyProxy,
    /// The host network namespace with per-destination iptables filtering.
    ///
    /// Pre-0.8 only. The rules land on the *host* chain, which the sandbox
    /// never traverses, so this filters nothing; it is retained unchanged
    /// because pre-0.8 callers already run under it.
    FirewallFiltered,
    /// Per-destination iptables filtering inside a slirp-backed private
    /// namespace, with no proxy. 0.8+ only.
    FirewallEnforced,
    /// Cooperative proxy routing inside a slirp-backed private namespace, with
    /// egress closed to everything but the proxy.
    ProxyOnly,
}

/// Whether this request uses strict network-contract behavior.
fn uses_strict_network_contract(request: &ExecutionRequest) -> bool {
    request.network_enforcement_compatibility == NetworkEnforcementCompatibility::Strict
}

/// Whether the policy carries the 0.8 directional shape.
///
/// Either section is enough: the parser fills both together, but checking only
/// one would route an ingress-only policy into the legacy path, where its
/// directional intent is silently discarded. Shared by every site that splits
/// directional from legacy so the fail-closed reading cannot drift apart.
///
/// Distinct from `crate::mxc_common::validator::directional_posture_supplied`, which
/// also folds in `network_mode_specified` and the proxy; the two are not
/// interchangeable.
pub(crate) fn is_directional(policy: &ContainerPolicy) -> bool {
    policy.network_egress.is_some() || policy.network_ingress.is_some()
}

impl ResolvedNetworkMode {
    /// Classify the internal request using the proxy's resolved runtime state.
    pub(crate) fn from_request(request: &ExecutionRequest, proxy_active: bool) -> Self {
        if proxy_active {
            return if uses_strict_network_contract(request) {
                Self::ProxyOnly
            } else {
                Self::LegacyProxy
            };
        }

        // The directional 0.8 posture is authoritative when present: the parser
        // fills these sections only on that path and leaves every legacy field
        // at its default, so classifying from the legacy fields below would
        // read a policy that never said either as `Isolated` and take the
        // sandbox offline with the requested rules programmed nowhere.
        //
        // Either section makes it directional (see `is_directional`); a missing
        // egress defaults to deny, failing closed.
        //
        // Directional never selects `Shared`: the host namespace has no inbound
        // primitive, and `network_ingress` has no `_specified` twin, so a
        // defaulted `ingress.default='deny'` is indistinguishable from one the
        // caller wrote and could not be refused without refusing every
        // "allow all outbound" policy with it. The private namespace honors
        // both directions, so an open egress posture becomes an accept-all
        // chain rather than an unfiltered namespace.
        if is_directional(&request.policy) {
            // Off the 0.8 contract there is no private namespace to program.
            // Report the unfiltered truth and let `validate` refuse it rather
            // than pretending the posture was applied.
            if !uses_strict_network_contract(request) {
                return Self::Shared;
            }
            let egress = request.policy.network_egress.clone().unwrap_or_default();
            // A bare deny is `--unshare-net`: cheaper than slirp plus a
            // deny-all chain, identical in effect, and inbound is denied by
            // the absence of connectivity rather than by a rule.
            let ruleless = egress.allow.is_empty() && egress.deny.is_empty();
            return if ruleless && egress.default == NetworkAction::Deny {
                Self::Isolated
            } else {
                Self::FirewallEnforced
            };
        }

        let uses_firewall = matches!(
            request.policy.network_enforcement_mode,
            NetworkEnforcementMode::Firewall | NetworkEnforcementMode::Both
        );
        let has_host_rules =
            !request.policy.allowed_hosts.is_empty() || !request.policy.blocked_hosts.is_empty();

        if uses_firewall && has_host_rules {
            if uses_strict_network_contract(request) {
                Self::FirewallEnforced
            } else {
                Self::FirewallFiltered
            }
        } else if request.policy.default_network_policy == NetworkPolicy::Block && !has_host_rules {
            Self::Isolated
        } else {
            Self::Shared
        }
    }

    /// Whether current behavior gives the sandbox a private network namespace.
    pub(crate) fn uses_private_netns(self) -> bool {
        matches!(
            self,
            Self::Isolated | Self::ProxyOnly | Self::FirewallEnforced
        )
    }

    /// Whether the runner supplies a pre-created user namespace to Bubblewrap.
    pub(crate) fn uses_external_userns(self) -> bool {
        matches!(self, Self::ProxyOnly | Self::FirewallEnforced)
    }

    /// Whether the mode uses the host-side firewall manager.
    ///
    /// False for `ProxyOnly` and `FirewallEnforced`, which are *not*
    /// iptables-free: they program rules directly into the sandbox's own
    /// network namespace from the supervisor (see `proxy_network`) rather than
    /// going through the host manager.
    #[cfg(any(target_os = "linux", test))]
    pub(crate) fn requires_host_firewall_manager(self) -> bool {
        matches!(self, Self::FirewallFiltered)
    }

    /// Whether this mode actually applies the policy's host lists.
    ///
    /// `FirewallEnforced` filters by address in the sandbox's own namespace.
    /// `ProxyOnly` closes egress to everything but the proxy endpoint, so the
    /// lists are enforced at the proxy — true only for the builtin proxy; an
    /// external one is refused by [`external_proxy_host_rules_rejection`].
    /// Every other mode leaves the lists unapplied.
    pub(crate) fn enforces_host_rules(self) -> bool {
        matches!(self, Self::FirewallEnforced | Self::ProxyOnly)
    }
}

/// Rejection text for host lists no mechanism will enforce, on schema 0.8+.
///
/// Owned here rather than in the parser: this is a statement about what
/// Bubblewrap can enforce, so it belongs with the backend that enforces it.
pub const BWRAP_UNENFORCED_HOST_RULES: &str =
    "Bubblewrap: network.allowedHosts and network.blockedHosts require an enforcement \
     mechanism. With enforcementMode='capabilities' (the default) and no network.proxy, \
     nothing applies them: the host lists suppress the --unshare-net full block, so the \
     sandbox shares the host network namespace with no filtering at all. Set \
     network.enforcementMode to 'firewall' to filter by address inside the sandbox's own \
     network namespace, set network.proxy to enforce host filtering at the proxy layer, or \
     drop the host lists to get the namespace-level block that defaultPolicy='block' applies \
     on its own.";

/// Rejection text for `allowLocalNetwork=false` under a shared namespace.
pub const BWRAP_LOCAL_NETWORK_SHARED_NS: &str =
    "Bubblewrap: network.allowLocalNetwork=false is not enforced while the \
     sandbox shares the host network namespace (defaultPolicy='allow'). \
     The sandboxed process can still bind, listen and accept on host-local addresses. For \
     an unreachable sandbox use defaultPolicy='block' with no host rules and no proxy, \
     which applies --unshare-net; to keep the shared namespace, acknowledge the exposure \
     with allowLocalNetwork=true.";

/// Rejection text for `allowLocalNetwork=true` under a private namespace.
pub const BWRAP_LOCAL_NETWORK_PRIVATE_NS: &str =
    "Bubblewrap: network.allowLocalNetwork=true is confined to the sandbox's own \
     network namespace. Isolated, proxy and firewall modes apply --unshare-net, so a \
     listener inside the sandbox is reachable only from within it, never from the host. \
     Use defaultPolicy='allow' with no host rules and no proxy to share the host network \
     namespace.";

/// Refuse a directional 0.8 posture Bubblewrap cannot honor.
///
/// The backend declares `INGRESS_DEFAULT` and `HOST_LOOPBACK` in
/// [`network_policy_support`], which tells shared validation it understands
/// those fields — not that it can satisfy both of their values. Shared
/// validation therefore stops checking them and these rejections become the
/// only thing standing between an unsupported value and a silent drop, so they
/// ship in the same change as the declaration.
///
/// Deliberately *not* schema-gated. The pre-0.8 warning path exists for configs
/// that predate a rule; a directional section is a 0.8 construct, so seeing one
/// on an older schema is a caller error rather than a legacy config to carry
/// forward — and the mode resolver reports `Shared` for it, meaning nothing
/// would be programmed.
pub fn directional_network_rejection(request: &ExecutionRequest) -> Option<&'static str> {
    let egress = request.policy.network_egress.as_ref();
    let ingress = request.policy.network_ingress.as_ref();
    if egress.is_none() && ingress.is_none() {
        return None;
    }

    if !uses_strict_network_contract(request) {
        return Some(BWRAP_DIRECTIONAL_PRE_0_8);
    }

    if let Some(ingress) = ingress {
        if ingress.default == NetworkAction::Allow {
            return Some(BWRAP_INGRESS_DEFAULT_ALLOW);
        }
        if ingress.host_loopback == NetworkAction::Allow {
            return Some(BWRAP_HOST_LOOPBACK_ALLOW);
        }
    }

    None
}

/// Rejection text for a directional section on a pre-0.8 schema.
pub const BWRAP_DIRECTIONAL_PRE_0_8: &str =
    "Bubblewrap: network.egress/network.ingress require schema 0.9.0-alpha or later. \
     Earlier schemas run the sandbox in the host network namespace, where the \
     directional posture would be accepted and then never programmed. Raise the \
     config's version field, or express the policy with defaultPolicy, \
     allowedHosts and blockedHosts.";

/// Rejection text for an inbound-accepting directional posture.
pub const BWRAP_INGRESS_DEFAULT_ALLOW: &str =
    "Bubblewrap: network.ingress.default='allow' is not supported. The sandbox runs in a \
     private network namespace reached through slirp, which has no route in until a host \
     port is forwarded to it, and the schema carries no port list to forward. A listener \
     inside the sandbox is reachable from the sandbox only. Use \
     network.ingress.default='deny'.";

/// Rejection text for an inbound-accepting host-loopback posture.
pub const BWRAP_HOST_LOOPBACK_ALLOW: &str =
    "Bubblewrap: network.ingress.hostLoopback='allow' is not supported. The sandbox's \
     loopback belongs to its own network namespace and is not the host's, so the host \
     cannot dial a sandbox listener and nothing bridges the two. Use \
     network.ingress.hostLoopback='deny'.";

/// Reject host lists that no mechanism will apply, on schema 0.8+.
///
/// Host lists suppress the `Isolated` mode, so a mode that does not apply them
/// leaves the sandbox on the host namespace unfiltered. This is the only layer
/// that checks it: the parser validates structure, and every caller — CLI,
/// SDK, FFI, or a Rust caller handing `mxc_engine` a hand-built
/// `ExecutionRequest` — reaches a runner, while only JSON configs reach the
/// parser.
pub fn unenforced_host_rules_rejection(request: &ExecutionRequest) -> Option<&'static str> {
    if !uses_strict_network_contract(request) {
        return None;
    }
    let has_host_rules =
        !request.policy.allowed_hosts.is_empty() || !request.policy.blocked_hosts.is_empty();
    let mode =
        ResolvedNetworkMode::from_request(request, request.policy.network_proxy.is_enabled());

    (has_host_rules && !mode.enforces_host_rules()).then_some(BWRAP_UNENFORCED_HOST_RULES)
}

/// Rejection text for an external proxy combined with host lists.
///
/// Duplicated (verbatim) from the parser's pre-existing check of the same
/// combination. The parser keeps its copy for JSON configs; this one covers
/// callers who hand a runner an `ExecutionRequest` directly.
pub const BWRAP_EXTERNAL_PROXY_HOST_RULES: &str =
    "Bubblewrap: an external network.proxy (url/localhost) cannot be combined with \
     allowedHosts, blockedHosts, or defaultPolicy='block'. The external proxy is expected to \
     enforce its own host policy; MXC does not forward host lists to it. Use \
     'network.proxy.builtinTestServer: true' (testing only) for MXC-enforced host filtering, \
     or remove the host policy.";

/// Rejection text for a proxy combined with firewall enforcement.
///
/// Duplicated (verbatim) from the parser's pre-existing check of the same
/// combination, exactly as [`BWRAP_EXTERNAL_PROXY_HOST_RULES`] is. The parser
/// keeps its copy for JSON configs; this one covers callers who hand a runner
/// an `ExecutionRequest` directly. Keep the two strings identical.
pub const BWRAP_PROXY_WITH_FIREWALL: &str = "Bubblewrap: network.proxy cannot be combined with \
     network.enforcementMode='firewall' or 'both'. The cooperative \
     env-var proxy enforces hosts at the proxy layer; iptables-based \
     enforcement requires privilege and is mutually exclusive.";

/// Rejection text for a proxy combined with a directional egress rule set.
///
/// Distinct from [`BWRAP_EXTERNAL_PROXY_HOST_RULES`] because the two describe
/// different mistakes: that one names the legacy host-list fields, none of
/// which a directional caller has set. A caller told to remove `allowedHosts`
/// when they wrote `network.egress` would have nothing to act on.
pub const BWRAP_PROXY_DIRECTIONAL_EGRESS: &str =
    "Bubblewrap: network.proxy cannot be combined with a directional network.egress rule set. \
     A proxy resolves to proxy-only egress, whose chain opens the proxy endpoint alone and \
     never reads network.egress, so the rules would be dropped in silence. Use \
     network.egress.default='deny' with no allow/deny rules (the proxy-only posture), or \
     remove network.proxy and express the policy with network.egress.";

/// Validate-time twin of the parser's external-proxy host-list rejection.
///
/// MXC applies the host lists itself only for the builtin test proxy; an
/// operator-supplied proxy is never handed them, so accepting the combination
/// would drop the requested policy silently. Not schema-gated, matching the
/// parser.
pub fn external_proxy_host_rules_rejection(request: &ExecutionRequest) -> Option<&'static str> {
    let proxy = &request.policy.network_proxy;
    if !proxy.is_enabled() {
        return None;
    }

    // Checked ahead of the builtin exemption because it binds to *every*
    // enabled proxy. Both proxy flavors resolve to `ResolvedNetworkMode::
    // ProxyOnly`, whose chain comes from `EgressPlan::for_proxy` and never
    // reads `network_egress` -- so a directional rule set is dropped in
    // silence either way. The exemption below is about host *lists*, which
    // MXC does apply itself for the builtin proxy; nothing applies directional
    // rules under a proxy, so the exemption must not extend to them.
    //
    // JSON configs cannot reach this (the parser constrains the same posture),
    // which leaves programmatic callers: precisely who this twin exists for.
    let directional_conflicts = request
        .policy
        .network_egress
        .as_ref()
        .is_some_and(|egress| {
            egress.default != NetworkAction::Deny
                || !egress.allow.is_empty()
                || !egress.deny.is_empty()
        });
    if directional_conflicts {
        return Some(BWRAP_PROXY_DIRECTIONAL_EGRESS);
    }

    if proxy.builtin_test_server {
        return None;
    }
    let has_host_rules =
        !request.policy.allowed_hosts.is_empty() || !request.policy.blocked_hosts.is_empty();
    // `default_network_policy` is a legacy-shape field: the directional path
    // never writes it, so it sits at its `Block` default whether or not the
    // caller said anything about egress. Reading it as a caller statement
    // would refuse every directional runtime proxy -- the one posture the
    // parser already constrains to `egress.default='deny'` with no direct
    // rules, which *is* proxy-only egress and carries no host lists that could
    // be silently dropped.
    let legacy_shape = !is_directional(&request.policy);
    let conflicts = has_host_rules
        || (legacy_shape && request.policy.default_network_policy == NetworkPolicy::Block);

    conflicts.then_some(BWRAP_EXTERNAL_PROXY_HOST_RULES)
}

/// Validate-time twin of the parser's proxy + firewall-enforcement rejection.
///
/// [`ResolvedNetworkMode::from_request`] tests the proxy first and returns
/// `ProxyOnly`, so `enforcementMode` is never consulted on that path: without
/// this gate the runner silently discards an explicitly-set, security-relevant
/// field. Public SDK policy entry points validate through the exact parser:
/// `mxc_sdk::v1::build_request*` constructs an exact `1.0.0` Rust contract
/// value and normalizes it through `config_parser`, and `SandboxRequest`'s
/// inner `ExecutionRequest` is `pub(crate)`. This gate also protects direct
/// engine callers holding an `ExecutionRequest`. Not schema-gated, matching
/// the parser.
pub fn proxy_with_firewall_rejection(request: &ExecutionRequest) -> Option<&'static str> {
    let conflicts = request.policy.network_proxy.is_enabled()
        && matches!(
            request.policy.network_enforcement_mode,
            NetworkEnforcementMode::Firewall | NetworkEnforcementMode::Both
        );
    conflicts.then_some(BWRAP_PROXY_WITH_FIREWALL)
}

/// Validate-time twin of [`local_network_diagnostic`]: the same mismatch, but
/// only for schemas that reject it rather than warn.
///
/// Keys off proxy *enablement* rather than a resolved address because
/// `builtinTestServer` has no address until the proxy starts, which is after
/// validation.
///
/// Rejects on the value, not on whether the caller wrote the field. `false` is
/// the schema default *and* a deny, so an omitted `allowLocalNetwork` still
/// asks for inbound denial. Callers wanting the shared namespace acknowledge
/// the exposure with `allowLocalNetwork=true`. The warning path keeps the
/// looser check: it only logs.
pub fn local_network_rejection(request: &ExecutionRequest) -> Option<&'static str> {
    if !uses_strict_network_contract(request) {
        return None;
    }
    let mode =
        ResolvedNetworkMode::from_request(request, request.policy.network_proxy.is_enabled());
    local_network_diagnostic_for_mode(request, mode)
}

/// Describe a `network.allowLocalNetwork` setting Bubblewrap cannot honor, or
/// `None` when the sandbox's namespace already matches the request.
///
/// `allowLocalNetwork` governs whether the sandboxed process may bind/listen on
/// local IPs and accept **inbound** connections (it says nothing about outbound
/// reachability of local addresses — that is `defaultPolicy`/`allowedHosts`).
/// Bubblewrap has no inbound-only primitive: the sandbox either gets a private
/// network namespace or shares the host's, and neither can be narrowed further.
/// Unprivileged bwrap has no veth to scope iptables to, and seccomp cannot
/// dereference the `sockaddr` passed to `bind`, so an AF_INET-only filter is not
/// expressible. The namespace choice therefore decides the outcome, and this
/// returns the mismatch so the runner can say so out loud rather than dropping
/// the field silently.
///
/// The private-namespace arm satisfies `false` only at the sandbox boundary:
/// bwrap brings `lo` up inside the new namespace, so sandbox processes can still
/// bind and connect to each other over their own loopback. That stays inside the
/// caller's trust boundary — those processes already share pipes, files and the
/// mount namespace — so it is not warned about.
pub fn local_network_diagnostic(
    request: &ExecutionRequest,
    proxy_address: Option<&ProxyAddress>,
) -> Option<&'static str> {
    let network_mode = ResolvedNetworkMode::from_request(request, proxy_address.is_some());
    local_network_diagnostic_for_mode(request, network_mode)
}

/// Describe an inbound-policy mismatch using a previously resolved mode.
///
/// The text carries no severity prefix so it can serve both the pre-0.8
/// warning and the 0.8+ rejection; callers add "WARNING: " when logging.
pub(crate) fn local_network_diagnostic_for_mode(
    request: &ExecutionRequest,
    network_mode: ResolvedNetworkMode,
) -> Option<&'static str> {
    match (
        request.policy.allow_local_network,
        network_mode.uses_private_netns(),
    ) {
        (false, false) => Some(BWRAP_LOCAL_NETWORK_SHARED_NS),
        (true, true) => Some(BWRAP_LOCAL_NETWORK_PRIVATE_NS),
        _ => None,
    }
}

/// `PATH` for the sandboxed child, from schema 0.9.
///
/// `--clearenv` leaves the child with no `PATH`, so resolution fell through to
/// the shell's compiled-in default. That value varies: it matches this one on
/// Debian and Ubuntu, so nothing changes there, but on RHEL it omitted the
/// `sbin` directories. Setting it explicitly removes the dependency.
const DEFAULT_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";

/// `TERM` for the sandboxed child. Curses-based tools error out when it is
/// unset; it does not make a tool believe it has a terminal, which is `isatty`.
const DEFAULT_TERM: &str = "xterm-256color";

/// The directory the child is actually started in, if any.
///
/// [`build_args_classified_with_mode`] emits `--chdir` for exactly this value
/// and [`default_env`] points `HOME` at it, so the two cannot name different
/// directories — a relative `--chdir` would otherwise resolve against whatever
/// cwd bwrap carried into the namespace, leaving `HOME` naming a different
/// directory than the one the child landed in. Normalizing against the sandbox
/// root is what makes them agree, so it is gated on the schema that introduced
/// `HOME`; below 0.9 the caller's spelling reaches `--chdir` untouched.
///
/// A policy grant is deliberately *not* consulted: bwrap enters one only when
/// `process.cwd` names it, so treating it as the start directory would put
/// `HOME` somewhere the child never went.
fn start_directory(request: &ExecutionRequest) -> Option<String> {
    Some(request.working_directory.as_str())
        .filter(|dir| !dir.is_empty())
        .map(|dir| {
            if request.supplies_default_env() {
                crate::mxc_common::models::sandbox_absolute_path(dir)
            } else {
                dir.to_string()
            }
        })
}

/// The default environment: `PATH`, `TERM`, and — when one resolves — `HOME`.
///
/// `HOME` names the directory the child actually runs in, so it is a path the
/// sandbox can reach rather than the launching user's real home, which the
/// bind-mount policy would not have made visible. With no start directory it
/// is left unset: policy mounts are emitted after `--tmpfs /tmp` and therefore
/// win, so a `/tmp` fallback could be the host's shared directory rather than
/// a private one.
fn default_env(request: &ExecutionRequest) -> Vec<(String, String)> {
    let mut entries = vec![("PATH".to_string(), DEFAULT_PATH.to_string())];

    if let Some(home) = start_directory(request) {
        entries.push(("HOME".to_string(), home));
    }

    entries.push(("TERM".to_string(), DEFAULT_TERM.to_string()));
    entries
}

/// The entries the child should get, as `KEY=VALUE` strings.
///
/// The state dispatch and overlay merge are shared; see
/// [`crate::mxc_common::default_env::resolve_env`]. Below 0.9 the caller's entries are
/// passed through untouched.
fn resolved_env(request: &ExecutionRequest) -> Vec<String> {
    crate::mxc_common::default_env::resolve_env(request, || default_env(request))
}

/// Build the complete `bwrap` argument list, masking **every** denied path as a
/// directory (`--tmpfs`).
///
/// This is the pure, classification-free entry point: it performs no filesystem
/// I/O and so stays unit-testable on every host. Unit tests and any caller that
/// has not stat'd the denied paths use it. The Bubblewrap runner uses
/// [`build_args_classified`] instead. See
/// docs/bwrap-support/bubblewrap-backend.md for how denied paths are masked.
pub fn build_args(request: &ExecutionRequest, proxy_address: Option<&ProxyAddress>) -> Vec<String> {
    build_args_classified(request, proxy_address, &HashSet::new())
}

/// Build the complete argument list for `bwrap` from the given request.
///
/// The returned vector does **not** include the `bwrap` binary name itself —
/// callers pass it to `Command::new("bwrap").args(&args)`.
///
/// `proxy_address` is the proxy endpoint visible from the sandbox (if the
/// request has `network.proxy` configured).
/// When `Some`, the builder:
/// - emits `--unshare-net` and expects the runner to provide `--userns FD`
///   plus slirp-backed connectivity,
/// - strips any caller-supplied `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` /
///   `FTP_PROXY` / `NO_PROXY` entries from `request.env`,
/// - emits `--setenv` for the proxy keys (all but `NO_PROXY`) pointing at the
///   proxy URL.
///
/// `denied_files` is the set of `deniedPaths` entries the runner classified as
/// files (built by `symlink_metadata`-probing each denied path, so this function
/// performs no filesystem I/O and stays unit-testable on every host). See
/// docs/bwrap-support/bubblewrap-backend.md for how denied paths are masked.
pub fn build_args_classified(
    request: &ExecutionRequest,
    proxy_address: Option<&ProxyAddress>,
    denied_files: &HashSet<String>,
) -> Vec<String> {
    let network_mode = ResolvedNetworkMode::from_request(request, proxy_address.is_some());
    build_args_classified_with_mode(request, proxy_address, denied_files, network_mode)
}

/// Build Bubblewrap arguments using a previously resolved network mode.
pub(crate) fn build_args_classified_with_mode(
    request: &ExecutionRequest,
    proxy_address: Option<&ProxyAddress>,
    denied_files: &HashSet<String>,
    network_mode: ResolvedNetworkMode,
) -> Vec<String> {
    // -- Namespace isolation (all unshared by default) ---------------------
    let mut args = Vec::new();
    if !network_mode.uses_external_userns() {
        args.push("--unshare-user".into());
    }
    // SECURITY: proxy mode joins the supervisor's user namespace rather than
    // unsharing, leaving that descriptor open in the workload. It is inert only
    // because bwrap empties the capability sets before exec — asserted by
    // run_bwrap_network_proxy_test.sh, explained in
    // docs/bwrap-support/bubblewrap-backend.md.
    args.extend(
        ["--unshare-pid", "--unshare-ipc", "--unshare-uts"]
            .into_iter()
            .map(String::from),
    );

    // `--unshare-pid` alone does not make killing our `bwrap` handle tear the
    // sandbox down: bwrap forks, so pid 1 of the new namespace is that child,
    // not the process we spawned. Without this flag a backgrounded descendant
    // outlives a timeout kill and keeps running after `run_teardown()` has
    // removed the network enforcement it was sandboxed by.
    args.push("--die-with-parent".into());

    // Network: full-block and proxy modes use a private namespace. Proxy mode
    // receives rootless connectivity from the runner's slirp supervisor.
    // Per-host firewall mode continues to share the host namespace.
    if network_mode.uses_private_netns() {
        args.push("--unshare-net".into());
    }

    // -- Base filesystem (deny-by-default; see `BASELINE_RO_BIND_PATHS`) ---
    // bwrap applies mounts in order; later mounts at the same path shadow
    // earlier ones. We therefore lay the baseline + standard virtual
    // filesystems down first, then apply user-supplied policy mounts last
    // so they always win when paths overlap (e.g. `readwritePaths:
    // ["/tmp/workspace"]` must beat the standard `--tmpfs /tmp`).
    for path in BASELINE_RO_BIND_PATHS {
        args.extend(["--ro-bind-try".into(), (*path).into(), (*path).into()]);
    }

    // Recreate the standard `/var/run -> /run` compatibility symlink. Some
    // distros (older RHEL/CentOS-era, some container images) write
    // `/etc/resolv.conf` as a symlink routed through `/var/run/...` (e.g.
    // `/var/run/NetworkManager/resolv.conf`). We never mount `/var`, so that
    // intermediate path would dangle inside the sandbox and DNS would
    // silently fail. The symlink rescues the whole `/var/run/...` family and
    // pulls no host `/var` contents in (bwrap synthesises an empty `/var`).
    args.extend(["--symlink".into(), "/run".into(), "/var/run".into()]);

    // Standard virtual filesystems (applied before policy mounts so policy
    // paths under /dev, /proc, or /tmp survive).
    args.extend(["--dev".into(), "/dev".into()]);
    args.extend(["--proc".into(), "/proc".into()]);
    args.extend(["--tmpfs".into(), "/tmp".into()]);

    // Policy mounts, emitted in most-specific-path-wins order so a deeper path
    // always overrides a shallower ancestor with a different intent regardless
    // of which policy list it came from (e.g. `readwritePaths: ["/data/secrets"]`
    // must survive `deniedPaths: ["/data"]`). bwrap applies mounts in order and
    // the last at a path wins, so walking the specificity-ordered list last —
    // after the baseline + virtual filesystems above — gives the intended
    // precedence. `resolve_mount_order` assumes object normalization already ran
    // (it does, in the runner before `build_args`), so exact same-path conflicts
    // are already collapsed to the strictest intent.
    for mount in crate::mxc_common::filesystem_resolve::resolve_mount_order(&request.policy) {
        match mount.intent {
            // Read-write: override the base ro-bind and any standard mount.
            FsIntent::ReadWrite => {
                args.extend(["--bind".into(), mount.path.clone(), mount.path.clone()]);
            }
            // Read-only: already covered by the base ro-bind, but listed
            // explicitly so the intent is clear and it overrides any rw parent.
            FsIntent::ReadOnly => {
                args.extend(["--ro-bind".into(), mount.path.clone(), mount.path.clone()]);
            }
            FsIntent::Denied => {
                if denied_files.contains(&mount.path) {
                    args.extend(["--ro-bind".into(), "/dev/null".into(), mount.path.clone()]);
                } else {
                    args.extend(["--tmpfs".into(), mount.path.clone()]);
                }
            }
        }
    }

    // -- Working directory -------------------------------------------------
    if let Some(dir) = start_directory(request) {
        args.extend(["--chdir".into(), dir]);
    }

    // -- Environment -------------------------------------------------------
    // Clear the inherited environment, then set only the vars from the
    // request so the sandbox has a minimal, predictable environment.
    args.push("--clearenv".into());
    for env_str in resolved_env(request) {
        // An entry with no `=` names no variable, so it is dropped here too.
        if let Some((key, value)) = env_str.split_once('=') {
            // When the proxy is active, drop any caller-supplied proxy env
            // entries so they cannot override the values we set below.
            if proxy_address.is_some() && is_managed_proxy_key(key) {
                continue;
            }
            args.extend(["--setenv".into(), key.into(), value.into()]);
        }
    }

    // -- Network proxy env vars -------------------------------------------
    // Cooperative env-var proxying: well-behaved tools (curl, requests,
    // etc.) honor these and route through the proxy where allow / block
    // enforcement happens. Tools that bypass these variables (raw sockets)
    // are NOT enforced -- this is a documented limitation of the
    // unprivileged proxy model.
    //
    // We deliberately do NOT set NO_PROXY here. Exempting any destination
    // would let cooperating clients bypass the configured proxy policy.
    if let Some(addr) = proxy_address {
        let url = addr.to_url();
        for key in PROXY_SET_KEYS {
            args.extend(["--setenv".into(), (*key).into(), url.clone()]);
        }
    }

    // -- Command -----------------------------------------------------------
    args.extend(COMMAND_TAIL.iter().map(|arg| arg.to_string()));
    args.push(request.script_code.clone());

    args
}

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

    fn base_request() -> ExecutionRequest {
        ExecutionRequest {
            script_code: "echo hello".into(),
            working_directory: "/home/user".into(),
            ..Default::default()
        }
    }

    /// `process.env` resolution, which schema 0.9 gave a default block.
    mod env {
        use super::*;
        use crate::mxc_common::models::DefaultEnvCompatibility;

        fn request(compatibility: DefaultEnvCompatibility) -> ExecutionRequest {
            ExecutionRequest {
                default_env_compatibility: compatibility,
                ..Default::default()
            }
        }

        fn value<'a>(entries: &'a [String], key: &str) -> Option<&'a str> {
            entries
                .iter()
                .find_map(|kv| kv.strip_prefix(&format!("{key}=")))
        }

        /// A direct typed SDK request that named no contract takes the current
        /// behavior.
        #[test]
        fn a_direct_sdk_request_gets_the_default_block() {
            let r = ExecutionRequest::default();
            assert_eq!(value(&resolved_env(&r), "PATH"), Some(DEFAULT_PATH));
        }

        #[test]
        fn an_omitted_env_gets_the_default_block() {
            let mut r = request(DefaultEnvCompatibility::DefaultBlock);
            r.env = None;
            r.working_directory = "/workspace".into();
            let entries = resolved_env(&r);
            assert_eq!(value(&entries, "PATH"), Some(DEFAULT_PATH));
            assert_eq!(value(&entries, "HOME"), Some("/workspace"));
            assert_eq!(value(&entries, "TERM"), Some(DEFAULT_TERM));
        }

        #[test]
        fn the_default_path_covers_sbin() {
            // The RHEL failure this default exists to prevent.
            for dir in ["/usr/sbin", "/sbin", "/usr/bin", "/bin"] {
                assert!(
                    DEFAULT_PATH.split(':').any(|entry| entry == dir),
                    "{dir} must be on the default PATH"
                );
            }
        }

        #[test]
        fn an_explicitly_empty_env_stays_empty() {
            let mut r = request(DefaultEnvCompatibility::DefaultBlock);
            r.env = Some(vec![]);
            assert!(resolved_env(&r).is_empty());
        }

        #[test]
        fn a_supplied_env_is_used_verbatim() {
            let mut r = request(DefaultEnvCompatibility::DefaultBlock);
            r.env = Some(vec!["FOO=bar".into()]);
            assert_eq!(resolved_env(&r), vec!["FOO=bar".to_string()]);
        }

        #[test]
        fn inherit_default_env_layers_over_the_default_block() {
            let mut r = request(DefaultEnvCompatibility::DefaultBlock);
            r.env = Some(vec!["FOO=bar".into(), "PATH=/only/mine".into()]);
            r.inherit_default_env = true;
            let entries = resolved_env(&r);

            assert_eq!(value(&entries, "FOO"), Some("bar"));
            assert_eq!(value(&entries, "TERM"), Some(DEFAULT_TERM));
            // Replaced, not appended: --setenv twice for one name is
            // order-dependent.
            assert_eq!(value(&entries, "PATH"), Some("/only/mine"));
            assert_eq!(
                entries.iter().filter(|kv| kv.starts_with("PATH=")).count(),
                1
            );
        }

        #[test]
        fn home_follows_the_directory_the_child_starts_in() {
            let mut r = request(DefaultEnvCompatibility::DefaultBlock);
            r.env = None;
            r.working_directory = "/workspace".into();
            assert_eq!(value(&resolved_env(&r), "HOME"), Some("/workspace"));
        }

        #[test]

        fn a_caller_entry_without_a_value_reaches_no_setenv() {
            for inherit in [false, true] {
                let mut r = base_request();
                r.default_env_compatibility = DefaultEnvCompatibility::DefaultBlock;
                r.env = Some(vec!["FEATURE_FLAG".into(), "FOO=bar".into()]);
                r.inherit_default_env = inherit;
                let args = build_args(&r, None);

                assert!(
                    !args.iter().any(|a| a == "FEATURE_FLAG"),
                    "a valueless entry must not be set (inherit {inherit}): {args:?}"
                );
                assert!(
                    args.windows(3)
                        .any(|w| w[0] == "--setenv" && w[1] == "FOO" && w[2] == "bar"),
                    "the well-formed entry must survive (inherit {inherit}): {args:?}"
                );
            }
        }

        /// A policy grant is not a working directory: bwrap emits `--chdir`
        /// only for `process.cwd`, so a granted directory the child never
        /// enters must not become its `HOME`.
        #[test]
        fn a_policy_grant_alone_does_not_become_home() {
            let mut r = request(DefaultEnvCompatibility::DefaultBlock);
            r.env = None;
            r.working_directory = String::new();
            // A real directory, so the shared resolver's `is_dir` probe would
            // accept it if `HOME` consulted the policy.
            r.policy.readwrite_paths = vec![std::env::temp_dir().display().to_string()];

            assert_eq!(value(&resolved_env(&r), "HOME"), None);
            let args = build_args(&r, None);
            assert!(
                !args.iter().any(|a| a == "--chdir"),
                "a policy grant must not chdir the child: {args:?}"
            );
        }

        /// `HOME` and `--chdir` come from one resolution, so they cannot name
        /// different directories.
        #[test]
        fn home_and_chdir_agree() {
            for cwd in ["", "/workspace", "work", "./work", "a/../b", "/x/../y/./z"] {
                let mut r = request(DefaultEnvCompatibility::DefaultBlock);
                r.env = None;
                r.working_directory = cwd.into();
                let args = build_args(&r, None);

                let chdir = args
                    .windows(2)
                    .find(|w| w[0] == "--chdir")
                    .map(|w| w[1].clone());
                let home = value(&resolved_env(&r), "HOME").map(str::to_string);
                assert_eq!(
                    home, chdir,
                    "HOME must name the directory the child starts in (cwd {cwd:?})"
                );
            }
        }

        #[test]
        fn a_relative_start_directory_is_anchored_to_the_sandbox_root() {
            for (cwd, expected) in [
                ("work", "/work"),
                ("./work", "/work"),
                ("a/../b", "/b"),
                ("/x/../y/./z", "/y/z"),
            ] {
                let mut r = request(DefaultEnvCompatibility::DefaultBlock);
                r.env = None;
                r.working_directory = cwd.into();
                assert_eq!(value(&resolved_env(&r), "HOME"), Some(expected));
            }
        }

        #[test]
        fn the_default_block_reaches_the_argument_list() {
            let mut r = base_request();
            r.default_env_compatibility = DefaultEnvCompatibility::DefaultBlock;
            r.env = None;
            let args = build_args(&r, None);

            let pos = args
                .windows(3)
                .position(|w| w[0] == "--setenv" && w[1] == "PATH" && w[2] == DEFAULT_PATH);
            assert!(pos.is_some(), "PATH must be set via --setenv: {args:?}");
            let clearenv = args.iter().position(|a| a == "--clearenv").unwrap();
            assert!(
                pos.unwrap() > clearenv,
                "--setenv must follow --clearenv, else it is wiped"
            );
        }
    }

    #[test]
    fn the_schema_gate_does_not_apply_when_no_proxy_is_active() {
        // Without an active proxy the version is irrelevant — a 0.8 request
        // still classifies on policy alone (default policy is block, so this
        // lands on the plain isolated namespace, not the proxy one).
        let request = ExecutionRequest {
            network_enforcement_compatibility: NetworkEnforcementCompatibility::Strict,
            ..base_request()
        };
        assert_eq!(
            ResolvedNetworkMode::from_request(&request, false),
            ResolvedNetworkMode::Isolated
        );
    }

    #[test]
    fn basic_args_contain_namespace_flags() {
        let args = build_args(&base_request(), None);
        assert!(args.contains(&"--unshare-user".to_string()));
        assert!(args.contains(&"--unshare-pid".to_string()));
        assert!(args.contains(&"--unshare-ipc".to_string()));
        assert!(args.contains(&"--unshare-uts".to_string()));
    }

    /// Dropping this flag silently reintroduces a real leak: a backgrounded
    /// descendant survives the timeout kill and keeps running after teardown
    /// has removed its network enforcement.
    #[test]
    fn basic_args_request_die_with_parent() {
        let args = build_args(&base_request(), None);
        assert!(args.contains(&"--die-with-parent".to_string()));
    }

    struct NetworkPlanCase {
        name: &'static str,
        compatibility: NetworkEnforcementCompatibility,
        default_policy: NetworkPolicy,
        enforcement_mode: NetworkEnforcementMode,
        allowed_hosts: &'static [&'static str],
        blocked_hosts: &'static [&'static str],
        proxy_active: bool,
        expected: ResolvedNetworkMode,
    }

    #[test]
    fn classifies_current_network_policy_modes() {
        let cases = [
            NetworkPlanCase {
                name: "default block is isolated",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Block,
                enforcement_mode: NetworkEnforcementMode::Capabilities,
                allowed_hosts: &[],
                blocked_hosts: &[],
                proxy_active: false,
                expected: ResolvedNetworkMode::Isolated,
            },
            NetworkPlanCase {
                name: "default allow is shared",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Allow,
                enforcement_mode: NetworkEnforcementMode::Capabilities,
                allowed_hosts: &[],
                blocked_hosts: &[],
                proxy_active: false,
                expected: ResolvedNetworkMode::Shared,
            },
            NetworkPlanCase {
                name: "firewall allow rules are enforced in-namespace at 0.8",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Block,
                enforcement_mode: NetworkEnforcementMode::Firewall,
                allowed_hosts: &["203.0.113.7"],
                blocked_hosts: &[],
                proxy_active: false,
                expected: ResolvedNetworkMode::FirewallEnforced,
            },
            NetworkPlanCase {
                name: "firewall allow rules are enforced for host rules",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Block,
                enforcement_mode: NetworkEnforcementMode::Firewall,
                allowed_hosts: &["example.com"],
                blocked_hosts: &[],
                proxy_active: false,
                expected: ResolvedNetworkMode::FirewallEnforced,
            },
            NetworkPlanCase {
                name: "combined enforcement block rules are enforced at 0.8",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Allow,
                enforcement_mode: NetworkEnforcementMode::Both,
                allowed_hosts: &[],
                blocked_hosts: &["198.51.100.9"],
                proxy_active: false,
                expected: ResolvedNetworkMode::FirewallEnforced,
            },
            NetworkPlanCase {
                name: "combined enforcement block rules are enforced for host rules",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Allow,
                enforcement_mode: NetworkEnforcementMode::Both,
                allowed_hosts: &[],
                blocked_hosts: &["example.com"],
                proxy_active: false,
                expected: ResolvedNetworkMode::FirewallEnforced,
            },
            NetworkPlanCase {
                name: "capabilities mode with host rules stays shared",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Block,
                enforcement_mode: NetworkEnforcementMode::Capabilities,
                allowed_hosts: &["example.com"],
                blocked_hosts: &[],
                proxy_active: false,
                expected: ResolvedNetworkMode::Shared,
            },
            NetworkPlanCase {
                name: "proxy takes precedence over isolation",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Block,
                enforcement_mode: NetworkEnforcementMode::Capabilities,
                allowed_hosts: &[],
                blocked_hosts: &[],
                proxy_active: true,
                expected: ResolvedNetworkMode::ProxyOnly,
            },
            NetworkPlanCase {
                name: "proxy takes precedence over firewall filtering",
                compatibility: NetworkEnforcementCompatibility::Strict,
                default_policy: NetworkPolicy::Allow,
                enforcement_mode: NetworkEnforcementMode::Firewall,
                allowed_hosts: &[],
                blocked_hosts: &["example.com"],
                proxy_active: true,
                expected: ResolvedNetworkMode::ProxyOnly,
            },
        ];

        for case in cases {
            let mut request = ExecutionRequest {
                network_enforcement_compatibility: case.compatibility,
                ..Default::default()
            };
            request.policy.default_network_policy = case.default_policy;
            request.policy.network_enforcement_mode = case.enforcement_mode;
            request.policy.allowed_hosts = case
                .allowed_hosts
                .iter()
                .map(|host| (*host).into())
                .collect();
            request.policy.blocked_hosts = case
                .blocked_hosts
                .iter()
                .map(|host| (*host).into())
                .collect();

            let actual = ResolvedNetworkMode::from_request(&request, case.proxy_active);
            assert_eq!(actual, case.expected, "{}", case.name);
        }
    }

    #[test]
    fn resolved_network_mode_capabilities_match_current_behavior() {
        assert!(ResolvedNetworkMode::Isolated.uses_private_netns());
        assert!(ResolvedNetworkMode::ProxyOnly.uses_private_netns());
        assert!(ResolvedNetworkMode::ProxyOnly.uses_external_userns());
        assert!(!ResolvedNetworkMode::Isolated.uses_external_userns());
        assert!(!ResolvedNetworkMode::LegacyProxy.uses_private_netns());
        assert!(ResolvedNetworkMode::FirewallFiltered.requires_host_firewall_manager());
        assert!(!ResolvedNetworkMode::Shared.requires_host_firewall_manager());
        // ProxyOnly enforces via in-netns rules, not the host manager.
        assert!(!ResolvedNetworkMode::ProxyOnly.requires_host_firewall_manager());
        // FirewallEnforced is the same shape as ProxyOnly minus the proxy: its
        // rules are programmed from inside the sandbox's own namespace, which
        // is the whole reason it filters where FirewallFiltered does not.
        assert!(ResolvedNetworkMode::FirewallEnforced.uses_private_netns());
        assert!(ResolvedNetworkMode::FirewallEnforced.uses_external_userns());
        assert!(!ResolvedNetworkMode::FirewallEnforced.requires_host_firewall_manager());
    }

    #[test]
    fn network_block_adds_unshare_net() {
        let mut r = base_request();
        r.policy.default_network_policy = NetworkPolicy::Block;
        let args = build_args(&r, None);
        assert!(args.contains(&"--unshare-net".to_string()));
    }

    #[test]
    fn network_allow_omits_unshare_net() {
        let mut r = base_request();
        r.policy.default_network_policy = NetworkPolicy::Allow;
        let args = build_args(&r, None);
        assert!(!args.contains(&"--unshare-net".to_string()));
    }

    #[test]
    fn network_block_with_host_rules_omits_unshare_net() {
        let mut r = base_request();
        r.policy.default_network_policy = NetworkPolicy::Block;
        r.policy.allowed_hosts = vec!["example.com".into()];
        let args = build_args(&r, None);
        assert!(
            !args.contains(&"--unshare-net".to_string()),
            "should omit --unshare-net when host rules require iptables"
        );
    }

    // ------- allowLocalNetwork diagnostic tests -------------------------

    #[test]
    fn local_network_denied_under_private_netns_is_not_warned() {
        // Default policy (block, no host lists, no proxy) applies
        // --unshare-net: nothing outside can reach in, so allowLocalNetwork=false
        // is satisfied at the sandbox boundary and needs no warning.
        let r = base_request();
        assert!(!r.policy.allow_local_network);
        assert!(local_network_diagnostic(&r, None).is_none());
    }

    #[test]
    fn local_network_denied_on_shared_netns_warns() {
        let mut r = base_request();
        r.policy.default_network_policy = NetworkPolicy::Allow;
        let msg = local_network_diagnostic(&r, None).expect("shared netns cannot honor the deny");
        assert!(msg.contains("allowLocalNetwork=false"));
    }

    #[test]
    fn local_network_denied_with_host_rules_warns() {
        let mut r = base_request();
        r.policy.blocked_hosts = vec!["evil.example.com".into()];
        assert!(local_network_diagnostic(&r, None).is_some());
    }

    #[test]
    fn local_network_denied_with_0_8_proxy_is_not_warned() {
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        let addr = ProxyAddress::new("127.0.0.1".into(), 8080);
        assert!(local_network_diagnostic(&r, Some(&addr)).is_none());
    }

    #[test]
    fn local_network_allowed_under_private_netns_warns() {
        let mut r = base_request();
        r.policy.allow_local_network = true;
        let msg = local_network_diagnostic(&r, None).expect("--unshare-net isolates the listener");
        assert!(msg.contains("allowLocalNetwork=true"));
    }

    #[test]
    fn local_network_allowed_on_shared_netns_is_honored() {
        let mut r = base_request();
        r.policy.allow_local_network = true;
        r.policy.default_network_policy = NetworkPolicy::Allow;
        assert!(local_network_diagnostic(&r, None).is_none());
    }

    // ------- allowLocalNetwork rejection (schema 0.8+) ------------------

    #[test]
    fn local_network_mismatch_is_rejected_at_0_8() {
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.default_network_policy = NetworkPolicy::Allow;
        let msg = local_network_rejection(&r).expect("shared netns cannot honor the deny");
        assert!(msg.contains("allowLocalNetwork=false"));
        // The text is reused verbatim as an error, so it must carry no severity.
        assert!(!msg.contains("WARNING"));
    }

    #[test]
    fn an_omitted_local_network_is_rejected_like_an_explicit_deny_at_0_8() {
        // `false` is the schema default *and* a deny, so silence still asks for
        // inbound denial.
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.default_network_policy = NetworkPolicy::Allow;
        assert!(!r.policy.allow_local_network, "default is the deny posture");
        let msg = local_network_rejection(&r).expect("an omitted deny is still a deny");
        assert!(msg.contains("allowLocalNetwork=false"));
        // Actionable only if it names the acknowledgment.
        assert!(msg.contains("allowLocalNetwork=true"));
    }

    #[test]
    fn acknowledged_local_network_exposure_is_accepted_at_0_8() {
        // The escape hatch from the rejection above.
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.default_network_policy = NetworkPolicy::Allow;
        r.policy.allow_local_network = true;
        assert!(local_network_rejection(&r).is_none());
    }

    #[test]
    fn honored_local_network_is_not_rejected_at_0_8() {
        // block + no host rules + no proxy is a private netns, which satisfies
        // allowLocalNetwork=false; nothing to reject.
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        assert!(local_network_rejection(&r).is_none());
    }

    #[test]
    fn builtin_test_server_counts_as_an_active_proxy_when_rejecting() {
        // builtinTestServer has no address until the proxy starts, which is
        // after validation, so the rejection keys off enablement instead.
        // defaultPolicy='allow' would be a shared namespace on its own, so the
        // rejection fires only if the proxy is recognized without an address.
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.default_network_policy = NetworkPolicy::Allow;
        r.policy.allow_local_network = true;
        assert!(local_network_rejection(&r).is_none());

        r.policy.network_proxy.builtin_test_server = true;
        assert!(r.policy.network_proxy.address.is_none());
        assert!(local_network_rejection(&r).is_some());
    }

    /// Without this twin a programmatic caller would sail past the parser's
    /// rejection and have the host policy dropped on the floor.
    #[test]
    fn external_proxy_with_host_rules_is_rejected() {
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.default_network_policy = NetworkPolicy::Allow;
        r.policy.network_proxy.address = Some(ProxyAddress::new("proxy.example.com".into(), 3128));
        assert!(external_proxy_host_rules_rejection(&r).is_none());

        r.policy.allowed_hosts = vec!["10.0.0.1".into()];
        let msg = external_proxy_host_rules_rejection(&r).expect("lists are never forwarded");
        assert!(msg.contains("external network.proxy"));

        r.policy.allowed_hosts.clear();
        r.policy.blocked_hosts = vec!["10.0.0.1".into()];
        assert!(external_proxy_host_rules_rejection(&r).is_some());

        r.policy.blocked_hosts.clear();
        r.policy.default_network_policy = NetworkPolicy::Block;
        assert!(external_proxy_host_rules_rejection(&r).is_some());
    }

    /// The builtin test proxy *is* handed the lists, so it must stay accepted.
    #[test]
    fn builtin_test_server_with_host_rules_is_not_rejected() {
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.network_proxy.builtin_test_server = true;
        r.policy.allowed_hosts = vec!["10.0.0.1".into()];
        assert!(external_proxy_host_rules_rejection(&r).is_none());
    }

    /// The parser refuses this pairing, and every public entry point reaches
    /// the runner through the parser -- so this pins the runner's own twin
    /// rather than a live bypass. Without it, `from_request` returns
    /// `ProxyOnly` before `enforcementMode` is read, and an in-tree caller
    /// holding an `ExecutionRequest` has the field dropped without a word.
    #[test]
    fn a_proxy_with_firewall_enforcement_is_rejected() {
        let mut r = base_request();
        r.policy.network_proxy.address = Some(ProxyAddress::new("127.0.0.1".into(), 3128));

        for mode in [
            NetworkEnforcementMode::Firewall,
            NetworkEnforcementMode::Both,
        ] {
            r.policy.network_enforcement_mode = mode.clone();
            assert_eq!(
                proxy_with_firewall_rejection(&r),
                Some(BWRAP_PROXY_WITH_FIREWALL),
                "{mode:?} must be refused with the parser's own message"
            );
        }

        // `is_enabled()` covers both proxy flavors, so the builtin refuses too.
        let mut builtin = base_request();
        builtin.policy.network_proxy.builtin_test_server = true;
        builtin.policy.network_enforcement_mode = NetworkEnforcementMode::Firewall;
        assert!(proxy_with_firewall_rejection(&builtin).is_some());

        // Negative controls: the default mode never invokes iptables, and the
        // gate must key on the proxy rather than on the mode alone.
        r.policy.network_enforcement_mode = NetworkEnforcementMode::Capabilities;
        assert!(proxy_with_firewall_rejection(&r).is_none());

        r.policy.network_enforcement_mode = NetworkEnforcementMode::Firewall;
        r.policy.network_proxy.address = None;
        assert!(proxy_with_firewall_rejection(&r).is_none());
    }

    /// A directional runtime proxy must not trip the legacy host-list guard.
    ///
    /// `default_network_policy` is a legacy-shape field the directional path
    /// never writes, so it sits at its `Block` default. Reading it as if the
    /// caller had asked for `defaultPolicy='block'` refused *every* directional
    /// runtime proxy -- which made `RUNTIME_PROXY` declarable but unusable,
    /// since the parser requires exactly `egress.default='deny'` with no direct
    /// rules for that field. The guard must still fire on the legacy shape, and
    /// still fire on real host lists in either shape, so all three are pinned
    /// here.
    #[test]
    fn a_directional_runtime_proxy_is_not_refused_by_the_legacy_host_list_guard() {
        use crate::mxc_common::models::{NetworkEgressPolicy, NetworkRule};

        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.network_proxy.address = Some(ProxyAddress::new("127.0.0.1".into(), 3128));

        // Legacy shape, defaulted `Block`: still refused, as before.
        r.policy.default_network_policy = NetworkPolicy::Block;
        assert!(
            external_proxy_host_rules_rejection(&r).is_some(),
            "the legacy shape must keep its refusal"
        );

        // Directional shape: the same defaulted `Block` is not a caller
        // statement, so it must no longer refuse.
        r.policy.network_egress = Some(NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });
        assert!(
            external_proxy_host_rules_rejection(&r).is_none(),
            "a directional proxy-only posture carries no host lists to drop"
        );

        // An ingress-only directional request is directional too: keying the
        // legacy discriminator on `egress` alone read the defaulted `Block` as
        // a caller statement and refused it.
        r.policy.network_egress = None;
        r.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy::default());
        assert!(
            external_proxy_host_rules_rejection(&r).is_none(),
            "an absent egress section is not a legacy `defaultPolicy='block'`"
        );
        r.policy.network_ingress = None;
        r.policy.network_egress = Some(NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });

        // Real host lists are still refused even on the directional shape --
        // the parser forbids the mix, so this only reaches a programmatic
        // caller, which is exactly who this twin exists for.
        r.policy.allowed_hosts = vec!["10.0.0.1".into()];
        assert!(
            external_proxy_host_rules_rejection(&r).is_some(),
            "host lists are never forwarded to an external proxy"
        );
        r.policy.allowed_hosts.clear();

        // Directional egress that is *not* the proxy-only posture must fail
        // closed. `ProxyOnly` builds its chain from `EgressPlan::for_proxy` and
        // never reads `network_egress`, so accepting these would drop the
        // requested rules in silence -- the same class of bug the host-list
        // half of this guard prevents.
        for unhonorable in [
            NetworkEgressPolicy {
                default: NetworkAction::Allow,
                ..Default::default()
            },
            NetworkEgressPolicy {
                default: NetworkAction::Deny,
                allow: vec![NetworkRule::default()],
                ..Default::default()
            },
            NetworkEgressPolicy {
                default: NetworkAction::Deny,
                deny: vec![NetworkRule::default()],
                ..Default::default()
            },
        ] {
            r.policy.network_egress = Some(unhonorable.clone());
            assert_eq!(
                external_proxy_host_rules_rejection(&r),
                Some(BWRAP_PROXY_DIRECTIONAL_EGRESS),
                "a directional rule set combined with a proxy would be dropped in silence"
            );

            // The builtin proxy takes the same chain from `for_proxy`, so the
            // exemption it enjoys for host *lists* -- which MXC applies itself
            // -- must not extend to directional rules, which nothing applies.
            let mut builtin = r.clone();
            builtin.policy.network_proxy.address = None;
            builtin.policy.network_proxy.builtin_test_server = true;
            assert_eq!(
                external_proxy_host_rules_rejection(&builtin),
                Some(BWRAP_PROXY_DIRECTIONAL_EGRESS),
                "the builtin proxy drops directional rules just as silently"
            );
        }

        // The builtin proxy keeps its host-list exemption: that is the whole
        // point of the flag, and narrowing it would be a behavior change.
        r.policy.network_egress = Some(NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });
        r.policy.network_proxy.address = None;
        r.policy.network_proxy.builtin_test_server = true;
        r.policy.allowed_hosts = vec!["10.0.0.1".into()];
        assert!(
            external_proxy_host_rules_rejection(&r).is_none(),
            "MXC enforces host lists itself for the builtin proxy"
        );
    }

    /// A directional egress policy must land on the one mode whose chains the
    /// sandbox actually traverses.
    ///
    /// This is the invariant that was broken: `ResolvedNetworkMode` classified
    /// from the legacy fields alone, which the directional parse path leaves at
    /// their defaults, so a rule-bearing policy resolved to `Isolated` and the
    /// runner — which builds the egress chain only under `FirewallEnforced`
    /// (bwrap_runner.rs) — never programmed the rules at all. Unit tests on
    /// `EgressPlan` cannot see this: they call the plan directly and so skip
    /// the gate that decides whether it is ever called.
    #[test]
    fn a_directional_rule_selects_the_namespace_whose_chain_is_programmed() {
        let request = directional_egress_request(
            NetworkEnforcementCompatibility::Strict,
            NetworkAction::Deny,
            true,
        );
        assert_eq!(
            ResolvedNetworkMode::from_request(&request, false),
            ResolvedNetworkMode::FirewallEnforced
        );
    }

    /// A ruleless directional policy still gets a namespace that honors the
    /// inbound posture. Only a bare deny degenerates to `--unshare-net`, where
    /// the absence of connectivity denies inbound for free; a bare allow keeps
    /// the private namespace and expresses itself as an accept-all chain,
    /// because the host namespace could not deny inbound at all.
    #[test]
    fn a_ruleless_directional_policy_still_honors_the_inbound_posture() {
        let denied = directional_egress_request(
            NetworkEnforcementCompatibility::Strict,
            NetworkAction::Deny,
            false,
        );
        assert_eq!(
            ResolvedNetworkMode::from_request(&denied, false),
            ResolvedNetworkMode::Isolated
        );

        let allowed = directional_egress_request(
            NetworkEnforcementCompatibility::Strict,
            NetworkAction::Allow,
            false,
        );
        let mode = ResolvedNetworkMode::from_request(&allowed, false);
        assert_eq!(mode, ResolvedNetworkMode::FirewallEnforced);
        assert!(mode.uses_private_netns());
    }

    /// No directional posture may share the host network namespace under the
    /// 0.8 contract: there is no inbound primitive there, and a defaulted
    /// `ingress.default='deny'` is indistinguishable from a written one, so
    /// `Shared` would silently drop the inbound half of the policy.
    #[test]
    fn no_directional_posture_shares_the_host_namespace() {
        for default in [NetworkAction::Allow, NetworkAction::Deny] {
            for with_rule in [false, true] {
                let request = directional_egress_request(
                    NetworkEnforcementCompatibility::Strict,
                    default,
                    with_rule,
                );
                let mode = ResolvedNetworkMode::from_request(&request, false);
                assert!(
                    mode.uses_private_netns(),
                    "default={default:?} with_rule={with_rule} resolved to {mode:?}"
                );
            }
        }
    }

    /// A proxy run is classified by the proxy arm before the directional one,
    /// so a directional section must not divert it out of `ProxyOnly` — that
    /// mode derives its chain from the resolved proxy endpoint.
    #[test]
    fn a_directional_section_does_not_divert_a_proxy_run() {
        let mut request = directional_egress_request(
            NetworkEnforcementCompatibility::Strict,
            NetworkAction::Deny,
            true,
        );
        request.policy.network_proxy.builtin_test_server = true;
        assert_eq!(
            ResolvedNetworkMode::from_request(&request, true),
            ResolvedNetworkMode::ProxyOnly
        );
    }

    /// An ingress-only directional request must not fall to the legacy arm.
    ///
    /// It did: keying on `network_egress` alone sent it there, where a leftover
    /// `defaultPolicy='allow'` resolved to `Shared` -- the host namespace, with
    /// no chain at all -- silently discarding both the ingress denial and the
    /// host-loopback drop.
    #[test]
    fn an_ingress_only_directional_request_still_gets_a_private_namespace() {
        use crate::mxc_common::models::{NetworkIngressPolicy, NetworkPolicy};

        let mut request = base_request();
        request.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        request.policy.network_ingress = Some(NetworkIngressPolicy::default());
        request.policy.default_network_policy = NetworkPolicy::Allow;

        let mode = ResolvedNetworkMode::from_request(&request, false);
        assert_ne!(
            mode,
            ResolvedNetworkMode::Shared,
            "the host namespace programs no chain, so the deny posture would be lost"
        );
        assert!(mode.uses_private_netns(), "{mode:?}");
    }

    /// The predicate is now shared by three call sites, so pin it directly:
    /// a per-site test would let one drift without failing the others.
    #[test]
    fn either_directional_section_alone_marks_the_policy_directional() {
        use crate::mxc_common::models::{NetworkEgressPolicy, NetworkIngressPolicy};

        let cases = [
            (None, None, false),
            (Some(NetworkEgressPolicy::default()), None, true),
            (None, Some(NetworkIngressPolicy::default()), true),
            (
                Some(NetworkEgressPolicy::default()),
                Some(NetworkIngressPolicy::default()),
                true,
            ),
        ];

        for (egress, ingress, expected) in cases {
            let policy = ContainerPolicy {
                network_egress: egress.clone(),
                network_ingress: ingress.clone(),
                ..Default::default()
            };
            assert_eq!(
                is_directional(&policy),
                expected,
                "egress={:?} ingress={:?}",
                egress.is_some(),
                ingress.is_some()
            );
        }
    }

    /// Build a directional request: no legacy network field is touched, which
    /// is exactly what the parser produces on that path.
    fn directional_egress_request(
        compatibility: NetworkEnforcementCompatibility,
        default: NetworkAction,
        with_rule: bool,
    ) -> ExecutionRequest {
        use crate::mxc_common::models::{NetworkEgressPolicy, NetworkRule};

        let mut request = base_request();
        request.network_enforcement_compatibility = compatibility;
        request.policy.network_egress = Some(NetworkEgressPolicy {
            default,
            allow: if with_rule {
                vec![NetworkRule::default()]
            } else {
                Vec::new()
            },
            deny: Vec::new(),
        });
        request
    }

    /// Build a directional request carrying both sections.
    fn directional_request(
        compatibility: NetworkEnforcementCompatibility,
        ingress_default: NetworkAction,
        host_loopback: NetworkAction,
    ) -> ExecutionRequest {
        use crate::mxc_common::models::{NetworkEgressPolicy, NetworkIngressPolicy};

        let mut request = base_request();
        request.network_enforcement_compatibility = compatibility;
        request.policy.network_egress = Some(NetworkEgressPolicy::default());
        request.policy.network_ingress = Some(NetworkIngressPolicy {
            default: ingress_default,
            host_loopback,
        });
        request
    }

    /// Slirp has no route into the namespace and the schema carries no port
    /// list to forward one, so an inbound-accepting posture cannot be honored.
    #[test]
    fn an_inbound_accepting_directional_posture_is_refused() {
        let request = directional_request(
            NetworkEnforcementCompatibility::Strict,
            NetworkAction::Allow,
            NetworkAction::Deny,
        );
        assert_eq!(
            directional_network_rejection(&request),
            Some(BWRAP_INGRESS_DEFAULT_ALLOW)
        );
    }

    /// The sandbox's loopback is its own namespace's, not the host's.
    #[test]
    fn a_host_loopback_accepting_posture_is_refused() {
        let request = directional_request(
            NetworkEnforcementCompatibility::Strict,
            NetworkAction::Deny,
            NetworkAction::Allow,
        );
        assert_eq!(
            directional_network_rejection(&request),
            Some(BWRAP_HOST_LOOPBACK_ALLOW)
        );
    }

    /// Positive control: the honorable posture must pass, or the gate above is
    /// just refusing every directional config.
    #[test]
    fn a_fully_denied_directional_posture_is_accepted() {
        let request = directional_request(
            NetworkEnforcementCompatibility::Strict,
            NetworkAction::Deny,
            NetworkAction::Deny,
        );
        assert_eq!(directional_network_rejection(&request), None);
    }

    /// A programmatic request with no directional sections does not reach
    /// the directional gate. Exact v0.9 JSON cannot supply these legacy fields.
    #[test]
    fn a_programmatic_request_without_directional_fields_bypasses_the_directional_gate() {
        let mut request = base_request();
        request.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        request.policy.default_network_policy = NetworkPolicy::Allow;
        request.policy.allowed_hosts = vec!["10.0.0.1".into()];
        assert_eq!(directional_network_rejection(&request), None);
    }

    /// Pin the strict mode resolver's namespace choice against explicit
    /// expectations. These are programmatic policies, not v0.9 JSON: the
    /// runner separately rejects combinations it cannot enforce.
    #[test]
    fn strict_programmatic_network_modes_use_the_expected_namespace_across_the_matrix() {
        for proxy in [false, true] {
            for mode in [
                NetworkEnforcementMode::Capabilities,
                NetworkEnforcementMode::Firewall,
                NetworkEnforcementMode::Both,
            ] {
                for policy in [NetworkPolicy::Allow, NetworkPolicy::Block] {
                    for hosts in [false, true] {
                        let mut r = base_request();
                        r.network_enforcement_compatibility =
                            NetworkEnforcementCompatibility::Strict;
                        r.policy.network_proxy.builtin_test_server = proxy;
                        r.policy.network_enforcement_mode = mode.clone();
                        r.policy.default_network_policy = policy.clone();
                        r.policy.allowed_hosts = if hosts {
                            vec!["10.0.0.1".into()]
                        } else {
                            vec![]
                        };

                        // A proxy or enforceable firewall rule needs a private
                        // namespace; ruleless block is isolated without slirp.
                        let uses_firewall = matches!(
                            mode,
                            NetworkEnforcementMode::Firewall | NetworkEnforcementMode::Both
                        );
                        let expected = proxy
                            || (uses_firewall && hosts)
                            || (policy == NetworkPolicy::Block && !hosts);

                        let resolved = ResolvedNetworkMode::from_request(&r, proxy);
                        assert_eq!(
                            resolved.uses_private_netns(),
                            expected,
                            "proxy={proxy} mode={mode:?} policy={policy:?} hosts={hosts}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn filesystem_policy_produces_correct_mounts() {
        let mut r = base_request();
        r.policy.readwrite_paths = vec!["/workspace".into()];
        r.policy.readonly_paths = vec!["/data".into()];
        r.policy.denied_paths = vec!["/secrets".into()];
        let args = build_args(&r, None);

        // rw
        let rw_pos = args.iter().position(|a| a == "--bind").unwrap();
        assert_eq!(args[rw_pos + 1], "/workspace");
        assert_eq!(args[rw_pos + 2], "/workspace");

        // ro — baseline paths are emitted via --ro-bind-try, so a bare
        // --ro-bind must correspond to the user's readonlyPaths entry.
        args.windows(3)
            .position(|w| w[0] == "--ro-bind" && w[1] == "/data" && w[2] == "/data")
            .expect("readonly policy path /data should produce a --ro-bind mount");

        // denied
        let tmpfs_positions: Vec<_> = args
            .iter()
            .enumerate()
            .filter(|(_, a)| *a == "--tmpfs")
            .collect();
        let secrets_mount = tmpfs_positions
            .iter()
            .find(|(i, _)| args[i + 1] == "/secrets");
        assert!(
            secrets_mount.is_some(),
            "denied path should be tmpfs-masked"
        );
    }

    /// Helper: index of the `op` mount whose **destination** path is `path`.
    /// `--tmpfs` emits `op DEST` (one path); `--bind`/`--ro-bind` emit
    /// `op SRC DEST`, so the destination is the second path. Matching the
    /// destination (rather than the arg immediately after the op) keeps this
    /// correct even if the backend ever emits `SRC != DEST`. Searches from the
    /// end so a policy mount is matched rather than a same-named baseline entry.
    fn policy_mount_pos(args: &[String], op: &str, path: &str) -> usize {
        let dest_offset = if op == "--tmpfs" { 1 } else { 2 };
        (0..args.len())
            .rev()
            .find(|&i| args[i] == op && args.get(i + dest_offset).map(String::as_str) == Some(path))
            .unwrap_or_else(|| panic!("expected `{op} ... {path}` in args: {args:?}"))
    }

    /// A deep denied path must be emitted AFTER a shallower read-write ancestor
    /// so the mask wins on the subtree (most-specific-path-wins).
    #[test]
    fn deep_denied_child_masks_rw_parent() {
        let mut r = base_request();
        r.policy.readwrite_paths = vec!["/data".into()];
        r.policy.denied_paths = vec!["/data/secrets".into()];
        let args = build_args(&r, None);

        let parent = policy_mount_pos(&args, "--bind", "/data");
        let child = policy_mount_pos(&args, "--tmpfs", "/data/secrets");
        assert!(
            child > parent,
            "denied /data/secrets (pos {child}) must come after rw /data (pos {parent}) \
             so it masks the subtree: {args:?}"
        );
    }

    /// Regression for the previously-broken case: a deep read-write path under a
    /// shallower denied parent must be emitted AFTER the parent tmpfs so the deep
    /// bind is not shadowed by the mask (most-specific-path-wins).
    #[test]
    fn deep_rw_child_survives_denied_parent() {
        let mut r = base_request();
        r.policy.readwrite_paths = vec!["/data/secrets".into()];
        r.policy.denied_paths = vec!["/data".into()];
        let args = build_args(&r, None);

        let parent = policy_mount_pos(&args, "--tmpfs", "/data");
        let child = policy_mount_pos(&args, "--bind", "/data/secrets");
        assert!(
            child > parent,
            "rw /data/secrets (pos {child}) must come after denied /data (pos {parent}) \
             so the deep bind is not shadowed by the mask: {args:?}"
        );
    }

    /// A denied path classified as a **directory** (not in `denied_files`) is
    /// masked with an empty `--tmpfs`, matching the default `build_args`.
    #[test]
    fn denied_directory_is_masked_with_tmpfs() {
        let mut r = base_request();
        r.policy.denied_paths = vec!["/secrets".into()];
        let denied_files = HashSet::new();
        let args = build_args_classified(&r, None, &denied_files);

        // tmpfs at /secrets, and no ro-bind of /dev/null onto it.
        policy_mount_pos(&args, "--tmpfs", "/secrets");
        assert!(
            args.windows(3)
                .all(|w| !(w[0] == "--ro-bind" && w[1] == "/dev/null" && w[2] == "/secrets")),
            "a directory denied path must not be masked with /dev/null: {args:?}"
        );
    }

    /// A denied path classified as a **file** (present in `denied_files`) is
    /// masked with `--ro-bind /dev/null`, not `--tmpfs` (which would replace the
    /// file with an empty directory).
    #[test]
    fn denied_file_is_masked_with_dev_null() {
        let mut r = base_request();
        r.policy.denied_paths = vec!["/etc/shadow".into()];
        let denied_files = HashSet::from(["/etc/shadow".to_string()]);
        let args = build_args_classified(&r, None, &denied_files);

        // `--ro-bind /dev/null /etc/shadow` present ...
        let pos = args
            .windows(3)
            .position(|w| w[0] == "--ro-bind" && w[1] == "/dev/null" && w[2] == "/etc/shadow");
        assert!(
            pos.is_some(),
            "a file denied path must be masked with `--ro-bind /dev/null`: {args:?}"
        );
        // ... and it is NOT tmpfs-masked.
        assert!(
            args.windows(2)
                .all(|w| !(w[0] == "--tmpfs" && w[1] == "/etc/shadow")),
            "a file denied path must not be tmpfs-masked: {args:?}"
        );
    }

    /// Classification is per-path: in one policy a denied file and a denied
    /// directory get their respective masks, and the specificity ordering is
    /// still honored (deep file mask emitted after its shallower rw ancestor).
    #[test]
    fn mixed_denied_file_and_dir_masks_each_correctly() {
        let mut r = base_request();
        r.policy.readwrite_paths = vec!["/data".into()];
        r.policy.denied_paths = vec!["/data/secret.txt".into(), "/cache".into()];
        let denied_files = HashSet::from(["/data/secret.txt".to_string()]);
        let args = build_args_classified(&r, None, &denied_files);

        // File → /dev/null, after the rw /data parent.
        let parent = policy_mount_pos(&args, "--bind", "/data");
        let file_mask = policy_mount_pos(&args, "--ro-bind", "/data/secret.txt");
        assert!(
            file_mask > parent,
            "deep denied file mask (pos {file_mask}) must come after rw /data (pos {parent}): {args:?}"
        );
        assert_eq!(args[file_mask + 1], "/dev/null");

        // Dir → tmpfs.
        policy_mount_pos(&args, "--tmpfs", "/cache");
    }

    /// Regression for review comment: a denied **directory** and a denied
    /// **file nested inside it** must each get the correct primitive AND be
    /// ordered parent-first, so the deeper `/dev/null` file mask lands inside
    /// the shallower tmpfs (most-specific-path-wins) rather than being shadowed
    /// by it. Mirrors the empirically-verified E2E behaviour.
    #[test]
    fn nested_denied_dir_and_child_file_mask_each_correctly() {
        let mut r = base_request();
        r.policy.denied_paths = vec!["/data/secret".into(), "/data/secret/key".into()];
        // Only the nested path is a file; the parent is a directory (tmpfs).
        let denied_files = HashSet::from(["/data/secret/key".to_string()]);
        let args = build_args_classified(&r, None, &denied_files);

        // Parent dir → tmpfs; child file → /dev/null.
        let parent = policy_mount_pos(&args, "--tmpfs", "/data/secret");
        let child = policy_mount_pos(&args, "--ro-bind", "/data/secret/key");
        assert_eq!(
            args[child + 1],
            "/dev/null",
            "nested denied file must be masked with /dev/null: {args:?}"
        );
        assert!(
            child > parent,
            "child file mask (pos {child}) must come after parent tmpfs (pos {parent}) \
             so it lands inside the masked subtree: {args:?}"
        );
    }

    #[test]
    fn environment_variables_are_set() {
        let mut r = base_request();
        r.env = Some(vec!["FOO=bar".into(), "PATH=/usr/bin".into()]);
        let args = build_args(&r, None);
        assert!(args.contains(&"--clearenv".to_string()));
        let foo_pos = args.iter().position(|a| a == "FOO").unwrap();
        assert_eq!(args[foo_pos - 1], "--setenv");
        assert_eq!(args[foo_pos + 1], "bar");
    }

    #[test]
    fn working_directory_is_set() {
        let args = build_args(&base_request(), None);
        let chdir_pos = args.iter().position(|a| a == "--chdir").unwrap();
        assert_eq!(args[chdir_pos + 1], "/home/user");
    }

    #[test]
    fn command_is_last() {
        let args = build_args(&base_request(), None);
        let sep = args.iter().position(|a| a == "--").unwrap();
        assert_eq!(args[sep + 1], "sh");
        assert_eq!(args[sep + 2], "-c");
        assert_eq!(args[sep + 3], "echo hello");
    }

    #[test]
    fn empty_working_directory_omits_chdir() {
        let mut r = base_request();
        r.working_directory = String::new();
        let args = build_args(&r, None);
        assert!(!args.contains(&"--chdir".to_string()));
    }

    /// Regression test for policy-mount-shadowing bug:
    /// the hard-coded `--tmpfs /tmp` must NOT shadow user policy mounts
    /// whose paths fall under `/tmp`. With the original ordering the
    /// standard `/tmp` tmpfs was applied AFTER policy mounts and wiped them
    /// out. The fix is to lay standard mounts down first so user policy
    /// mounts always come after and win.
    #[test]
    fn policy_mounts_under_tmp_are_not_shadowed_by_standard_tmpfs() {
        let mut r = base_request();
        r.policy.readwrite_paths = vec!["/tmp/workspace".into()];
        r.policy.readonly_paths = vec!["/tmp/data".into()];
        r.policy.denied_paths = vec!["/tmp/secrets".into()];
        let args = build_args(&r, None);

        // Locate the position of the standard --tmpfs /tmp mount.
        let tmpfs_tmp_pos = args
            .windows(2)
            .position(|w| w[0] == "--tmpfs" && w[1] == "/tmp")
            .expect("standard --tmpfs /tmp must be present");

        // Helper: find the position of an "--<op> /tmp/<x>" mount, asserting
        // it comes AFTER the standard /tmp tmpfs so it actually applies.
        let assert_after = |op: &str, target: &str| {
            let pos = args
                .windows(2)
                .position(|w| w[0] == op && w[1] == target)
                .unwrap_or_else(|| panic!("missing {} {}", op, target));
            assert!(
                pos > tmpfs_tmp_pos,
                "{} {} (pos {}) must come after --tmpfs /tmp (pos {}) \
                     or it will be shadowed",
                op,
                target,
                pos,
                tmpfs_tmp_pos
            );
        };

        assert_after("--bind", "/tmp/workspace");
        assert_after("--ro-bind", "/tmp/data");
        assert_after("--tmpfs", "/tmp/secrets");
    }

    // ------- Network proxy env-var injection tests ----------------------

    #[test]
    fn proxy_active_uses_private_network_and_external_user_namespace() {
        let mut r = base_request();
        r.network_enforcement_compatibility = NetworkEnforcementCompatibility::Strict;
        r.policy.default_network_policy = NetworkPolicy::Block;
        let addr = ProxyAddress::new("127.0.0.1".into(), 12345);
        let args = build_args(&r, Some(&addr));
        assert!(
            args.contains(&"--unshare-net".to_string()),
            "proxy mode must use a private network namespace"
        );
        assert!(
            !args.contains(&"--unshare-user".to_string()),
            "the runner supplies proxy mode's pre-created user namespace"
        );
    }

    #[test]
    fn proxy_active_injects_env_vars() {
        let r = base_request();
        let addr = ProxyAddress::new("127.0.0.1".into(), 7777);
        let args = build_args(&r, Some(&addr));

        // Each proxy key must be set via --setenv.
        for key in &[
            "HTTP_PROXY",
            "HTTPS_PROXY",
            "ALL_PROXY",
            "http_proxy",
            "https_proxy",
            "all_proxy",
        ] {
            let pos = args
                .iter()
                .position(|a| a == *key)
                .unwrap_or_else(|| panic!("missing --setenv {} in {:?}", key, args));
            assert_eq!(args[pos - 1], "--setenv");
        }

        // Value points at the loopback proxy URL.
        let http_pos = args.iter().position(|a| a == "HTTP_PROXY").unwrap();
        assert_eq!(args[http_pos + 1], "http://127.0.0.1:7777");
    }

    #[test]
    fn proxy_active_does_not_exempt_loopback_via_no_proxy() {
        // Setting NO_PROXY=localhost,127.0.0.1 would let cooperating HTTP
        // clients bypass the proxy for host-loopback destinations.
        // Any bypass would silently defeat allowedHosts/blockedHosts.
        let r = base_request();
        let addr = ProxyAddress::new("127.0.0.1".into(), 7777);
        let args = build_args(&r, Some(&addr));

        assert!(
            !args.iter().any(|a| a == "NO_PROXY" || a == "no_proxy"),
            "proxy mode must not emit NO_PROXY/no_proxy --setenv pairs: {:?}",
            args,
        );
    }

    #[test]
    fn proxy_active_strips_caller_supplied_proxy_env() {
        let mut r = base_request();
        r.env = Some(vec![
            "FOO=bar".into(),
            "HTTP_PROXY=http://attacker.example:9999".into(),
            "https_proxy=http://attacker.example:9999".into(),
            "ALL_PROXY=http://attacker.example:9999".into(),
            "FTP_PROXY=http://attacker.example:9999".into(),
            "ftp_proxy=http://attacker.example:9999".into(),
            "NO_PROXY=*".into(),
            "PATH=/usr/bin".into(),
        ]);
        let addr = ProxyAddress::new("127.0.0.1".into(), 9000);
        let args = build_args(&r, Some(&addr));

        // Caller-supplied proxy values must NOT appear.
        assert!(
            !args.iter().any(|a| a == "http://attacker.example:9999"),
            "caller-supplied proxy URL must be stripped"
        );

        // The legitimate (non-proxy) env vars are preserved.
        assert!(args.iter().any(|a| a == "FOO"));
        assert!(args.iter().any(|a| a == "PATH"));

        // The proxy URL is the one we set, not the attacker's.
        let http_pos = args.iter().position(|a| a == "HTTP_PROXY").unwrap();
        assert_eq!(args[http_pos + 1], "http://127.0.0.1:9000");

        // FTP variables point at the configured proxy rather than a
        // caller-controlled alternative.
        for key in ["FTP_PROXY", "ftp_proxy"] {
            let pos = args
                .iter()
                .position(|arg| arg == key)
                .unwrap_or_else(|| panic!("missing --setenv {key} in {args:?}"));
            assert_eq!(args[pos + 1], "http://127.0.0.1:9000");
        }

        // Bypass variables remain absent after clearing the caller's
        // environment.
        for key in ["NO_PROXY", "no_proxy"] {
            assert!(
                !args.iter().any(|arg| arg == key),
                "proxy mode must not emit caller-controlled {key}: {args:?}"
            );
        }
    }

    #[test]
    fn proxy_inactive_leaves_caller_supplied_proxy_env_intact() {
        // When the runner has not configured a proxy, the builder must NOT
        // strip env vars whose keys happen to match PROXY_ENV_KEYS -- those
        // are just regular env vars set by the caller for some other reason.
        let mut r = base_request();
        r.env = Some(vec!["HTTP_PROXY=http://caller.example:8080".into()]);
        let args = build_args(&r, None);

        let pos = args.iter().position(|a| a == "HTTP_PROXY").unwrap();
        assert_eq!(args[pos + 1], "http://caller.example:8080");
    }

    // ------- Deny-by-default baseline filesystem tests ------------------

    /// Regression test for the original `--ro-bind / /` baseline. The
    /// builder must NOT bind-mount the entire host root, because that
    /// exposed `$HOME` and other confidential dirs by default. Mirrors
    /// the seatbelt backend's `(deny default)` posture.
    #[test]
    fn baseline_does_not_bind_mount_host_root() {
        let args = build_args(&base_request(), None);
        let root_bind = args
            .windows(3)
            .any(|w| (w[0] == "--ro-bind" || w[0] == "--bind") && w[1] == "/" && w[2] == "/");
        assert!(
            !root_bind,
            "baseline must not bind-mount host / into the sandbox; got: {:?}",
            args
        );
    }

    /// The minimum baseline allowlist required for a shell + dynamic
    /// linker + libc to function inside the sandbox. Emitted via
    /// `--ro-bind-try` so missing paths are silently skipped on distros
    /// where they don't exist (e.g. `/lib32` on x86_64-only systems).
    #[test]
    fn baseline_emits_required_ro_bind_try_paths() {
        let args = build_args(&base_request(), None);
        let required = [
            "/bin",
            "/sbin",
            "/lib",
            "/lib64",
            "/usr/bin",
            "/usr/lib",
            "/usr/share",
            "/etc",
        ];
        for path in required {
            let found = args
                .windows(3)
                .any(|w| w[0] == "--ro-bind-try" && w[1] == path && w[2] == path);
            assert!(
                found,
                "baseline must emit `--ro-bind-try {} {}` so sandboxed processes \
                 can find sh / libc / system config",
                path, path
            );
        }
    }

    /// The baseline must NOT include `/usr` wholesale because that would
    /// expose `/usr/local` (locally-installed software, sometimes
    /// user-managed). Seatbelt's `SYSTEM_READ_ALLOW` does not include
    /// `/usr/local` either — match that posture.
    #[test]
    fn baseline_does_not_expose_usr_local() {
        let args = build_args(&base_request(), None);
        // No `--ro-bind /usr /usr` and no `--ro-bind-try /usr /usr`.
        let usr_whole = args
            .windows(3)
            .any(|w| matches!(w[0].as_str(), "--ro-bind" | "--ro-bind-try") && w[1] == "/usr");
        assert!(
            !usr_whole,
            "baseline must bind /usr subpaths individually so /usr/local is \
             not implicitly exposed; got: {:?}",
            args
        );
        // And no explicit /usr/local mount either. Restrict the scan to
        // mount-argument windows so a script body that merely mentions
        // `/usr/local` cannot trigger a false positive.
        let usr_local = args.windows(3).any(|w| {
            matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try")
                && w[1] == "/usr/local"
        });
        assert!(!usr_local, "baseline must not expose /usr/local by default");
    }

    /// The baseline must keep confidential host locations out of the
    /// sandbox. Callers who legitimately need any of these can opt in
    /// via `readonlyPaths`.
    #[test]
    fn baseline_excludes_confidential_paths() {
        let args = build_args(&base_request(), None);
        for forbidden in [
            "/home",
            "/root",
            "/opt",
            "/srv",
            "/var",
            "/sys",
            "/run/user",
            "/run/dbus",
        ] {
            let exposed = args.windows(2).any(|w| {
                matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try")
                    && w[1] == forbidden
            });
            assert!(
                !exposed,
                "baseline must not bind-mount {} — that would re-expose \
                 confidential host state",
                forbidden
            );
        }
    }

    /// DNS stub-resolver dirs must be in the baseline so `/etc/resolv.conf`
    /// symlinks resolve when the caller has network access. Emitted via
    /// `--ro-bind-try` so hosts without systemd-resolved / NetworkManager /
    /// resolvconf still build a valid argument vector.
    #[test]
    fn baseline_includes_dns_stub_resolver_dirs() {
        let args = build_args(&base_request(), None);
        for path in [
            "/run/systemd/resolve",
            "/run/NetworkManager",
            "/run/resolvconf",
        ] {
            let found = args
                .windows(3)
                .any(|w| w[0] == "--ro-bind-try" && w[1] == path && w[2] == path);
            assert!(
                found,
                "baseline must emit `--ro-bind-try {} {}` so DNS works when \
                 /etc/resolv.conf is a symlink",
                path, path
            );
        }
    }

    /// Regression test for the `/etc/resolv.conf -> /var/run/.../resolv.conf`
    /// symlink case (older RHEL/CentOS-era, some container images). We never
    /// mount `/var`, so without a `/var/run -> /run` compat symlink the
    /// target dangles and DNS silently breaks. Assert the symlink is emitted
    /// so `/var/run/NetworkManager/resolv.conf` resolves into the bound
    /// `/run/NetworkManager`.
    #[test]
    fn baseline_recreates_var_run_compat_symlink() {
        let args = build_args(&base_request(), None);
        let found = args
            .windows(3)
            .any(|w| w[0] == "--symlink" && w[1] == "/run" && w[2] == "/var/run");
        assert!(
            found,
            "baseline must emit `--symlink /run /var/run` so /etc/resolv.conf \
             symlinks routed through /var/run/... resolve; got: {:?}",
            args
        );
        // The compat symlink must not drag a host /var bind in with it.
        let var_bound = args.windows(2).any(|w| {
            matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try") && w[1] == "/var"
        });
        assert!(!var_bound, "compat symlink must not bind host /var");
    }

    /// Regression test for WSL, where `/etc/resolv.conf` points at
    /// `/mnt/wsl/resolv.conf`. We bind that single file (via `--ro-bind-try`,
    /// so it is skipped on non-WSL hosts) without exposing the rest of
    /// `/mnt`.
    #[test]
    fn baseline_includes_wsl_resolv_conf() {
        let args = build_args(&base_request(), None);
        let found = args.windows(3).any(|w| {
            w[0] == "--ro-bind-try"
                && w[1] == "/mnt/wsl/resolv.conf"
                && w[2] == "/mnt/wsl/resolv.conf"
        });
        assert!(
            found,
            "baseline must emit `--ro-bind-try /mnt/wsl/resolv.conf ...` so DNS \
             works under WSL; got: {:?}",
            args
        );
        // Only the single resolv.conf file — never /mnt or /mnt/wsl wholesale.
        let mnt_whole = args.windows(2).any(|w| {
            matches!(w[0].as_str(), "--bind" | "--ro-bind" | "--ro-bind-try")
                && (w[1] == "/mnt" || w[1] == "/mnt/wsl")
        });
        assert!(
            !mnt_whole,
            "baseline must not expose /mnt or /mnt/wsl wholesale"
        );
    }

    /// Baseline mounts must come before policy mounts so the user's
    /// `readwritePaths` / `readonlyPaths` / `deniedPaths` always win on
    /// conflict (same shadowing rule as the existing `/tmp` regression
    /// test, applied here to the baseline).
    #[test]
    fn baseline_mounts_precede_policy_mounts() {
        let mut r = base_request();
        r.policy.readwrite_paths = vec!["/etc/policy-writable".into()];
        let args = build_args(&r, None);

        let baseline_etc = args
            .windows(3)
            .position(|w| w[0] == "--ro-bind-try" && w[1] == "/etc" && w[2] == "/etc")
            .expect("baseline /etc bind missing");
        let policy_bind = args
            .windows(3)
            .position(|w| w[0] == "--bind" && w[1] == "/etc/policy-writable")
            .expect("policy bind missing");

        assert!(
            policy_bind > baseline_etc,
            "policy mount at /etc/policy-writable (pos {}) must come after \
             baseline /etc bind (pos {}) so the policy mount wins",
            policy_bind,
            baseline_etc
        );
    }
}