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

//! Policy mapping — translates MXC's platform-agnostic `ContainerPolicy` into
//! WSLC SDK volume mounts and networking mode.
//!
//! This module contains pure functions with no SDK dependency, making it
//! fully unit-testable without the WSLC runtime. The denied-path overlap check
//! has an optional I/O-backed tier (alias canonicalization) whose resolver is
//! injected, so its logic stays testable without touching disk.

use crate::mxc_common::filesystem_canonical::{canonicalize_allowing_absent_tail, PathCanonical};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainerPolicy, ExecutionRequest};
use crate::wslc_common::wslc_bindings::WslcContainerNetworkingMode;

/// A resolved volume mount ready to be passed to `WslcSetContainerSettingsVolumes`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VolumeMount {
    /// Windows host path (e.g., `C:\workspace`).
    pub windows_path: String,
    /// Linux container path (e.g., `/mnt/c/workspace`).
    pub container_path: String,
    /// Whether the mount is read-only.
    pub read_only: bool,
}

/// Convert a Windows path to a WSL2 container mount path.
///
/// Applies the WSL2 convention: strip the drive letter, lowercase it,
/// and prefix with `/mnt/`. Forward slashes are used throughout.
///
/// Examples:
/// - `C:\workspace` → `/mnt/c/workspace`
/// - `D:\data\files` → `/mnt/d/data/files`
/// - `C:\` → `/mnt/c/`
///
/// Returns `None` if the path doesn't start with a drive letter (e.g., UNC paths).
pub fn windows_path_to_container_path(windows_path: &str) -> Option<String> {
    let path = windows_path.trim();
    if path.len() < 2 {
        return None;
    }

    let bytes = path.as_bytes();
    let drive = bytes[0];
    let separator = bytes[1];

    if !drive.is_ascii_alphabetic() || (separator != b':') {
        return None;
    }

    // After the colon, must be \, /, or end-of-string (bare "C:")
    if path.len() > 2 {
        let after_colon = bytes[2];
        if after_colon != b'\\' && after_colon != b'/' {
            return None;
        }
    }

    let drive_lower = (drive as char).to_ascii_lowercase();
    let rest = &path[2..];
    let rest_forward = rest.replace('\\', "/");

    Some(format!("/mnt/{}{}", drive_lower, rest_forward))
}

/// Map a one-shot `process.cwd` to the container working directory.
///
/// The one-shot surface takes a local Windows drive path and maps it under
/// `/mnt/<drive>` with [`windows_path_to_container_path`]. A blank value means
/// the cwd was omitted and yields `Ok(None)`, so the container default applies.
/// Any other value that cannot be mapped is an error rather than being dropped,
/// because running the workload in a directory the caller did not ask for is a
/// silent policy deviation. For the same reason a value with an interior NUL is
/// rejected: the SDK takes a C string and would see only the prefix.
pub fn container_working_directory(cwd: &str) -> Result<Option<String>, String> {
    if cwd.trim().is_empty() {
        return Ok(None);
    }
    if cwd.contains('\0') {
        return Err(format!(
            "WSLC: process.cwd {cwd:?} contains an interior NUL byte, which is not a \
             valid C string"
        ));
    }
    windows_path_to_container_path(cwd)
        .map(Some)
        .ok_or_else(|| {
            format!(
                "WSLC: process.cwd {cwd:?} is not a local Windows drive path. The one-shot \
             WSLc surface maps process.cwd from a host path under /mnt/<drive> \
             (e.g. C:\\work -> /mnt/c/work); relative, drive-relative, UNC, and \
             in-container paths are not supported. To start in an absolute \
             in-container path such as /work, use the state-aware lifecycle."
            )
        })
}

/// Build volume mounts from a container policy's filesystem paths.
///
/// - `readwrite_paths` → mounts with `read_only: false`
/// - `readonly_paths` → mounts with `read_only: true`
/// - `denied_paths` → not mounted (Linux container isolation means they're inaccessible)
///
/// Returns an error if any path is not a valid local Windows drive path.
/// UNC paths (`\\server\share`) are explicitly rejected because the WSLC SDK
/// can only mount paths via the `/mnt/<drive>/` convention and has no mechanism
/// to project network shares into the container's filesystem namespace.
pub fn build_volume_mounts(
    readwrite_paths: &[String],
    readonly_paths: &[String],
) -> Result<Vec<VolumeMount>, String> {
    let mut mounts = Vec::new();

    for path in readwrite_paths {
        let container_path = windows_path_to_container_path(path).ok_or_else(|| {
            format!(
                "WSLC: readwritePaths entry '{}' is not a valid local drive path. \
                 Only paths starting with a drive letter (e.g. C:\\...) are supported; \
                 UNC paths (\\\\server\\share) cannot be mapped into a WSL container.",
                path
            )
        })?;
        mounts.push(VolumeMount {
            windows_path: path.clone(),
            container_path,
            read_only: false,
        });
    }

    for path in readonly_paths {
        let container_path = windows_path_to_container_path(path).ok_or_else(|| {
            format!(
                "WSLC: readonlyPaths entry '{}' is not a valid local drive path. \
                 Only paths starting with a drive letter (e.g. C:\\...) are supported; \
                 UNC paths (\\\\server\\share) cannot be mapped into a WSL container.",
                path
            )
        })?;
        mounts.push(VolumeMount {
            windows_path: path.clone(),
            container_path,
            read_only: true,
        });
    }

    Ok(mounts)
}

/// A Windows host path parsed for structural overlap comparison.
///
/// Parsing is platform-independent (no `std::path`, whose component semantics
/// vary by build target) so results match on Windows and Linux CI. The drive
/// prefix and root are kept distinct, and `.`/`..` are folded lexically (no disk
/// access) so a traversal spelling like `C:\a\sub\..` compares equal to `C:\a`.
#[derive(Debug, PartialEq, Eq)]
struct NormalizedPath {
    /// Lowercased drive prefix without separator (`Some("c:")`), or `None`.
    drive: Option<String>,
    /// Whether a separator follows the optional drive: distinguishes absolute
    /// `C:\a` from drive-relative `C:a`, and rooted `\a` from relative `a`.
    rooted: bool,
    /// Lexically folded, lowercased path components.
    components: Vec<String>,
}

impl NormalizedPath {
    /// Parse a Windows host path: split on `/` and `\`, case-fold (full Unicode),
    /// and fold `.`/`..`. A rooted path clamps `..` at the root (Windows
    /// semantics) so a traversal cannot escape into a different tree.
    fn parse(path: &str) -> Self {
        let lowered = path.trim().to_lowercase();
        let bytes = lowered.as_bytes();

        // Drive prefix = a leading `x:` (ASCII letter + colon).
        let (drive, rest) =
            if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
                (Some(lowered[..2].to_string()), &lowered[2..])
            } else {
                (None, lowered.as_str())
            };

        let rooted = rest.starts_with(['/', '\\']);

        let mut components: Vec<String> = Vec::new();
        for segment in rest.split(['/', '\\']).filter(|s| !s.is_empty()) {
            match segment {
                "." => {}
                ".." => {
                    if components.last().is_some_and(|last| last != "..") {
                        components.pop();
                    } else if !rooted {
                        // Relative path: a leading `..` needs a base to resolve,
                        // so retain it. Rooted paths clamp at the root instead.
                        components.push("..".to_string());
                    }
                }
                other => components.push(other.to_string()),
            }
        }

        NormalizedPath {
            drive,
            rooted,
            components,
        }
    }

    /// True when `self` (a mounted parent) strictly contains `child` (a denied
    /// path) — i.e. `child` resolves strictly deeper inside `self`'s tree.
    ///
    /// A whole-drive/root mount (`C:\`, `\`) contains every path sharing its
    /// drive anchor, including drive-relative spellings (`C:secrets`). An exact
    /// match is not "strictly deeper" and returns `false` (enforceable by simply
    /// not mounting the path). Comparison is per-component, so a partial-component
    /// match (`C:\project` vs `C:\project2`) is correctly rejected.
    ///
    /// Excluding exact match here is deliberate: an exact same-*string* deny==mount
    /// is already collapsed most-restrictive-wins at parse time
    /// (`normalize_filesystem_paths`), and an exact same-*object* alias (a deny
    /// that canonicalizes onto the mount root) is normally collapsed by D6
    /// (`normalize_object_conflicts`) before this validator runs. This method
    /// therefore only owns the *strictly-nested* overlap; the Tier-2 caller
    /// separately rejects alias-induced canonical equality (differing original
    /// strings) that D6 missed as absent.
    fn contains_strictly(&self, child: &NormalizedPath) -> bool {
        if self.rooted && self.components.is_empty() {
            // Whole-drive mount: covers the entire drive, so any same-anchor path
            // is unenforceable. Exclude the identical root (exact match).
            return self.drive == child.drive && !(child.rooted && child.components.is_empty());
        }

        self.drive == child.drive
            && self.rooted == child.rooted
            && self.components.len() < child.components.len()
            && self
                .components
                .iter()
                .zip(child.components.iter())
                .all(|(ancestor, descendant)| ancestor == descendant)
    }
}

/// Reject configs where a `deniedPaths` entry is nested under a mounted
/// (`readwritePaths` / `readonlyPaths`) parent, which WSLC cannot enforce.
///
/// LXC and Bubblewrap mask such a deny by overlaying it (`/dev/null` or
/// `tmpfs`), but WSLC's flat volume-mount surface has no overlay/exclusion
/// primitive: a denied subtree under a mounted parent would remain fully
/// accessible through that parent mount. Rather than silently leaving it
/// accessible, reject the config with an actionable error.
///
/// Non-overlapping denied paths need no masking — WSLC simply does not mount
/// them, so they are implicitly enforced (unmounted = invisible) and pass. An
/// exact-path match between a denied path and a mounted path is likewise
/// enforceable (the path is not mounted) and is not treated as an overlap; such
/// exact same-string conflicts are already collapsed most-restrictive-wins at
/// parse time by `mxc_common`'s `normalize_filesystem_paths` (which runs for
/// every backend), and object-identity aliases (different spellings of the same
/// object via symlink/hard link/bind) are additionally tightened at the runner
/// by [`crate::mxc_common::filesystem_object::normalize_object_conflicts`].
///
/// This is a **two-tier** check. Tier 1 is a structural, lexical pre-check (no
/// disk access): paths are parsed with drive prefix and root kept distinct,
/// case-folded (full Unicode), and `.`/`..` folded, so traversal spellings
/// (`C:\proj\sub\..`), whole-drive mounts (`C:\`, `\`), and drive-relative
/// spellings (`C:secrets`) are caught. Tier 2 canonicalizes each path on disk
/// ([`crate::mxc_common::filesystem_canonical::canonicalize_allowing_absent_tail`]) to
/// collapse symlinks, junctions, 8.3 short names, and `\\?\` prefixes, then
/// re-runs the structural compare on the resolved forms — closing the gap where
/// a **policy path itself** is an alias that resolves into a mounted tree. A
/// denied leaf that does not exist yet but sits under an aliased parent is
/// resolved by canonicalizing the deepest existing ancestor and replaying the
/// missing tail (folding `.`/`..`), so a not-yet-created deny under a junctioned
/// mount is still caught. With `deniedPaths` present, a path that exists but
/// cannot be resolved **fails closed** (config rejected) rather than falling
/// back to the weaker textual compare, matching the D6 pass
/// ([`crate::mxc_common::filesystem_object::normalize_object_conflicts`]).
///
/// **Scope / known limitations.** Tier 2 canonicalizes only the paths *listed in
/// the policy*; it does not scan *inside* a mounted directory for reparse
/// points. A junction planted within a mounted tree that points at a denied (or
/// otherwise out-of-tree) location — e.g. mount `C:\project`, deny `C:\secrets`,
/// with `C:\project\link -> C:\secrets` — is **not** caught: canonicalizing the
/// two policy entries yields non-overlapping paths, yet the guest could reach
/// `C:\secrets` through `C:\project\link` if the runtime follows the reparse
/// point. Detecting this would require walking the mounted subtree for reparse
/// points (expensive and still racy) or controlling traversal beneath the mount,
/// which the WSLC SDK does not expose. The same gap applies to a hard link: since
/// hard links are names for one object, hard-linked *policy entries* are caught by
/// D6's file-ID grouping (`normalize_object_conflicts`); only an *unlisted* hard
/// link inside a mounted subtree escapes both Tier 2 and D6. Creating either alias
/// needs write access the guest lacks, so both are out of scope under the
/// trusted-author threat model. Tier 2 also does not fold Unicode normalization
/// forms. A residual TOCTOU window remains between
/// canonicalization and the SDK mount (an alias could be swapped in between);
/// fully closing it needs handle-based mounting the WSLC SDK does not expose, so
/// it is likewise accepted.
pub fn validate_denied_path_overlap(
    readwrite_paths: &[String],
    readonly_paths: &[String],
    denied_paths: &[String],
) -> Result<(), String> {
    validate_denied_path_overlap_with(
        readwrite_paths,
        readonly_paths,
        denied_paths,
        canonicalize_allowing_absent_tail,
    )
}

/// The complete WSLc provision-time filesystem-policy gate, shared by the
/// one-shot runner (`wsl_container_runner::start_container`) and the state-aware
/// provision path (`state_aware::build_provision_config`). Keeping the three
/// ordered steps in one place stops the two runners drifting apart when a policy
/// check or its ordering changes.
///
/// The steps, in the order both paths must run them:
/// 1. **Object-identity normalization (D6)** — tighten rw/ro/denied aliases of
///    the same host object to the strictest intent (deny > ro > rw) via
///    [`crate::mxc_common::filesystem_object::normalize_object_conflicts`]. A path moved
///    to `denied` is simply not mounted (unmounted = invisible).
/// 2. **Delegation (D3)** — reject any path the invoking user cannot access via
///    [`crate::mxc_common::filesystem_access::check_delegation`], evaluated against the
///    already-tightened intents so the sandbox never gains access the caller lacks.
/// 3. **Denied-path overlap** — reject a `denied` entry nested under a still-mounted
///    parent (WSLc's flat volume surface has no overlay primitive), again against
///    the tightened lists, so a deny that only becomes nested after normalization
///    cannot slip through unenforced.
///
/// Returns the tightened policy when normalization changed something (the caller
/// rebuilds the request around it) or `None` when the policy was already
/// conflict-free. Any failure is returned as a `String`; callers map it to their
/// own error envelope (`ScriptResponse` / `MxcError`). Normalization diagnostics
/// are written to `logger`; callers decide how to surface them.
pub fn apply_provision_policy_gate(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Option<ContainerPolicy>, String> {
    let normalized =
        crate::mxc_common::filesystem_object::normalize_object_conflicts(&request.policy, logger)?;
    let effective = normalized.as_ref().unwrap_or(&request.policy);
    crate::mxc_common::filesystem_access::check_delegation(effective)?;
    validate_denied_path_overlap(
        &effective.readwrite_paths,
        &effective.readonly_paths,
        &effective.denied_paths,
    )?;
    Ok(normalized)
}

/// Overlap message for a denied path nested under a mounted parent.
fn overlap_error(denied: &str, mounted: &str, list_name: &str, via_alias: bool) -> String {
    let lead = if via_alias {
        format!(
            "WSLC: deniedPaths entry '{denied}' resolves (via a symlink, junction, or short \
             name) inside {list_name} entry '{mounted}'"
        )
    } else {
        format!("WSLC: deniedPaths entry '{denied}' is nested under {list_name} entry '{mounted}'")
    };
    format!(
        "{lead}. WSLC mounts host paths as flat volumes and has no overlay primitive to mask a \
         subtree of a mounted path, so this deny cannot be enforced — the path would remain \
         accessible through the parent mount. Remove the denied path, or stop mounting its parent."
    )
}

/// Inner overlap validator with an injected path resolver (for testability).
fn validate_denied_path_overlap_with(
    readwrite_paths: &[String],
    readonly_paths: &[String],
    denied_paths: &[String],
    resolve: impl Fn(&str) -> PathCanonical,
) -> Result<(), String> {
    if denied_paths.is_empty() {
        return Ok(());
    }

    let mounts: Vec<(&String, &str)> = readwrite_paths
        .iter()
        .map(|path| (path, "readwritePaths"))
        .chain(readonly_paths.iter().map(|path| (path, "readonlyPaths")))
        .collect();

    // No mounts means nothing a deny could be nested under — skip the on-disk
    // resolution (and its fail-closed-on-Unknown) entirely.
    if mounts.is_empty() {
        return Ok(());
    }

    // Tier 1: lexical fold (no I/O).
    for denied in denied_paths {
        let denied_path = NormalizedPath::parse(denied);
        for (mounted, list_name) in &mounts {
            if NormalizedPath::parse(mounted).contains_strictly(&denied_path) {
                return Err(overlap_error(denied, mounted, list_name, false));
            }
        }
    }

    // Tier 2: canonicalize on disk to collapse alias spellings, then re-compare.
    // Fail closed on an unresolvable path (Unknown) since deniedPaths are present.
    let denied_canon: Vec<(&String, PathCanonical)> =
        denied_paths.iter().map(|d| (d, resolve(d))).collect();
    let mount_canon: Vec<(&String, &str, PathCanonical)> = mounts
        .iter()
        .map(|(m, list)| (*m, *list, resolve(m)))
        .collect();

    for (path, canon) in denied_canon
        .iter()
        .map(|(p, c)| (*p, c))
        .chain(mount_canon.iter().map(|(p, _, c)| (*p, c)))
    {
        if matches!(canon, PathCanonical::Unknown) {
            return Err(format!(
                "WSLC: cannot verify deniedPaths against mounts because '{path}' could not be \
                 resolved to a canonical location (it exists but is not examinable). With \
                 deniedPaths present, MXC fails closed rather than risk an unenforced deny. \
                 Ensure the path is accessible, or remove the deniedPaths entry."
            ));
        }
    }

    for (denied, denied_canon) in &denied_canon {
        let PathCanonical::Canonical(denied_resolved) = denied_canon else {
            continue; // Absent: no on-disk ancestor resolved, so nothing to alias.
        };
        let denied_norm = NormalizedPath::parse(denied_resolved);
        let denied_lexical = NormalizedPath::parse(denied);
        for (mounted, list_name, mount_canon) in &mount_canon {
            let PathCanonical::Canonical(mount_resolved) = mount_canon else {
                continue;
            };
            let mount_norm = NormalizedPath::parse(mount_resolved);
            // Strict nesting is always an unenforceable overlap: the denied
            // subtree lives inside a flat mount that WSLC cannot mask.
            if mount_norm.contains_strictly(&denied_norm) {
                return Err(overlap_error(denied, mounted, list_name, true));
            }
            // Exact canonical equality is an overlap only when it comes from an
            // on-disk alias — the two spellings normalize to *different lexical*
            // forms yet resolve to the same object. A case/separator/`..` variant
            // of the same spelling folds to an equal `NormalizedPath` here (via
            // `NormalizedPath::parse`, NOT `normalize_filesystem_paths`, which only
            // dedupes byte-identical strings) and is the enforceable exact-match
            // case (enforced by not mounting the path), so accept it. But a deny
            // that aliases onto the mount root via a symlink, junction, or short
            // name has no exclusion primitive — `contains_strictly` (strictly
            // deeper only) misses that, so reject it here.
            let mount_lexical = NormalizedPath::parse(mounted);
            if mount_norm == denied_norm && mount_lexical != denied_lexical {
                return Err(overlap_error(denied, mounted, list_name, true));
            }
        }
    }

    Ok(())
}

/// Map the network default policy to a WSLC networking mode.
///
/// The WSLC SDK provides two networking modes:
/// - `None` — no network interface, fully isolated
/// - `Bridged` — NAT networking through the WSL2 VM's virtual adapter
///
/// Per-host filtering (`allowedHosts`/`blockedHosts` that need enforcement) is
/// rejected before this runs — see `build_iptables_rules`. This only maps the
/// bare-default posture:
///
/// - `Block` with no host rules → `None` (fully isolated)
/// - `Allow` → `Bridged` (NAT)
pub fn map_network_policy(is_block: bool, has_host_rules: bool) -> WslcContainerNetworkingMode {
    if is_block && !has_host_rules {
        WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_NONE
    } else {
        WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_BRIDGED
    }
}

/// Returns true if the policy requests per-host filtering (which WSLc cannot
/// enforce — such configs are rejected before execution).
///
/// Thin wrapper over [`crate::mxc_common::models::needs_host_filtering`] so the parser
/// and this backend share one definition:
/// - `Block` → only `allowed_hosts` matter (allowlist)
/// - `Allow` → only `blocked_hosts` matter (blocklist)
pub fn needs_host_filtering(
    is_default_block: bool,
    allowed_hosts: &[String],
    blocked_hosts: &[String],
) -> bool {
    crate::mxc_common::models::needs_host_filtering(is_default_block, allowed_hosts, blocked_hosts)
}

/// Validate that a host string is safe for use in an iptables command.
/// Accepts hostnames (a-z, 0-9, dots, hyphens) and IPv4/IPv6 addresses
/// (digits, dots, colons, brackets, slash for CIDR).
/// Rejects empty strings and anything containing shell metacharacters.
fn is_valid_host(host: &str) -> bool {
    !host.is_empty()
        && host
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b".-:[]/_".contains(&b))
}

/// Build iptables commands for per-host network filtering.
///
/// **NOTE: WSLC per-host filtering is non-functional.** Two independent
/// blockers prevent it from working:
/// 1. WSLC containers lack `CAP_NET_ADMIN` — the SDK's `Privileged` flag does
///    **not** grant it — so the in-container `iptables` exec is rejected.
/// 2. WSLC cannot expose VM-level network enforcement without breaking other
///    security guarantees (e.g. MDE); a host-enforced design is longer-tail.
///
/// Configs that require per-host filtering are therefore **rejected at
/// config-parse time** (and by `WSLContainerRunner::validate_runner`) before
/// this function is reached. This function is retained for reference but its
/// output is never applied.
///
/// When `defaultPolicy` is `Block` + `allowedHosts`:
///   - Default DROP all outbound
///   - ACCEPT to each allowed host
///   - ACCEPT established/related (for return traffic)
///   - ACCEPT loopback
///
/// When `defaultPolicy` is `Allow` + `blockedHosts`:
///   - DROP to each blocked host
///
/// Returns a shell command string to be exec'd inside the container.
///
/// Host values are validated to prevent shell command injection.
pub fn build_iptables_rules(
    allowed_hosts: &[String],
    blocked_hosts: &[String],
    is_default_block: bool,
) -> Option<String> {
    if allowed_hosts.is_empty() && blocked_hosts.is_empty() {
        return None;
    }

    let mut rules = Vec::new();

    if is_default_block && !allowed_hosts.is_empty() {
        // Allow loopback and established connections first
        rules.push("iptables -A OUTPUT -o lo -j ACCEPT".to_string());
        rules.push("iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT".to_string());

        // Allow DNS (needed to resolve hostnames)
        rules.push("iptables -A OUTPUT -p udp --dport 53 -j ACCEPT".to_string());
        rules.push("iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT".to_string());

        // Allow each specified host
        for host in allowed_hosts {
            if !is_valid_host(host) {
                continue;
            }
            rules.push(format!("iptables -A OUTPUT -d {} -j ACCEPT", host));
        }

        // Default drop everything else
        rules.push("iptables -A OUTPUT -j DROP".to_string());
    } else if !is_default_block && !blocked_hosts.is_empty() {
        // Block specific hosts
        for host in blocked_hosts {
            if !is_valid_host(host) {
                continue;
            }
            rules.push(format!("iptables -A OUTPUT -d {} -j DROP", host));
        }
    }

    if rules.is_empty() {
        None
    } else {
        // Join with shell && so each rule must succeed before the next runs.
        // If any iptables command fails, the chain stops and the error propagates.
        Some(rules.join(" && "))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- Path translation tests --

    #[test]
    fn path_c_drive_simple() {
        assert_eq!(
            windows_path_to_container_path(r"C:\workspace"),
            Some("/mnt/c/workspace".to_string())
        );
    }

    #[test]
    fn path_d_drive_nested() {
        assert_eq!(
            windows_path_to_container_path(r"D:\data\files\readme.txt"),
            Some("/mnt/d/data/files/readme.txt".to_string())
        );
    }

    #[test]
    fn path_drive_root_only() {
        assert_eq!(
            windows_path_to_container_path(r"C:\"),
            Some("/mnt/c/".to_string())
        );
    }

    #[test]
    fn path_uppercase_drive_lowered() {
        assert_eq!(
            windows_path_to_container_path(r"E:\Builds"),
            Some("/mnt/e/Builds".to_string())
        );
    }

    #[test]
    fn path_forward_slashes_preserved() {
        assert_eq!(
            windows_path_to_container_path("C:/workspace/src"),
            Some("/mnt/c/workspace/src".to_string())
        );
    }

    #[test]
    fn path_unc_returns_none() {
        assert_eq!(windows_path_to_container_path(r"\\server\share"), None);
    }

    #[test]
    fn path_empty_returns_none() {
        assert_eq!(windows_path_to_container_path(""), None);
    }

    #[test]
    fn path_relative_returns_none() {
        assert_eq!(windows_path_to_container_path("relative/path"), None);
    }

    // -- Working-directory mapping tests --

    #[test]
    fn cwd_blank_is_omitted() {
        for cwd in ["", "   ", "\t"] {
            assert_eq!(container_working_directory(cwd), Ok(None), "cwd {cwd:?}");
        }
    }

    #[test]
    fn cwd_drive_paths_are_mapped() {
        for (cwd, expected) in [
            (r"C:\work", "/mnt/c/work"),
            ("C:/work", "/mnt/c/work"),
            (r"D:\data\sub", "/mnt/d/data/sub"),
            ("C:", "/mnt/c"),
        ] {
            assert_eq!(
                container_working_directory(cwd),
                Ok(Some(expected.to_string())),
                "cwd {cwd:?}"
            );
        }
    }

    #[test]
    fn cwd_unmappable_values_are_rejected() {
        for cwd in ["/workspace", "work", "sub/dir", "C:work", r"\\server\share"] {
            let err = container_working_directory(cwd).unwrap_err();
            assert!(
                err.contains(&format!("{cwd:?}")),
                "error must name the value {cwd:?}: {err}"
            );
            assert!(
                err.contains("process.cwd"),
                "error must name the field: {err}"
            );
        }
    }

    #[test]
    fn cwd_interior_nul_is_rejected_not_truncated() {
        let err = container_working_directory("C:\\work\0ignored")
            .expect_err("an interior NUL must be rejected, not truncated at the C boundary");
        assert!(
            err.contains("interior NUL"),
            "error explains the cause: {err}"
        );
    }

    // -- Volume mount tests --

    #[test]
    fn build_mounts_mixed_rw_ro() {
        let rw = vec![r"C:\workspace".to_string()];
        let ro = vec![r"D:\data".to_string()];
        let mounts = build_volume_mounts(&rw, &ro).unwrap();

        assert_eq!(mounts.len(), 2);
        assert_eq!(mounts[0].container_path, "/mnt/c/workspace");
        assert!(!mounts[0].read_only);
        assert_eq!(mounts[1].container_path, "/mnt/d/data");
        assert!(mounts[1].read_only);
    }

    #[test]
    fn build_mounts_rejects_unc_readwrite() {
        let rw = vec![r"\\server\share".to_string()];
        let ro = vec![];
        let err = build_volume_mounts(&rw, &ro).unwrap_err();

        assert!(
            err.contains("\\\\server\\share"),
            "error should cite the path: {err}"
        );
        assert!(err.contains("UNC"), "error should mention UNC: {err}");
    }

    #[test]
    fn build_mounts_rejects_unc_readonly() {
        let rw = vec![];
        let ro = vec![r"\\nas\docs".to_string()];
        let err = build_volume_mounts(&rw, &ro).unwrap_err();

        assert!(
            err.contains("\\\\nas\\docs"),
            "error should cite the path: {err}"
        );
        assert!(
            err.contains("readonlyPaths"),
            "error should identify the field: {err}"
        );
    }

    #[test]
    fn build_mounts_rejects_unc_mixed_with_valid() {
        // Even if valid paths are present, a single UNC path fails the whole call.
        let rw = vec![r"\\server\share".to_string(), r"C:\valid".to_string()];
        let ro = vec![];
        let err = build_volume_mounts(&rw, &ro).unwrap_err();

        assert!(err.contains("\\\\server\\share"));
    }

    #[test]
    fn build_mounts_rejects_relative_path() {
        let rw = vec!["relative/path".to_string()];
        let ro = vec![];
        let err = build_volume_mounts(&rw, &ro).unwrap_err();

        assert!(err.contains("relative/path"));
    }

    #[test]
    fn build_mounts_empty_paths() {
        let mounts = build_volume_mounts(&[], &[]).unwrap();
        assert!(mounts.is_empty());
    }

    // -- Denied-path overlap validation tests --

    fn strings(paths: &[&str]) -> Vec<String> {
        paths.iter().map(|path| (*path).to_string()).collect()
    }

    /// Build a fake path resolver from explicit mappings; unmapped paths resolve
    /// to `Absent` (cleanly missing), so tier 2 skips them.
    fn resolver(map: Vec<(&'static str, PathCanonical)>) -> impl Fn(&str) -> PathCanonical {
        move |path: &str| {
            map.iter()
                .find(|(key, _)| *key == path)
                .map(|(_, value)| value.clone())
                .unwrap_or(PathCanonical::Absent)
        }
    }

    fn canonical(path: &str) -> PathCanonical {
        PathCanonical::Canonical(path.to_string())
    }

    #[test]
    fn canonical_rejects_denied_alias_resolving_into_mount() {
        // Deny `C:\link` is a symlink whose target lands inside the mounted tree.
        let resolve = resolver(vec![
            (r"C:\project", canonical(r"C:\project")),
            (r"C:\link", canonical(r"C:\project\secret")),
        ]);
        let err = validate_denied_path_overlap_with(
            &strings(&[r"C:\project"]),
            &[],
            &strings(&[r"C:\link"]),
            resolve,
        )
        .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
        assert!(err.contains("symlink, junction"), "{err}");
    }

    #[test]
    fn canonical_rejects_mounted_alias_containing_denied() {
        // Mount `C:\junction` resolves to `C:\real`, whose subtree holds the deny.
        let resolve = resolver(vec![
            (r"C:\junction", canonical(r"C:\real")),
            (r"C:\real\secret", canonical(r"C:\real\secret")),
        ]);
        let err = validate_denied_path_overlap_with(
            &strings(&[r"C:\junction"]),
            &[],
            &strings(&[r"C:\real\secret"]),
            resolve,
        )
        .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn canonical_fails_closed_on_unresolvable_denied_path() {
        let resolve = resolver(vec![
            (r"C:\mount", canonical(r"C:\mount")),
            (r"C:\denied", PathCanonical::Unknown),
        ]);
        let err = validate_denied_path_overlap_with(
            &strings(&[r"C:\mount"]),
            &[],
            &strings(&[r"C:\denied"]),
            resolve,
        )
        .unwrap_err();

        assert!(err.contains("fails closed"), "{err}");
    }

    #[test]
    fn canonical_fails_closed_on_unresolvable_mount() {
        let resolve = resolver(vec![
            (r"C:\mount", PathCanonical::Unknown),
            (r"C:\denied", canonical(r"C:\denied")),
        ]);
        let err = validate_denied_path_overlap_with(
            &strings(&[r"C:\mount"]),
            &[],
            &strings(&[r"C:\denied"]),
            resolve,
        )
        .unwrap_err();

        assert!(err.contains("fails closed"), "{err}");
    }

    #[test]
    fn canonical_allows_non_overlapping_resolved_paths() {
        let resolve = resolver(vec![
            (r"C:\a", canonical(r"C:\a")),
            (r"C:\b", canonical(r"C:\b")),
        ]);
        validate_denied_path_overlap_with(&strings(&[r"C:\a"]), &[], &strings(&[r"C:\b"]), resolve)
            .expect("non-overlapping resolved paths must pass");
    }

    #[test]
    fn canonical_skips_absent_denied_path() {
        // Absent now means no on-disk ancestor resolved (e.g. a missing drive),
        // which cannot overlap any mount, so tier 2 lets it pass.
        let resolve = resolver(vec![(r"C:\mount", canonical(r"C:\mount"))]);
        validate_denied_path_overlap_with(
            &strings(&[r"C:\mount"]),
            &[],
            &strings(&[r"C:\ghost"]),
            resolve,
        )
        .expect("absent denied path must pass");
    }

    #[test]
    fn canonical_rejects_absent_leaf_resolving_under_aliased_mount() {
        // A not-yet-created deny whose parent alias resolves inside the mount:
        // the tail-tolerant resolver hands back the in-tree canonical form, so
        // the overlap must still be rejected (finding B).
        let resolve = resolver(vec![
            (r"C:\junction", canonical(r"C:\real")),
            (r"C:\junction\secret", canonical(r"C:\real\secret")),
        ]);
        let err = validate_denied_path_overlap_with(
            &strings(&[r"C:\junction"]),
            &[],
            &strings(&[r"C:\junction\secret"]),
            resolve,
        )
        .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn canonical_rejects_denied_alias_equal_to_mount_root() {
        // Absent-tail deny whose parent alias lands *exactly* on the mount root:
        // D6 saw the deny as absent, but tail replay canonicalizes it onto the
        // mount root. `contains_strictly` (strictly deeper only) misses this equal
        // case, so Tier 2's explicit canonical-equality check must reject it.
        let resolve = resolver(vec![
            (r"C:\real", canonical(r"C:\real")),
            (r"C:\link\missing\..", canonical(r"C:\real")),
        ]);
        let err = validate_denied_path_overlap_with(
            &strings(&[r"C:\real"]),
            &[],
            &strings(&[r"C:\link\missing\.."]),
            resolve,
        )
        .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn canonical_allows_literal_exact_match_that_resolves() {
        // A literal deny == mount (same original string) that both canonicalize to
        // an existing object must still be accepted: parse-time normalization
        // collapses it most-restrictive-wins, and it is enforceable by simply not
        // mounting the path. Only alias-induced equality (differing originals) is
        // rejected, so an identical string must survive Tier 2.
        let resolve = resolver(vec![(r"C:\project", canonical(r"C:\project"))]);
        validate_denied_path_overlap_with(
            &strings(&[r"C:\project"]),
            &[],
            &strings(&[r"C:\project"]),
            resolve,
        )
        .expect("literal exact-match deny is enforceable and must be accepted");
    }

    #[test]
    fn canonical_allows_case_and_separator_variant_exact_match() {
        // `NormalizedPath::parse` case-folds and folds `/` vs `\`, so these are the
        // same spelling, not an on-disk alias: enforceable by not mounting → accept.
        let resolve = resolver(vec![
            (r"C:\Project", canonical(r"C:\project")),
            ("c:/project", canonical(r"C:\project")),
        ]);
        validate_denied_path_overlap_with(
            &strings(&[r"C:\Project"]),
            &[],
            &strings(&["c:/project"]),
            resolve,
        )
        .expect("case/separator variant of the same path must be accepted");
    }

    #[test]
    fn canonical_allows_dot_dot_variant_exact_match() {
        // `C:\x\..\project` folds to `C:\project` lexically — same spelling, not an alias.
        let resolve = resolver(vec![
            (r"C:\project", canonical(r"C:\project")),
            (r"C:\x\..\project", canonical(r"C:\project")),
        ]);
        validate_denied_path_overlap_with(
            &strings(&[r"C:\project"]),
            &[],
            &strings(&[r"C:\x\..\project"]),
            resolve,
        )
        .expect("`..`-variant of the same path must be accepted");
    }

    #[test]
    fn canonical_allows_trailing_separator_variant_exact_match() {
        // `parse` drops empty segments, so a trailing separator is the same spelling.
        let resolve = resolver(vec![
            (r"C:\project", canonical(r"C:\project")),
            (r"C:\project\", canonical(r"C:\project")),
        ]);
        validate_denied_path_overlap_with(
            &strings(&[r"C:\project"]),
            &[],
            &strings(&[r"C:\project\"]),
            resolve,
        )
        .expect("trailing-separator variant of the same path must be accepted");
    }

    #[test]
    fn empty_mounts_never_fail_closed() {
        // With no mounts nothing can overlap, so an unresolvable deny must NOT
        // be rejected (finding C).
        let resolve = resolver(vec![(r"C:\denied", PathCanonical::Unknown)]);
        validate_denied_path_overlap_with(&[], &[], &strings(&[r"C:\denied"]), resolve)
            .expect("no mounts means no possible overlap");
    }

    #[test]
    fn overlap_rejects_denied_child_of_readwrite_parent() {
        let err = validate_denied_path_overlap(
            &strings(&[r"C:\project"]),
            &[],
            &strings(&[r"C:\project\secrets"]),
        )
        .unwrap_err();

        assert!(
            err.contains(r"C:\project\secrets"),
            "error should cite the denied path: {err}"
        );
        assert!(
            err.contains(r"C:\project"),
            "error should cite the parent mount: {err}"
        );
        assert!(
            err.contains("readwritePaths"),
            "error should identify the mounting list: {err}"
        );
    }

    #[test]
    fn overlap_rejects_denied_child_of_readonly_parent() {
        let err = validate_denied_path_overlap(
            &[],
            &strings(&[r"C:\data"]),
            &strings(&[r"C:\data\private\keys"]),
        )
        .unwrap_err();

        assert!(err.contains("readonlyPaths"), "{err}");
    }

    #[test]
    fn overlap_allows_non_overlapping_denied_path() {
        // Denied path shares no mounted ancestor — WSLC just never mounts it.
        validate_denied_path_overlap(&strings(&[r"C:\project"]), &[], &strings(&[r"D:\secrets"]))
            .expect("non-overlapping denied path must be accepted");
    }

    #[test]
    fn overlap_allows_exact_path_match() {
        // Exact match is enforceable by simply not mounting the path; it is not
        // a nested-under-parent overlap.
        validate_denied_path_overlap(&strings(&[r"C:\project"]), &[], &strings(&[r"C:\project"]))
            .expect("exact-path deny is enforceable and must be accepted");
    }

    #[test]
    fn overlap_ignores_partial_component_prefix() {
        // "C:\project2" is not a child of "C:\project" — component-wise compare.
        validate_denied_path_overlap(
            &strings(&[r"C:\project"]),
            &[],
            &strings(&[r"C:\project2\secrets"]),
        )
        .expect("partial-component prefix must not count as an overlap");
    }

    #[test]
    fn overlap_is_case_and_separator_insensitive() {
        // Windows paths are case-insensitive; mixed separators and casing must
        // still be detected as an overlap.
        let err = validate_denied_path_overlap(
            &strings(&[r"C:\Project"]),
            &[],
            &strings(&["c:/project/Secrets"]),
        )
        .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn overlap_is_case_insensitive_for_non_ascii_components() {
        // NTFS folds non-ASCII case (C:\Ä == c:\ä), so a denied child differing
        // only by non-ASCII case from a mounted parent must still be rejected.
        let err =
            validate_denied_path_overlap(&strings(&["C:\\Ä"]), &[], &strings(&["c:\\ä\\secret"]))
                .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn overlap_detects_child_of_mounted_drive_root() {
        // Mounting a whole drive means any denied subpath is unenforceable.
        let err =
            validate_denied_path_overlap(&strings(&[r"C:\"]), &[], &strings(&[r"C:\Windows"]))
                .unwrap_err();

        assert!(err.contains(r"C:\Windows"), "{err}");
    }

    #[test]
    fn overlap_allows_denied_parent_of_mounted_child() {
        // The reverse nesting is out of scope: the denied parent is simply not
        // mounted, and the explicit child mount is an intentional carve-out.
        validate_denied_path_overlap(
            &strings(&[r"C:\project\src"]),
            &[],
            &strings(&[r"C:\project"]),
        )
        .expect("denied ancestor of a mounted child is not this overlap case");
    }

    #[test]
    fn overlap_empty_denied_paths_is_ok() {
        validate_denied_path_overlap(&strings(&[r"C:\project"]), &strings(&[r"D:\data"]), &[])
            .expect("no denied paths means nothing to validate");
    }

    #[test]
    fn overlap_reports_first_offending_pair_across_lists() {
        // A denied path nested under a read-only mount is caught even when a
        // read-write mount is also present and unrelated.
        let err = validate_denied_path_overlap(
            &strings(&[r"D:\unrelated"]),
            &strings(&[r"C:\app"]),
            &strings(&[r"C:\app\config\token"]),
        )
        .unwrap_err();

        assert!(err.contains("readonlyPaths"), "{err}");
        assert!(err.contains(r"C:\app\config\token"), "{err}");
    }

    #[test]
    fn overlap_rejects_dotdot_traversal_in_denied_path() {
        // `C:\outside\..\project\secrets` lexically folds to `C:\project\secrets`,
        // which is under the mounted `C:\project`.
        let err = validate_denied_path_overlap(
            &strings(&[r"C:\project"]),
            &[],
            &strings(&[r"C:\outside\..\project\secrets"]),
        )
        .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn overlap_rejects_dotdot_traversal_in_mounted_path() {
        // The mount `C:\project\sub\..` folds to `C:\project`, whose subtree
        // includes the denied `C:\project\secret`.
        let err = validate_denied_path_overlap(
            &strings(&[r"C:\project\sub\.."]),
            &[],
            &strings(&[r"C:\project\secret"]),
        )
        .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn overlap_rejects_child_of_bare_root_mount() {
        // A drive-less root mount (`\`) covers the whole current drive, so any
        // same-anchor denied path under it is unenforceable.
        let err =
            validate_denied_path_overlap(&strings(&[r"\"]), &[], &strings(&[r"\project\secret"]))
                .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn overlap_rejects_drive_relative_denied_under_full_drive() {
        // A whole-drive mount (`C:\`) covers even drive-relative spellings
        // (`C:secrets`), which resolve somewhere on the same drive.
        let err = validate_denied_path_overlap(&strings(&[r"C:\"]), &[], &strings(&[r"C:secrets"]))
            .unwrap_err();

        assert!(err.contains("cannot be enforced"), "{err}");
    }

    #[test]
    fn overlap_allows_absolute_vs_relative_no_false_positive() {
        // Rooted `\project` and relative `project\secret` have different anchors
        // (rooted vs not), so this is not a provable overlap and must be accepted.
        validate_denied_path_overlap(
            &strings(&[r"\project"]),
            &[],
            &strings(&[r"project\secret"]),
        )
        .expect("absolute mount vs relative deny must not be a false rejection");
    }

    // -- Network policy tests --

    #[test]
    fn network_block_no_hosts_maps_to_none() {
        assert_eq!(
            map_network_policy(true, false),
            WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_NONE
        );
    }

    #[test]
    fn network_block_with_hosts_maps_to_bridged() {
        assert_eq!(
            map_network_policy(true, true),
            WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_BRIDGED
        );
    }

    #[test]
    fn network_allow_maps_to_bridged() {
        assert_eq!(
            map_network_policy(false, false),
            WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_BRIDGED
        );
    }

    // -- Host filtering tests --

    #[test]
    fn needs_host_filtering_empty() {
        assert!(!needs_host_filtering(true, &[], &[]));
        assert!(!needs_host_filtering(false, &[], &[]));
    }

    #[test]
    fn needs_host_filtering_block_with_allowed() {
        assert!(needs_host_filtering(true, &["1.2.3.4".to_string()], &[]));
    }

    #[test]
    fn needs_host_filtering_allow_with_blocked() {
        assert!(needs_host_filtering(false, &[], &["evil.com".to_string()]));
    }

    #[test]
    fn needs_host_filtering_block_with_blocked_only_is_false() {
        // block + blockedHosts makes no sense — blocking is already the default
        assert!(!needs_host_filtering(true, &[], &["evil.com".to_string()]));
    }

    #[test]
    fn needs_host_filtering_allow_with_allowed_only_is_false() {
        // allow + allowedHosts makes no sense — everything is already allowed
        assert!(!needs_host_filtering(false, &["1.2.3.4".to_string()], &[]));
    }

    // -- Path edge case tests --

    #[test]
    fn path_drive_relative_returns_none() {
        // C:folder (no separator after colon) is invalid
        assert_eq!(windows_path_to_container_path("C:folder"), None);
    }

    #[test]
    fn path_bare_drive_returns_some() {
        // C: (just drive letter + colon) is valid
        assert_eq!(
            windows_path_to_container_path("C:"),
            Some("/mnt/c".to_string())
        );
    }

    #[test]
    fn iptables_none_when_no_hosts() {
        assert!(build_iptables_rules(&[], &[], true).is_none());
        assert!(build_iptables_rules(&[], &[], false).is_none());
    }

    #[test]
    fn iptables_block_with_allowed_hosts() {
        let rules = build_iptables_rules(
            &["1.2.3.4".to_string(), "example.com".to_string()],
            &[],
            true,
        )
        .unwrap();
        assert!(rules.contains("iptables -A OUTPUT -o lo -j ACCEPT"));
        assert!(rules.contains("iptables -A OUTPUT -d 1.2.3.4 -j ACCEPT"));
        assert!(rules.contains("iptables -A OUTPUT -d example.com -j ACCEPT"));
        assert!(rules.contains("iptables -A OUTPUT -j DROP"));
    }

    #[test]
    fn iptables_allow_with_blocked_hosts() {
        let rules = build_iptables_rules(
            &[],
            &["evil.com".to_string(), "10.0.0.1".to_string()],
            false,
        )
        .unwrap();
        assert!(rules.contains("iptables -A OUTPUT -d evil.com -j DROP"));
        assert!(rules.contains("iptables -A OUTPUT -d 10.0.0.1 -j DROP"));
        assert!(!rules.contains("-j ACCEPT"));
    }

    #[test]
    fn is_valid_host_accepts_valid_entries() {
        assert!(is_valid_host("example.com"));
        assert!(is_valid_host("192.168.1.1"));
        assert!(is_valid_host("10.0.0.0/8"));
        assert!(is_valid_host("my-host.example.com"));
        assert!(is_valid_host("::1"));
        assert!(is_valid_host("[::1]"));
        assert!(is_valid_host("2001:db8::1"));
    }

    #[test]
    fn is_valid_host_rejects_injection() {
        assert!(!is_valid_host(""));
        assert!(!is_valid_host("; rm -rf /"));
        assert!(!is_valid_host("host && echo pwned"));
        assert!(!is_valid_host("host | cat /etc/passwd"));
        assert!(!is_valid_host("$(whoami)"));
        assert!(!is_valid_host("host`id`"));
        assert!(!is_valid_host("host name with spaces"));
    }

    #[test]
    fn iptables_skips_invalid_hosts() {
        let rules = build_iptables_rules(
            &[],
            &[
                "good.com".to_string(),
                "; rm -rf /".to_string(),
                "10.0.0.1".to_string(),
            ],
            false,
        )
        .unwrap();
        assert!(rules.contains("good.com"));
        assert!(rules.contains("10.0.0.1"));
        assert!(!rules.contains("rm"));
    }
}