mxc-sdk 1.0.1

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
// 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;
#[cfg(any(target_os = "linux", test))]
use crate::mxc_common::models::ContainerPolicy;
use crate::mxc_common::models::{ExecutionRequest, NetworkAction, 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 the resolver file is *readable* when `/etc/resolv.conf`
///   is a symlink (the default on systemd-resolved hosts).
/// - To keep that file readable 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.
/// - Readable is not reachable. A nameserver on the host's loopback — the
///   systemd-resolved stub at `127.0.0.53`, a local `dnsmasq` — belongs to
///   the sandbox's own empty loopback once it is in a private network
///   namespace, so these binds alone leave names unresolvable. Reaching such
///   a resolver is what `proxy_network::ResolverPin` does, by pointing the
///   sandbox at slirp's forwarder.
/// - `/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 compatibility symlink the sandbox gets in place of a real `/var/run`,
/// and the directory it points at.
pub(crate) const COMPAT_RUN_LINK: &str = "/var/run";
pub(crate) const COMPAT_RUN_TARGET: &str = "/run";

/// An absolute resolver target with no overlapping known mount destination.
/// This lexical check does not resolve host or sandbox symlinks.
#[cfg(any(target_os = "linux", test))]
pub(crate) fn resolver_target_without_matching_mount(
    policy: &ContainerPolicy,
    target: &str,
) -> bool {
    if target == "/"
        || !target.starts_with('/')
        || target.split('/').any(|part| part == "." || part == "..")
    {
        return false;
    }

    let mut policy_mounts = policy
        .readwrite_paths
        .iter()
        .chain(&policy.readonly_paths)
        .chain(&policy.denied_paths)
        .map(String::as_str);
    for mount in BASELINE_RO_BIND_PATHS
        .iter()
        .copied()
        .chain(["/dev", "/proc", "/tmp", "/var/run"])
        .chain(policy_mounts.clone())
    {
        if !mount.starts_with('/')
            || mount.split('/').any(|part| part == "." || part == "..")
            || paths_overlap(target, mount)
        {
            return false;
        }
    }

    // A policy mount at the link (or an ancestor) replaces the host /etc
    // entry, so the presence of its target alone would not explain DNS.
    !policy_mounts.any(|mount| paths_overlap("/etc/resolv.conf", mount))
}

#[cfg(any(target_os = "linux", test))]
fn paths_overlap(a: &str, b: &str) -> bool {
    let a = std::path::Path::new(a);
    let b = std::path::Path::new(b);
    a.starts_with(b) || b.starts_with(a)
}

/// 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,
    /// Directional iptables filtering inside a slirp-backed private namespace.
    FirewallEnforced,
    /// Cooperative proxy routing inside a slirp-backed private namespace, with
    /// egress closed to everything but the proxy.
    ProxyOnly,
}

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 Self::ProxyOnly;
        }

        // An absent egress section is the supported deny default. Only a
        // ruleless deny can omit slirp and the namespace-local firewall.
        let egress = request.policy.network_egress.as_ref();
        if egress.is_none_or(|egress| {
            egress.default == NetworkAction::Deny
                && egress.allow.is_empty()
                && egress.deny.is_empty()
        }) {
            Self::Isolated
        } else {
            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)
    }
}

/// Refuse an inbound 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.
///
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 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 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'.";

/// Rejection text for a proxy combined with direct egress.
#[cfg(any(target_os = "linux", test))]
pub(crate) const BWRAP_PROXY_DIRECTIONAL_EGRESS: &str =
    "Bubblewrap: runtimeConfig.networkProxy cannot be combined with direct network.egress rules \
     or default='allow'. \
     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 runtimeConfig.networkProxy and express the policy with network.egress.";

/// Reject direct egress that proxy-only routing would otherwise discard.
#[cfg(any(target_os = "linux", test))]
pub(crate) fn proxy_with_egress_rejection(request: &ExecutionRequest) -> Option<&'static str> {
    let proxy = &request.policy.network_proxy;
    if !proxy.is_enabled() {
        return None;
    }

    request
        .policy
        .network_egress
        .as_ref()
        .is_some_and(|egress| {
            egress.default != NetworkAction::Deny
                || !egress.allow.is_empty()
                || !egress.deny.is_empty()
        })
        .then_some(BWRAP_PROXY_DIRECTIONAL_EGRESS)
}

/// `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 for every supported contract.
///
/// 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(crate::mxc_common::models::sandbox_absolute_path)
}

/// Find an explicit cwd with no overlapping known mount destination.
/// This is a lexical hint, not proof of visibility inside Bubblewrap.
#[cfg(any(target_os = "linux", test))]
pub(crate) fn cwd_without_matching_mount(request: &ExecutionRequest) -> Option<String> {
    let dir = start_directory(request)?;
    if dir == "/"
        || !request.working_directory.starts_with('/')
        || request
            .working_directory
            .split('/')
            .any(|part| part == "." || part == "..")
    {
        return None;
    }

    let mounts = BASELINE_RO_BIND_PATHS
        .iter()
        .copied()
        .chain(["/dev", "/proc", "/tmp", "/var/run"])
        .chain(
            request
                .policy
                .readwrite_paths
                .iter()
                .chain(&request.policy.readonly_paths)
                .chain(&request.policy.denied_paths)
                .map(String::as_str),
        );
    for mount in mounts {
        if !mount.starts_with('/') || mount.split('/').any(|part| part == "." || part == "..") {
            return None;
        }
        if path_is_within(&dir, mount) || path_is_within(mount, &dir) {
            return None;
        }
    }
    Some(dir)
}

#[cfg(any(target_os = "linux", test))]
fn path_is_within(path: &str, parent: &str) -> bool {
    std::path::Path::new(path).starts_with(parent)
}

/// 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`]. Explicit replacement 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/backends/bwrap/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 sandbox-visible runtime proxy endpoint, if 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/backends/bwrap/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/backends/bwrap/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());

    // Every supported mode has a private namespace; slirp provides connectivity
    // only after its firewall is installed.
    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(),
        COMPAT_RUN_TARGET.into(),
        COMPAT_RUN_LINK.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 -------------------------------------------
    // Cooperating tools route through the externally managed proxy; raw
    // sockets cannot bypass the namespace-local default-DROP chain.
    //
    // 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::*;

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

    #[test]
    fn resolver_target_hint_requires_no_mount_overlap() {
        let mut policy = ContainerPolicy::default();
        assert!(resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
        for no_warning in [
            "/run/systemd/resolve/resolv.conf",
            "/var/run/NetworkManager/resolv.conf",
            "/mnt/wsl/resolv.conf",
            "/etc/resolv.conf",
            "/tmp/resolv.conf",
        ] {
            assert!(
                !resolver_target_without_matching_mount(&policy, no_warning),
                "unexpected advisory for {no_warning}"
            );
        }
        policy.readonly_paths = vec!["/opt/private".into()];
        assert!(!resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
        for mount in ["/opt/private/", "/opt//private/"] {
            policy.readonly_paths = vec![mount.into()];
            assert!(
                !resolver_target_without_matching_mount(&policy, "/opt/private/resolv.conf"),
                "{mount}"
            );
        }
        policy.readonly_paths = vec!["/opt/private/resolv.conf/child".into()];
        assert!(!resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
        policy.readonly_paths = vec!["/opt/private2".into()];
        assert!(resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
        policy.readonly_paths = vec!["/".into()];
        assert!(!resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
    }

    #[test]
    fn resolver_diagnostic_recognizes_every_emitted_mount_destination() {
        let mut with_policy = base_request();
        with_policy.policy.readwrite_paths = vec!["/home/user/data".into()];
        with_policy.policy.readonly_paths = vec!["/opt/private".into()];
        with_policy.policy.denied_paths = vec!["/srv/blocked".into()];
        for request in [base_request(), with_policy] {
            let args = build_args(&request, None);
            for triple in args.windows(3) {
                if matches!(
                    triple[0].as_str(),
                    "--ro-bind-try" | "--ro-bind" | "--bind" | "--symlink"
                ) {
                    assert!(
                        !resolver_target_without_matching_mount(&request.policy, &triple[2]),
                        "unrecognized mount destination: {triple:?}"
                    );
                }
            }
            for pair in args.windows(2) {
                if matches!(pair[0].as_str(), "--dev" | "--proc" | "--tmpfs") {
                    assert!(
                        !resolver_target_without_matching_mount(&request.policy, &pair[1]),
                        "unrecognized virtual mount destination: {pair:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn cwd_hint_requires_a_nonoverlapping_absolute_path() {
        let mut request = base_request();
        assert_eq!(
            cwd_without_matching_mount(&request).as_deref(),
            Some("/home/user")
        );
        request.working_directory = "/".into();
        assert_eq!(cwd_without_matching_mount(&request), None);
        request.working_directory = "".into();
        assert_eq!(cwd_without_matching_mount(&request), None);
        request.working_directory = "home/user".into();
        assert_eq!(cwd_without_matching_mount(&request), None);
        request.working_directory = "/home/../home/user".into();
        assert_eq!(cwd_without_matching_mount(&request), None);
    }

    #[test]
    fn cwd_overlap_is_inconclusive_in_either_direction() {
        let mut request = base_request();
        for cwd in ["/etc", "/etc/project", "/usr", "/tmp/work", "/var"] {
            request.working_directory = cwd.into();
            assert_eq!(cwd_without_matching_mount(&request), None, "{cwd}");
        }
        for mount in [
            "/home",
            "/home/user",
            "/home/user/",
            "/home//user/",
            "/home/user/data",
            "/home//user/data/",
        ] {
            request.working_directory = "/home/user".into();
            request.policy.readonly_paths = vec![mount.into()];
            assert_eq!(cwd_without_matching_mount(&request), None, "{mount}");
        }
        for mount in ["/home/user2", "/home/user2/"] {
            request.policy.readonly_paths = vec![mount.into()];
            assert_eq!(
                cwd_without_matching_mount(&request).as_deref(),
                Some("/home/user"),
                "{mount}"
            );
        }
        request.policy.readonly_paths = vec!["/alias/../home/user".into()];
        assert_eq!(cwd_without_matching_mount(&request), None);
        request.policy.readonly_paths = vec!["/".into()];
        assert_eq!(cwd_without_matching_mount(&request), None);
        request.policy.readonly_paths.clear();
        request.policy.denied_paths = vec!["/home/user/hidden".into()];
        assert_eq!(cwd_without_matching_mount(&request), None);
    }

    #[test]
    fn cwd_proof_uses_the_mounted_baseline_and_virtual_roots() {
        let request = base_request();
        let args = build_args(&request, None);
        for mount in BASELINE_RO_BIND_PATHS {
            assert!(
                args.windows(3)
                    .any(|a| { a == ["--ro-bind-try", *mount, *mount] }),
                "{mount}"
            );
        }
        for (flag, path) in [
            ("--dev", "/dev"),
            ("--proc", "/proc"),
            ("--tmpfs", "/tmp"),
            ("--symlink", "/var/run"),
        ] {
            assert!(
                args.windows(2).any(|a| a[0] == flag && a[1] == path)
                    || (flag == "--symlink"
                        && args.windows(3).any(|a| a == ["--symlink", "/run", path])),
                "{flag} {path}"
            );
        }
    }

    #[test]
    fn ambiguous_resolver_paths_and_shadowed_link_do_not_warn() {
        let mut policy = ContainerPolicy::default();
        for target in ["relative/resolv.conf", "/opt/../secret/resolv.conf", "/"] {
            assert!(!resolver_target_without_matching_mount(&policy, target));
        }
        policy.denied_paths = vec!["/etc".into()];
        assert!(!resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
        policy.denied_paths = vec!["/etc//".into()];
        assert!(!resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
        policy.denied_paths = vec!["/alias/../etc".into()];
        assert!(!resolver_target_without_matching_mount(
            &policy,
            "/opt/private/resolv.conf"
        ));
    }

    #[test]
    fn cwd_diagnostic_recognizes_every_emitted_mount_destination() {
        let mut request = base_request();
        let args = build_args(&request, None);
        for triple in args.windows(3) {
            if matches!(
                triple[0].as_str(),
                "--ro-bind-try" | "--ro-bind" | "--bind" | "--symlink"
            ) {
                request.working_directory = triple[2].clone();
                assert!(
                    cwd_without_matching_mount(&request).is_none(),
                    "unrecognized mount destination: {triple:?}"
                );
            }
        }
        for pair in args.windows(2) {
            if matches!(pair[0].as_str(), "--dev" | "--proc" | "--tmpfs") {
                request.working_directory = pair[1].clone();
                assert!(
                    cwd_without_matching_mount(&request).is_none(),
                    "unrecognized virtual mount destination: {pair:?}"
                );
            }
        }
    }

    /// `process.env` resolution, which schema 0.9 gave a default block.
    mod env {
        use super::*;
        fn request() -> ExecutionRequest {
            ExecutionRequest::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();
            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();
            r.env = Some(vec![]);
            assert!(resolved_env(&r).is_empty());
        }

        #[test]
        fn a_supplied_env_is_used_verbatim() {
            let mut r = request();
            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();
            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();
            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.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();
            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();
                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();
                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.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 an_omitted_network_policy_is_isolated() {
        let request = ExecutionRequest { ..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()));
    }

    /// A directional egress policy must land on the one mode whose chains the
    /// sandbox actually traverses.
    ///
    #[test]
    fn a_directional_rule_selects_the_namespace_whose_chain_is_programmed() {
        let request = directional_egress_request(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(NetworkAction::Deny, false);
        assert_eq!(
            ResolvedNetworkMode::from_request(&denied, false),
            ResolvedNetworkMode::Isolated
        );

        let allowed = directional_egress_request(NetworkAction::Allow, false);
        let mode = ResolvedNetworkMode::from_request(&allowed, false);
        assert_eq!(mode, ResolvedNetworkMode::FirewallEnforced);
        assert!(build_args(&allowed, None).contains(&"--unshare-net".to_string()));
    }

    /// Neither default nor rules may share the host namespace.
    #[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(default, with_rule);
                assert!(
                    build_args(&request, None).contains(&"--unshare-net".to_string()),
                    "default={default:?} with_rule={with_rule} omitted --unshare-net"
                );
            }
        }
    }

    /// 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(NetworkAction::Deny, false);
        request.policy.network_proxy.address = Some(ProxyAddress::new("127.0.0.1".into(), 3128));
        assert_eq!(
            ResolvedNetworkMode::from_request(&request, true),
            ResolvedNetworkMode::ProxyOnly
        );
    }

    /// An ingress-only request retains isolation with implicit egress deny.
    #[test]
    fn an_ingress_only_directional_request_still_gets_a_private_namespace() {
        use crate::mxc_common::models::NetworkIngressPolicy;

        let mut request = base_request();
        request.policy.network_ingress = Some(NetworkIngressPolicy::default());
        let mode = ResolvedNetworkMode::from_request(&request, false);
        assert_eq!(mode, ResolvedNetworkMode::Isolated);
        assert!(build_args(&request, None).contains(&"--unshare-net".to_string()));
    }

    /// Build a supported egress request.
    fn directional_egress_request(default: NetworkAction, with_rule: bool) -> ExecutionRequest {
        use crate::mxc_common::models::{NetworkEgressPolicy, NetworkRule};

        let mut request = base_request();
        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(
        ingress_default: NetworkAction,
        host_loopback: NetworkAction,
    ) -> ExecutionRequest {
        use crate::mxc_common::models::{NetworkEgressPolicy, NetworkIngressPolicy};

        let mut request = base_request();
        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(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(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(NetworkAction::Deny, NetworkAction::Deny);
        assert_eq!(directional_network_rejection(&request), None);
    }

    #[test]
    fn only_external_runtime_proxies_are_accepted() {
        let mut request = directional_egress_request(NetworkAction::Deny, false);
        request.policy.network_proxy.address = Some(ProxyAddress::new("127.0.0.1".into(), 3128));
        assert!(proxy_with_egress_rejection(&request).is_none());
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Allow,
            ..Default::default()
        });
        assert_eq!(
            proxy_with_egress_rejection(&request),
            Some(BWRAP_PROXY_DIRECTIONAL_EGRESS)
        );
    }

    #[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 r = base_request();
        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 externally managed proxy policy.
        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 an `/etc/resolv.conf`
    /// symlink has a target to resolve to. 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 the sandbox can read \
                 /etc/resolv.conf when it 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
        );
    }
}