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

//! Canonical host-path resolution ("full alias canonicalization").
//!
//! The lexical path folding used by backend overlap checks (e.g. WSLC's
//! `validate_denied_path_overlap`) collapses `.`/`..` and case, but cannot see
//! *on-disk* aliases: a symlink, junction, 8.3 short name, or `\\?\` prefix that
//! redirects one path into another tree only diverges once the OS resolves it.
//! [`canonicalize_path`] opens the object and asks Windows for its final path
//! (`GetFinalPathNameByHandleW`), collapsing every such alias to one canonical
//! DOS spelling that callers can compare structurally.
//!
//! Like [`crate::mxc_common::filesystem_object`] this does file I/O, so it lives in
//! `mxc_common` and is invoked by backend runners close to the point of
//! enforcement. A path that exists but cannot be resolved is reported as
//! [`PathCanonical::Unknown`] (distinct from a cleanly-missing
//! [`PathCanonical::Absent`]) so callers can **fail closed** when `deniedPaths`
//! are present rather than fall back to a weaker textual compare.

/// Result of resolving a host path to its canonical on-disk form.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathCanonical {
    /// Resolved to a canonical DOS path with aliases (symlinks, junctions, 8.3
    /// names, `\\?\` prefixes) collapsed.
    Canonical(String),
    /// Cleanly missing — no object exists, so there is nothing to alias.
    Absent,
    /// Present (or maybe present) but unresolvable: access denied, I/O error, or
    /// an unsupported build target. Callers fail closed on this when denies apply.
    Unknown,
}

/// Resolve `path` to its canonical on-disk form, collapsing alias spellings.
///
/// Returns [`PathCanonical::Absent`] for a cleanly-missing path and
/// [`PathCanonical::Unknown`] when the object exists but cannot be examined.
#[cfg(windows)]
pub fn canonicalize_path(path: &str) -> PathCanonical {
    use windows::core::{HRESULT, PCWSTR};
    use windows::Win32::Foundation::{
        CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, HANDLE,
    };
    use windows::Win32::Storage::FileSystem::{
        CreateFileW, GetFinalPathNameByHandleW, FILE_FLAG_BACKUP_SEMANTICS,
        FILE_FLAG_OPEN_REPARSE_POINT, FILE_NAME_NORMALIZED, FILE_READ_ATTRIBUTES,
        FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GETFINALPATHNAMEBYHANDLE_FLAGS,
        OPEN_EXISTING, VOLUME_NAME_DOS,
    };

    // RAII guard so the handle is closed on every exit path, including an
    // allocation unwind between the two GetFinalPathNameByHandleW calls.
    struct OwnedHandle(HANDLE);
    impl Drop for OwnedHandle {
        fn drop(&mut self) {
            // SAFETY: only constructed from a valid CreateFileW handle.
            unsafe {
                let _ = CloseHandle(self.0);
            }
        }
    }

    let wide: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
    let share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

    // Open without data access; FILE_FLAG_BACKUP_SEMANTICS lets the same call
    // open directories as well as files. SAFETY: `wide` is a local
    // NUL-terminated buffer; all other pointers are NULL.
    let handle = unsafe {
        CreateFileW(
            PCWSTR(wide.as_ptr()),
            FILE_READ_ATTRIBUTES.0,
            share,
            None,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS,
            None,
        )
    };
    let handle = match handle {
        Ok(h) if !h.is_invalid() => OwnedHandle(h),
        Err(e) => {
            // Distinguish a cleanly-missing path from an unexaminable one using
            // the error captured by the failed call itself (no second, racy
            // GetLastError round-trip).
            let code = e.code();
            if code != HRESULT::from_win32(ERROR_FILE_NOT_FOUND.0)
                && code != HRESULT::from_win32(ERROR_PATH_NOT_FOUND.0)
            {
                // Exists but unexaminable (access denied, I/O error, …).
                return PathCanonical::Unknown;
            }
            // "Not found" from the open above is ambiguous: that open *follows*
            // reparse points, so a dangling symlink/junction (the link object
            // exists but its target is missing) also reports FILE/PATH_NOT_FOUND.
            // Re-probe without following the reparse point; if the link itself
            // opens, the path exists but cannot be resolved — classify it Unknown
            // so denied-path callers fail closed rather than replay a stale alias.
            // SAFETY: `wide` is a local NUL-terminated buffer; all other pointers
            // are NULL.
            let reparse = unsafe {
                CreateFileW(
                    PCWSTR(wide.as_ptr()),
                    FILE_READ_ATTRIBUTES.0,
                    share,
                    None,
                    OPEN_EXISTING,
                    FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
                    None,
                )
            };
            return match reparse {
                // The link object itself exists: present but unresolvable →
                // fail closed. Drop the probe handle immediately via the guard.
                Ok(h) if !h.is_invalid() => {
                    let _guard = OwnedHandle(h);
                    PathCanonical::Unknown
                }
                // Success with an invalid handle: no error to read → unexaminable.
                Ok(_) => PathCanonical::Unknown,
                Err(e) => {
                    let code = e.code();
                    if code == HRESULT::from_win32(ERROR_FILE_NOT_FOUND.0)
                        || code == HRESULT::from_win32(ERROR_PATH_NOT_FOUND.0)
                    {
                        // Genuinely missing (or a missing parent): absent.
                        PathCanonical::Absent
                    } else {
                        // Present but unexaminable (access denied, sharing
                        // violation, I/O) → fail closed.
                        PathCanonical::Unknown
                    }
                }
            };
        }
        // CreateFileW reported success but returned an invalid handle: there is
        // no error to read, so treat the path as unexaminable.
        Ok(_) => return PathCanonical::Unknown,
    };

    let flags = GETFINALPATHNAMEBYHANDLE_FLAGS(FILE_NAME_NORMALIZED.0 | VOLUME_NAME_DOS.0);
    // Probe the required length (incl. NUL) with an empty buffer, then fetch.
    // SAFETY: `handle.0` is valid; an empty slice is a valid zero-length buffer.
    let needed = unsafe { GetFinalPathNameByHandleW(handle.0, &mut [], flags) };
    if needed == 0 {
        return PathCanonical::Unknown;
    }

    let mut buf = vec![0u16; needed as usize];
    // SAFETY: `handle.0` is valid; `buf` holds `needed` elements.
    let written = unsafe { GetFinalPathNameByHandleW(handle.0, &mut buf, flags) };
    // 0 = failure; `>= len` means the path grew between calls (race) — treat
    // either as unresolvable rather than returning a truncated path.
    if written == 0 || written as usize >= buf.len() {
        return PathCanonical::Unknown;
    }

    let resolved = String::from_utf16_lossy(&buf[..written as usize]);
    PathCanonical::Canonical(strip_extended_prefix(&resolved))
}

/// Non-Windows builds have no final-path resolution; report every existing path
/// as unresolvable so callers fail closed when `deniedPaths` are present.
#[cfg(not(windows))]
pub fn canonicalize_path(_path: &str) -> PathCanonical {
    PathCanonical::Unknown
}

/// Like [`canonicalize_path`] but tolerates a not-yet-created leaf: when the
/// full path is missing it resolves the deepest existing ancestor (collapsing
/// its aliases) and replays the missing tail onto it. This lets callers compare
/// a denied path that does not exist yet but whose parent is an alias
/// (symlink/junction) into a mounted tree. Mirrors the bubblewrap runner's
/// `resolve_through_symlinks`. Returns [`PathCanonical::Absent`] only when no
/// ancestor resolves.
#[cfg(windows)]
pub fn canonicalize_allowing_absent_tail(path: &str) -> PathCanonical {
    use std::path::{Component, Path, PathBuf};

    #[cfg(test)]
    super::filesystem_probe::launch_tests::stall("wslc-overlap", path);

    match canonicalize_path(path) {
        PathCanonical::Canonical(resolved) => return PathCanonical::Canonical(resolved),
        PathCanonical::Unknown => return PathCanonical::Unknown,
        PathCanonical::Absent => {}
    }

    // Capture tail components verbatim (as `Component`, not `file_name`, which
    // returns `None` for `.`/`..`) so they survive to the replay below; the OS
    // already folds any `.`/`..` in the existing-ancestor portion.
    let mut tail: Vec<Component> = Vec::new();
    let mut cur = Path::new(path);
    while let Some(parent) = cur.parent() {
        if let Some(comp) = cur.components().next_back() {
            tail.push(comp);
        }
        match canonicalize_path(&parent.to_string_lossy()) {
            PathCanonical::Canonical(base) => {
                // Replay the absent tail onto the resolved ancestor, folding
                // `.`/`..` by push/pop so e.g. `X\..\Z` collapses to `Z` rather
                // than being mis-reconstructed as `X\Z`.
                let mut result = PathBuf::from(base);
                for comp in tail.iter().rev() {
                    match comp {
                        Component::Normal(name) => result.push(name),
                        Component::ParentDir => {
                            result.pop();
                        }
                        Component::CurDir => {}
                        // A prefix/root below an existing ancestor is impossible.
                        _ => {}
                    }
                }
                return PathCanonical::Canonical(result.to_string_lossy().into_owned());
            }
            PathCanonical::Unknown => return PathCanonical::Unknown,
            PathCanonical::Absent => {}
        }
        cur = parent;
    }
    PathCanonical::Absent
}

/// Non-Windows stub — see the [`canonicalize_path`] non-Windows variant.
#[cfg(not(windows))]
pub fn canonicalize_allowing_absent_tail(_path: &str) -> PathCanonical {
    PathCanonical::Unknown
}

/// Strip a Win32 extended-length prefix from a canonical path:
/// `\\?\C:\dir` → `C:\dir`, `\\?\UNC\server\share` → `\\server\share`.
#[cfg(windows)]
fn strip_extended_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()
    }
}

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

    #[cfg(windows)]
    #[test]
    fn strip_prefix_drive() {
        assert_eq!(strip_extended_prefix(r"\\?\C:\dir\file"), r"C:\dir\file");
    }

    #[cfg(windows)]
    #[test]
    fn strip_prefix_unc() {
        assert_eq!(
            strip_extended_prefix(r"\\?\UNC\server\share\file"),
            r"\\server\share\file"
        );
    }

    #[cfg(windows)]
    #[test]
    fn strip_prefix_absent_is_passthrough() {
        assert_eq!(strip_extended_prefix(r"C:\dir"), r"C:\dir");
    }

    #[cfg(windows)]
    #[test]
    fn canonicalizes_existing_dir() {
        let dir = std::env::temp_dir();
        let dir = dir.to_string_lossy();
        match canonicalize_path(&dir) {
            PathCanonical::Canonical(resolved) => {
                // The resolved form carries no extended prefix and names a drive.
                assert!(!resolved.starts_with(r"\\?\"), "{resolved}");
                assert!(resolved.contains(':'), "{resolved}");
            }
            other => panic!("expected Canonical for temp dir, got {other:?}"),
        }
    }

    #[cfg(windows)]
    #[test]
    fn missing_path_is_absent() {
        let missing = format!(r"C:\mxc-canonical-nonexistent-{}\child", std::process::id());
        assert_eq!(canonicalize_path(&missing), PathCanonical::Absent);
    }

    #[cfg(windows)]
    #[test]
    fn absent_tail_resolves_under_existing_ancestor() {
        // An existing directory with a not-yet-created child: the leaf is
        // Absent to `canonicalize_path` but the tail-tolerant resolver returns
        // the canonical ancestor with the missing child re-appended.
        let dir = std::env::temp_dir();
        let dir = dir.to_string_lossy();
        let child = format!(
            r"{}\mxc-absent-leaf-{}",
            dir.trim_end_matches('\\'),
            std::process::id()
        );
        assert_eq!(canonicalize_path(&child), PathCanonical::Absent);
        match canonicalize_allowing_absent_tail(&child) {
            PathCanonical::Canonical(resolved) => {
                assert!(
                    resolved.ends_with(&format!("mxc-absent-leaf-{}", std::process::id())),
                    "{resolved}"
                );
                assert!(!resolved.starts_with(r"\\?\"), "{resolved}");
            }
            other => panic!("expected Canonical for absent leaf, got {other:?}"),
        }
    }

    #[cfg(windows)]
    #[test]
    fn absent_tail_on_missing_drive_is_absent() {
        // No ancestor resolves (drive absent) → Absent, not a spurious Unknown.
        // Pick a genuinely unassigned drive letter at runtime rather than
        // hard-coding one: on a host where the chosen drive exists (mapped
        // network share, USB, subst) the root would resolve and the tail would
        // replay to Canonical, not Absent.
        let Some(free) = first_free_drive_letter() else {
            eprintln!("skipping: no free drive letter available on this host");
            return;
        };
        let missing = format!(r"{free}:\mxc-no-such-drive\child");
        assert_eq!(
            canonicalize_allowing_absent_tail(&missing),
            PathCanonical::Absent
        );
    }

    /// Returns a drive letter (`D`..=`Z`) with no assigned volume, or `None` if
    /// every letter is in use. Skips `A`/`B`/`C` to avoid floppy/system drives.
    #[cfg(windows)]
    fn first_free_drive_letter() -> Option<char> {
        use windows::Win32::Storage::FileSystem::GetLogicalDrives;
        // Bit i (0 = A) is set when that drive letter is assigned.
        let mask = unsafe { GetLogicalDrives() };
        ('D'..='Z').find(|letter| {
            let bit = (*letter as u32) - ('A' as u32);
            mask & (1 << bit) == 0
        })
    }

    #[cfg(windows)]
    #[test]
    fn absent_tail_folds_dotdot_across_aliased_ancestor() {
        // Regression: an aliased (junction) ancestor + multiple non-existent
        // components + `..`. The deepest existing ancestor is the junction,
        // resolved by the OS; the absent tail `sub\..\Z` must fold to `Z` on the
        // real target, not be mis-reconstructed as `sub\Z`.
        use std::process::Command;

        let tmp = std::env::temp_dir();
        let base = format!(
            r"{}\mxc-dotdot-{}",
            tmp.to_string_lossy().trim_end_matches('\\'),
            std::process::id()
        );
        let real = format!(r"{base}\real");
        let link = format!(r"{base}\link");
        std::fs::create_dir_all(&real).unwrap();

        let status = Command::new("cmd")
            .args(["/c", "mklink", "/J", &link, &real])
            .status()
            .unwrap();
        if !status.success() {
            eprintln!(
                "skipping absent_tail_folds_dotdot_across_aliased_ancestor: mklink /J failed"
            );
            let _ = std::fs::remove_dir_all(&base);
            return;
        }

        // `link` exists (→ real); `sub` and `Z` do not. `sub\..\Z` must fold to
        // `real\Z`, so the resolved form ends with `real\Z` and omits `sub`.
        let denied = format!(r"{link}\sub\..\Z");
        let resolved = match canonicalize_allowing_absent_tail(&denied) {
            PathCanonical::Canonical(r) => r,
            other => {
                let _ = std::fs::remove_dir_all(&base);
                panic!("expected Canonical, got {other:?}");
            }
        };
        let _ = std::fs::remove_dir_all(&base);

        assert!(
            resolved.to_lowercase().ends_with(r"\real\z"),
            "tail `sub\\..\\Z` must fold to `real\\Z`, got {resolved}"
        );
        assert!(
            !resolved.to_lowercase().contains(r"\sub\"),
            "`..` must cancel `sub`, got {resolved}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn dangling_reparse_point_is_unknown_not_absent() {
        // A junction whose target is missing exists as an object but makes the
        // *followed* open report FILE/PATH_NOT_FOUND. It must classify Unknown
        // (present-but-unresolvable → fail closed), never Absent, so denied-path
        // callers do not treat it as cleanly-missing and replay a stale alias.
        use std::process::Command;

        // Thread id keeps concurrent tests from colliding on the fixture dir.
        let tmp = std::env::temp_dir();
        let base = format!(
            r"{}\mxc-dangling-{}-{:?}",
            tmp.to_string_lossy().trim_end_matches('\\'),
            std::process::id(),
            std::thread::current().id()
        );
        let link = format!(r"{base}\link");
        let missing_target = format!(r"{base}\no-such-target");
        let _ = std::fs::remove_dir_all(&base); // clear any leftover from an aborted run
        std::fs::create_dir_all(&base).unwrap();

        // `mklink /J` creates a junction even when the target does not exist.
        let status = Command::new("cmd")
            .args(["/c", "mklink", "/J", &link, &missing_target])
            .status()
            .unwrap();
        // mklink /J needs no elevation, so a failure is a broken environment,
        // not an expected skip — surface it rather than silently no-op.
        assert!(
            status.success(),
            "mklink /J failed ({status}); junction creation needs no elevation, so this \
             indicates a broken test environment rather than an expected skip"
        );

        let result = canonicalize_path(&link);
        // Remove the junction itself (do not follow it) before clearing base.
        let _ = std::fs::remove_dir(&link);
        let _ = std::fs::remove_dir_all(&base);

        assert_eq!(
            result,
            PathCanonical::Unknown,
            "a dangling junction must be Unknown (fail closed), not Absent"
        );
    }

    #[cfg(windows)]
    #[test]
    fn dangling_junction_ancestor_is_unknown_not_canonical() {
        // Chain-level guard where the security property lives: a deny under a
        // dangling-junction *ancestor* must fail closed, never replay the absent
        // tail onto a resolved grandparent and return Canonical(<path with the
        // junction>) — which the overlap check would then miss.
        use std::process::Command;

        let tmp = std::env::temp_dir();
        let base = format!(
            r"{}\mxc-dangling-anc-{}-{:?}",
            tmp.to_string_lossy().trim_end_matches('\\'),
            std::process::id(),
            std::thread::current().id()
        );
        let link = format!(r"{base}\link");
        let missing_target = format!(r"{base}\no-such-target");
        let leaf = format!(r"{link}\file");
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();

        let status = Command::new("cmd")
            .args(["/c", "mklink", "/J", &link, &missing_target])
            .status()
            .unwrap();
        assert!(
            status.success(),
            "mklink /J failed ({status}); junction creation needs no elevation"
        );

        let result = canonicalize_allowing_absent_tail(&leaf);
        let _ = std::fs::remove_dir(&link);
        let _ = std::fs::remove_dir_all(&base);

        assert_eq!(
            result,
            PathCanonical::Unknown,
            "a deny under a dangling-junction ancestor must fail closed, not \
             resolve to a Canonical path still containing the junction"
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn non_windows_is_unknown() {
        assert_eq!(canonicalize_path("/tmp"), PathCanonical::Unknown);
        assert_eq!(
            canonicalize_allowing_absent_tail("/tmp/child"),
            PathCanonical::Unknown
        );
    }
}