mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Translate request policy into Windows Sandbox mapped folders and rejects.
//!
//! Windows Sandbox shares nothing by default. Mapped read/write and read-only
//! directories are additive; denied paths that overlap a mapped share are
//! rejected because Windows Sandbox has no per-path deny primitive. Network
//! isolation is currently all-or-nothing and enforced by the guest firewall.

use std::path::Path;

use crate::mxc_common::models::{ExecutionRequest, NetworkAction};

use crate::windows_sandbox_lifecycle::error::OneShotError;
use crate::windows_sandbox_lifecycle::vm::MappedFolder;

/// The enforceable shape of a request's policy for one disposable run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WsbPolicyPlan {
    /// Extra host folders to expose inside the guest.
    pub(crate) mapped_folders: Vec<MappedFolder>,
}

/// Validate the request's policy and produce a [`WsbPolicyPlan`].
pub(crate) fn plan_policy(request: &ExecutionRequest) -> Result<WsbPolicyPlan, OneShotError> {
    validate_network(request)?;
    let mapped_folders = plan_filesystem(request)?;

    Ok(WsbPolicyPlan { mapped_folders })
}

/// The guest agent enforces network lockdown; it cannot open a requested
/// connection or implement network rules.
fn validate_network(request: &ExecutionRequest) -> Result<(), OneShotError> {
    let policy = &request.policy;

    if policy.network_proxy.is_enabled() {
        return Err(OneShotError::Policy(
            "a network proxy is not supported by the Windows Sandbox backend".to_string(),
        ));
    }

    if policy.network_mode_specified
        || policy.network_egress.as_ref().is_some_and(|egress| {
            egress.default == NetworkAction::Allow
                || !egress.allow.is_empty()
                || !egress.deny.is_empty()
        })
        || policy.network_ingress.as_ref().is_some_and(|ingress| {
            ingress.default == NetworkAction::Allow || ingress.host_loopback == NetworkAction::Allow
        })
    {
        return Err(OneShotError::Policy(
            "directional network policy is not supported by the Windows Sandbox backend; \
             the guest agent enforces network isolation"
                .to_string(),
        ));
    }
    Ok(())
}

/// A mapped root in normalized form: the cleaned absolute string used for the
/// `.wsb` plus its lowercased path components for containment comparisons.
struct MappedRoot {
    display: String,
    components: Vec<String>,
    read_only: bool,
}

/// Resolve `readwrite`/`readonly` paths into mapped folders and validate
/// `deniedPaths` against them.
fn plan_filesystem(request: &ExecutionRequest) -> Result<Vec<MappedFolder>, OneShotError> {
    let policy = &request.policy;
    if !policy.enumerate_paths.is_empty() {
        return Err(OneShotError::Policy(
            "processContainer.filesystem.enumeratePaths is not supported by the Windows Sandbox backend"
                .to_string(),
        ));
    }
    let mut roots: Vec<MappedRoot> = Vec::new();

    for path in &policy.readwrite_paths {
        add_mapped_root(&mut roots, path, false)?;
    }
    for path in &policy.readonly_paths {
        add_mapped_root(&mut roots, path, true)?;
    }

    reject_denied_overlapping_shares(&policy.denied_paths, &roots)?;

    Ok(roots
        .into_iter()
        .map(|root| MappedFolder {
            host: root.display.clone(),
            sandbox: root.display,
            read_only: root.read_only,
        })
        .collect())
}

/// Canonicalize `raw`, ensure it is an existing directory, and add it to
/// `roots` — rejecting missing paths, files, conflicting read-only flags for
/// the same path, and overlapping (nested) mapped roots.
fn add_mapped_root(
    roots: &mut Vec<MappedRoot>,
    raw: &str,
    read_only: bool,
) -> Result<(), OneShotError> {
    let canonical = std::fs::canonicalize(raw).map_err(|e| {
        OneShotError::Policy(format!(
            "mapped path {raw:?} does not exist or is inaccessible (Windows Sandbox cannot map a \
             missing host folder): {e}"
        ))
    })?;

    let is_dir = canonical.is_dir();
    let display = strip_verbatim_prefix(&canonical.to_string_lossy());
    if !is_dir {
        return Err(OneShotError::Policy(format!(
            "mapped path {raw:?} is a file; Windows Sandbox can only map directories. Map its \
             parent directory instead."
        )));
    }

    let components = path_components(&display);

    for existing in roots.iter() {
        if existing.components == components {
            if existing.read_only != read_only {
                return Err(OneShotError::Policy(format!(
                    "path {display:?} is listed as both read-write and read-only"
                )));
            }
            // Identical duplicate with the same access — collapse silently.
            return Ok(());
        }
        if is_descendant(&components, &existing.components)
            || is_descendant(&existing.components, &components)
        {
            return Err(OneShotError::Policy(format!(
                "mapped path {display:?} overlaps another mapped path {:?}; Windows Sandbox \
                 rejects nested mapped folders",
                existing.display
            )));
        }
    }

    roots.push(MappedRoot {
        display,
        components,
        read_only,
    });
    Ok(())
}

/// Reject any denied path that *overlaps* a mapped share in either direction —
/// Windows Sandbox has no per-path Deny primitive, so neither carving a denied
/// hole out of a share nor denying a subtree that contains a share can be
/// honored. Denied paths outside every share are no-ops (the host shares
/// nothing by default) and are silently accepted.
///
/// Denied paths must be absolute; a relative path cannot be anchored to a host
/// location, so it is rejected fail-closed rather than silently treated as a
/// non-overlapping no-op. Overlap is decided on canonicalized components (see
/// [`normalize_denied`]) so short names / junctions / case cannot smuggle an
/// overlapping path past the check.
fn reject_denied_overlapping_shares(
    denied_paths: &[String],
    roots: &[MappedRoot],
) -> Result<(), OneShotError> {
    for denied in denied_paths {
        let denied_components = normalize_denied(denied)?;
        if denied_components.is_empty() {
            continue;
        }
        for root in roots {
            if denied_components == root.components {
                return Err(OneShotError::Policy(format!(
                    "denied path {denied:?} is the same as mapped share {:?}; the Windows Sandbox \
                     backend cannot map a folder and deny it at the same time",
                    root.display
                )));
            }
            if is_descendant(&denied_components, &root.components) {
                return Err(OneShotError::Policy(format!(
                    "denied path {denied:?} lies inside mapped share {:?}; the Windows Sandbox \
                     backend cannot carve a denied subtree out of a mapped folder",
                    root.display
                )));
            }
            if is_descendant(&root.components, &denied_components) {
                return Err(OneShotError::Policy(format!(
                    "denied path {denied:?} contains mapped share {:?}; the Windows Sandbox \
                     backend cannot deny a host subtree while a folder inside it is mapped",
                    root.display
                )));
            }
        }
    }
    Ok(())
}

/// Normalize a denied path to comparison components, mirroring the
/// canonicalization applied to mapped roots so the two are compared
/// apples-to-apples.
///
/// - Rejects a non-absolute path (it cannot be anchored to a host location).
/// - Canonicalizes the full path when it exists (resolves 8.3 short names,
///   junctions/symlinks, and case to the same form a mapped root gets).
/// - When the leaf does not yet exist, canonicalizes the longest existing
///   ancestor and appends the remaining lexical tail — but only when that
///   ancestor is a genuine prefix of the lexical path, otherwise falls back to
///   the purely lexical form rather than risk constructing a wrong path.
/// - Falls back to lexical normalization when nothing along the path exists.
fn normalize_denied(raw: &str) -> Result<Vec<String>, OneShotError> {
    let p = Path::new(raw);
    if !p.is_absolute() {
        return Err(OneShotError::Policy(format!(
            "denied path {raw:?} is not an absolute host path; deniedPaths must be absolute so the \
             Windows Sandbox backend can determine whether they overlap a mapped share"
        )));
    }

    let lexical = path_components(&strip_verbatim_prefix(raw));

    if let Ok(canonical) = std::fs::canonicalize(p) {
        return Ok(path_components(&strip_verbatim_prefix(
            &canonical.to_string_lossy(),
        )));
    }

    for ancestor in p.ancestors().skip(1) {
        if ancestor.as_os_str().is_empty() {
            continue;
        }
        if let Ok(canonical) = std::fs::canonicalize(ancestor) {
            let ancestor_lexical =
                path_components(&strip_verbatim_prefix(&ancestor.to_string_lossy()));
            // Trust the canonical ancestor only when it is a genuine prefix of
            // the lexical path; a `..` straddling a partially-existing path
            // could otherwise yield a wrong reconstruction, so prefer the
            // lexical form in that pathological case.
            if ancestor_lexical.len() <= lexical.len() && lexical.starts_with(&ancestor_lexical) {
                let mut components =
                    path_components(&strip_verbatim_prefix(&canonical.to_string_lossy()));
                components.extend_from_slice(&lexical[ancestor_lexical.len()..]);
                return Ok(components);
            }
            break;
        }
    }

    Ok(lexical)
}

/// Strip a `\\?\` or `\\?\UNC\` verbatim prefix from a Windows path string.
/// `std::fs::canonicalize` returns verbatim paths, which Windows Sandbox does
/// not accept in a `.wsb`.
fn strip_verbatim_prefix(path: &str) -> String {
    if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
        format!(r"\\{rest}")
    } else if let Some(rest) = path.strip_prefix(r"\\?\") {
        rest.to_string()
    } else {
        path.to_string()
    }
}

/// Split a path into case-folded, normalized components for case-insensitive
/// comparison. `.` segments are dropped and `..` pops the previous component.
/// Drive/separator forms are unified by splitting on both `\` and `/`. Folding
/// is Unicode-aware (`to_lowercase`) rather than ASCII-only so non-ASCII path
/// segments cannot vary in case to slip a denied path past the overlap check.
fn path_components(path: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for raw in path.split(['\\', '/']) {
        match raw {
            "" | "." => {}
            ".." => {
                out.pop();
            }
            seg => out.push(seg.to_lowercase()),
        }
    }
    out
}

/// True when `child` is strictly nested inside `ancestor` (component-wise
/// prefix, longer than the ancestor). Component-wise comparison avoids the
/// `C:\foo` vs `C:\foobar` false positive a string-prefix test would hit.
fn is_descendant(child: &[String], ancestor: &[String]) -> bool {
    child.len() > ancestor.len() && child.starts_with(ancestor)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::{
        ContainerPolicy, NetworkEgressPolicy, NetworkIngressPolicy, NetworkPeer, NetworkRule,
        ProxyAddress, ProxyConfig,
    };

    fn request_with(policy: ContainerPolicy) -> ExecutionRequest {
        ExecutionRequest {
            policy,
            ..Default::default()
        }
    }

    fn assert_policy_err_contains(err: OneShotError, expected: &str) {
        match err {
            OneShotError::Policy(msg) => {
                assert!(msg.contains(expected), "expected {expected:?} in {msg:?}")
            }
            other => panic!("expected Policy variant, got {other:?}"),
        }
    }

    fn assert_rejects_direct_network(policy: ContainerPolicy) {
        assert!(!policy.network_mode_specified);
        let err = plan_policy(&request_with(policy)).unwrap_err();
        assert_policy_err_contains(err, "directional network policy");
    }

    fn sample_rule() -> NetworkRule {
        NetworkRule {
            to: vec![NetworkPeer {
                cidr: "192.0.2.1/32".parse().unwrap(),
                except: Vec::new(),
            }],
            ..Default::default()
        }
    }

    // ===== network =====

    #[test]
    fn omitted_network_defaults_to_guest_firewall_isolation() {
        let plan = plan_policy(&ExecutionRequest::default()).unwrap();
        assert!(plan.mapped_folders.is_empty());
    }

    #[test]
    fn explicitly_supplied_network_posture_is_not_silently_ignored() {
        let err = plan_policy(&request_with(ContainerPolicy {
            network_mode_specified: true,
            network_egress: Some(crate::mxc_common::models::NetworkEgressPolicy::default()),
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "directional network policy");
    }

    #[test]
    fn allow_network_rejected() {
        let err = plan_policy(&request_with(ContainerPolicy {
            network_egress: Some(crate::mxc_common::models::NetworkEgressPolicy {
                default: NetworkAction::Allow,
                ..Default::default()
            }),
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "directional network policy");
    }

    #[test]
    fn direct_egress_allow_rule_rejected_without_presence_flag() {
        assert_rejects_direct_network(ContainerPolicy {
            network_egress: Some(NetworkEgressPolicy {
                allow: vec![sample_rule()],
                ..Default::default()
            }),
            ..Default::default()
        });
    }

    #[test]
    fn direct_egress_deny_rule_rejected_without_presence_flag() {
        assert_rejects_direct_network(ContainerPolicy {
            network_egress: Some(NetworkEgressPolicy {
                deny: vec![sample_rule()],
                ..Default::default()
            }),
            ..Default::default()
        });
    }

    #[test]
    fn direct_ingress_allow_rejected_without_presence_flag() {
        assert_rejects_direct_network(ContainerPolicy {
            network_ingress: Some(NetworkIngressPolicy {
                default: NetworkAction::Allow,
                ..Default::default()
            }),
            ..Default::default()
        });
    }

    #[test]
    fn direct_host_loopback_allow_rejected_without_presence_flag() {
        assert_rejects_direct_network(ContainerPolicy {
            network_ingress: Some(NetworkIngressPolicy {
                host_loopback: NetworkAction::Allow,
                ..Default::default()
            }),
            ..Default::default()
        });
    }

    #[test]
    fn enumerate_paths_rejected() {
        let err = plan_policy(&request_with(ContainerPolicy {
            enumerate_paths: vec!["C:\\tools".to_string()],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "processContainer.filesystem.enumeratePaths");
    }

    #[test]
    fn proxy_rejected() {
        let err = plan_policy(&request_with(ContainerPolicy {
            network_proxy: ProxyConfig {
                address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
            },
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "proxy");
    }

    // ===== filesystem =====

    #[test]
    fn readwrite_and_readonly_paths_become_mapped_folders() {
        let rw = tempfile::tempdir().unwrap();
        let ro = tempfile::tempdir().unwrap();
        let plan = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![rw.path().to_string_lossy().into_owned()],
            readonly_paths: vec![ro.path().to_string_lossy().into_owned()],
            ..Default::default()
        }))
        .unwrap();
        assert_eq!(plan.mapped_folders.len(), 2);
        let rw_folder = plan.mapped_folders.iter().find(|f| !f.read_only).unwrap();
        let ro_folder = plan.mapped_folders.iter().find(|f| f.read_only).unwrap();
        // Host parity: sandbox path equals host path.
        assert_eq!(rw_folder.host, rw_folder.sandbox);
        assert_eq!(ro_folder.host, ro_folder.sandbox);
        // No verbatim prefix leaks into the .wsb value.
        assert!(!rw_folder.host.starts_with(r"\\?\"));
    }

    #[test]
    fn missing_path_rejected() {
        let err = plan_policy(&request_with(ContainerPolicy {
            readonly_paths: vec![r"C:\definitely\not\here\xyzzy".to_string()],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "does not exist");
    }

    #[test]
    fn file_path_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.txt");
        std::fs::write(&file, b"x").unwrap();
        let err = plan_policy(&request_with(ContainerPolicy {
            readonly_paths: vec![file.to_string_lossy().into_owned()],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "is a file");
    }

    #[test]
    fn conflicting_readonly_flags_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().to_string_lossy().into_owned();
        let err = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![p.clone()],
            readonly_paths: vec![p],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "both read-write and read-only");
    }

    #[test]
    fn duplicate_same_access_collapses() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().to_string_lossy().into_owned();
        let plan = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![p.clone(), p],
            ..Default::default()
        }))
        .unwrap();
        assert_eq!(plan.mapped_folders.len(), 1);
    }

    #[test]
    fn nested_mapped_paths_rejected() {
        let parent = tempfile::tempdir().unwrap();
        let child = parent.path().join("child");
        std::fs::create_dir(&child).unwrap();
        let err = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![parent.path().to_string_lossy().into_owned()],
            readonly_paths: vec![child.to_string_lossy().into_owned()],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "overlaps");
    }

    // ===== denied paths =====

    #[test]
    fn denied_outside_shares_is_noop() {
        let dir = tempfile::tempdir().unwrap();
        let plan = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![dir.path().to_string_lossy().into_owned()],
            denied_paths: vec![r"C:\some\unrelated\secret".to_string()],
            ..Default::default()
        }))
        .unwrap();
        assert_eq!(plan.mapped_folders.len(), 1);
    }

    #[test]
    fn denied_equal_to_mapped_share_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().to_string_lossy().into_owned();
        let err = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![p.clone()],
            denied_paths: vec![p],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "same as mapped share");
    }

    #[test]
    fn denied_inside_mapped_share_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let inside = format!("{}\\secret", dir.path().to_string_lossy());
        let err = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![dir.path().to_string_lossy().into_owned()],
            denied_paths: vec![inside],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "inside mapped share");
    }

    #[test]
    fn denied_ancestor_of_mapped_share_rejected() {
        // A denied path that *contains* a mapped share is unenforceable: the
        // share remains reachable through the mapping despite the denial.
        let parent = tempfile::tempdir().unwrap();
        let child = parent.path().join("child");
        std::fs::create_dir(&child).unwrap();
        let err = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![child.to_string_lossy().into_owned()],
            denied_paths: vec![parent.path().to_string_lossy().into_owned()],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "contains mapped share");
    }

    #[test]
    fn denied_relative_path_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let err = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![dir.path().to_string_lossy().into_owned()],
            denied_paths: vec![r"relative\secret".to_string()],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "absolute");
    }

    #[test]
    fn denied_equal_share_matches_through_case_and_separator() {
        // The same existing directory written with different case and forward
        // slashes must still be recognised as the mapped share (canonicalized,
        // case-folded comparison), not slip past as a no-op.
        let dir = tempfile::tempdir().unwrap();
        let mapped = dir.path().to_string_lossy().into_owned();
        let denied = mapped.replace('\\', "/").to_uppercase();
        let err = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![mapped],
            denied_paths: vec![denied],
            ..Default::default()
        }))
        .unwrap_err();
        assert_policy_err_contains(err, "same as mapped share");
    }

    #[test]
    fn denied_nonexistent_outside_share_under_real_ancestor_is_noop() {
        // A denied leaf that does not exist but whose existing ancestor is
        // unrelated to any mapped share remains a no-op.
        let mapped = tempfile::tempdir().unwrap();
        let other = tempfile::tempdir().unwrap();
        let denied = format!("{}\\ghost\\leaf", other.path().to_string_lossy());
        let plan = plan_policy(&request_with(ContainerPolicy {
            readwrite_paths: vec![mapped.path().to_string_lossy().into_owned()],
            denied_paths: vec![denied],
            ..Default::default()
        }))
        .unwrap();
        assert_eq!(plan.mapped_folders.len(), 1);
    }

    // ===== component helpers =====

    #[test]
    fn path_components_are_case_insensitive_and_normalized() {
        assert_eq!(
            path_components(r"C:\Foo\Bar"),
            path_components(r"c:/foo/bar/")
        );
        assert_eq!(
            path_components(r"C:\foo\.\bar"),
            path_components(r"C:\foo\bar")
        );
        assert_eq!(
            path_components(r"C:\foo\baz\..\bar"),
            path_components(r"C:\foo\bar")
        );
    }

    #[test]
    fn is_descendant_avoids_prefix_false_positive() {
        let foobar = path_components(r"C:\foobar");
        let foo = path_components(r"C:\foo");
        assert!(!is_descendant(&foobar, &foo));
        let foo_child = path_components(r"C:\foo\child");
        assert!(is_descendant(&foo_child, &foo));
        // Equal is not a descendant.
        assert!(!is_descendant(&foo, &foo));
    }

    #[test]
    fn strip_verbatim_prefix_handles_drive_and_unc() {
        assert_eq!(strip_verbatim_prefix(r"\\?\C:\foo"), r"C:\foo");
        assert_eq!(
            strip_verbatim_prefix(r"\\?\UNC\server\share"),
            r"\\server\share"
        );
        assert_eq!(strip_verbatim_prefix(r"C:\foo"), r"C:\foo");
    }
}