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

//! Check that the invoking user can delegate the requested filesystem access.

use crate::mxc_common::filesystem_object::FilesystemPolicyError;
use crate::mxc_common::filesystem_probe::FilesystemProbe;
use crate::mxc_common::models::ContainerPolicy;

/// The access the invoking user must hold to delegate a path to the sandbox.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum AccessMode {
    /// Read access only (for `readonlyPaths`).
    Read,
    /// Read and write access (for `readwritePaths`).
    ReadWrite,
}

impl AccessMode {
    /// The JSON list name this mode maps to, and the access phrase, for the
    /// rejection message.
    fn list_name(self) -> &'static str {
        match self {
            AccessMode::Read => "readonlyPaths",
            AccessMode::ReadWrite => "readwritePaths",
        }
    }

    fn access_phrase(self) -> &'static str {
        match self {
            AccessMode::Read => "read",
            AccessMode::ReadWrite => "read+write",
        }
    }
}

/// What probing the invoking user's access to a path found.
#[derive(Clone, PartialEq, Eq, Debug)]
enum Access {
    Granted,
    /// The path does not exist; the existence warning reports it instead.
    Missing,
    /// The user lacks the access, or the path cannot be named on this host.
    Denied,
    /// The path could not be examined (e.g. a stale mount or I/O error).
    Uninspectable(String),
}

#[cfg(unix)]
fn user_can_access(path: &str, mode: AccessMode) -> Access {
    use std::ffi::CString;

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

    let Ok(c_path) = CString::new(path) else {
        return Access::Denied;
    };
    let mask = match mode {
        AccessMode::Read => libc::R_OK,
        AccessMode::ReadWrite => libc::R_OK | libc::W_OK,
    };

    // access(2) checks the caller's real IDs, so a root caller passes regardless of file mode.
    // SAFETY: `c_path` is a valid NUL-terminated C string for the duration of the call.
    let rc = unsafe { libc::access(c_path.as_ptr(), mask) };
    if rc == 0 {
        return Access::Granted;
    }
    classify_access_error(std::io::Error::last_os_error())
}

/// An untraversable parent reports `EACCES`, so it counts as a denial.
#[cfg(unix)]
fn classify_access_error(error: std::io::Error) -> Access {
    match error.raw_os_error() {
        Some(libc::ENOENT) | Some(libc::ENOTDIR) => Access::Missing,
        Some(libc::EACCES) | Some(libc::EPERM) | Some(libc::EROFS) => Access::Denied,
        _ => Access::Uninspectable(error.to_string()),
    }
}

#[cfg(windows)]
fn user_can_access(path: &str, mode: AccessMode) -> Access {
    use windows::core::PCWSTR;
    use windows::Win32::Foundation::{CloseHandle, GetLastError, GENERIC_READ, GENERIC_WRITE};
    use windows::Win32::Storage::FileSystem::{
        CreateFileW, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_DELETE, FILE_SHARE_READ,
        FILE_SHARE_WRITE, OPEN_EXISTING,
    };

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

    // Probe the caller's effective access by asking the OS to open the object
    // with the required rights. FILE_FLAG_BACKUP_SEMANTICS lets the same call
    // open directories as well as files, so — unlike a plain `File::open` — this
    // covers directory WRITE access (mapped by the OS to FILE_ADD_FILE /
    // FILE_ADD_SUBDIRECTORY), which is the common WSLC `readwritePaths` case.
    let wide: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
    let desired = match mode {
        AccessMode::Read => GENERIC_READ.0,
        AccessMode::ReadWrite => GENERIC_READ.0 | GENERIC_WRITE.0,
    };
    let share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

    // SAFETY: `wide` is a local NUL-terminated buffer; all other pointers are NULL.
    let handle = unsafe {
        CreateFileW(
            PCWSTR(wide.as_ptr()),
            desired,
            share,
            None,
            OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS,
            None,
        )
    };
    match handle {
        Ok(h) if !h.is_invalid() => {
            // SAFETY: `h` is a valid handle returned by CreateFileW.
            unsafe {
                let _ = CloseHandle(h);
            }
            Access::Granted
        }
        // SAFETY: reads the thread-local last error set by the failed call above.
        _ => classify_access_error(unsafe { GetLastError() }),
    }
}

#[cfg(windows)]
fn classify_access_error(error: windows::Win32::Foundation::WIN32_ERROR) -> Access {
    use windows::Win32::Foundation::{
        ERROR_ACCESS_DENIED, ERROR_FILE_NOT_FOUND, ERROR_INVALID_NAME, ERROR_PATH_NOT_FOUND,
        ERROR_WRITE_PROTECT,
    };

    match error {
        ERROR_FILE_NOT_FOUND | ERROR_PATH_NOT_FOUND => Access::Missing,
        ERROR_ACCESS_DENIED | ERROR_INVALID_NAME | ERROR_WRITE_PROTECT => Access::Denied,
        _ => Access::Uninspectable(std::io::Error::from_raw_os_error(error.0 as i32).to_string()),
    }
}

#[cfg(not(any(unix, windows)))]
fn user_can_access(_path: &str, _mode: AccessMode) -> Access {
    Access::Missing
}

pub fn check_delegation(policy: &ContainerPolicy) -> Result<(), FilesystemPolicyError> {
    let mut probe = FilesystemProbe::default();
    check_delegation_with(policy, |path, mode| {
        probe.run(path, move |path| user_can_access(path, mode))
    })
}

fn check_delegation_with(
    policy: &ContainerPolicy,
    mut check: impl FnMut(&str, AccessMode) -> Result<Access, String>,
) -> Result<(), FilesystemPolicyError> {
    for (paths, mode) in [
        (&policy.readonly_paths, AccessMode::Read),
        (&policy.readwrite_paths, AccessMode::ReadWrite),
    ] {
        for path in paths {
            match check(path, mode).map_err(FilesystemPolicyError::Host)? {
                Access::Granted | Access::Missing => {}
                Access::Denied => {
                    return Err(FilesystemPolicyError::Policy(format!(
                        "Filesystem path '{}' ({}): the invoking user does not have {} access, \
                         so it cannot be delegated to the sandbox",
                        path,
                        mode.list_name(),
                        mode.access_phrase(),
                    )));
                }
                Access::Uninspectable(reason) => {
                    return Err(FilesystemPolicyError::Host(format!(
                        "Filesystem path '{}' ({}): could not check the invoking user's {} \
                         access ({reason}), so it was not delegated to the sandbox",
                        path,
                        mode.list_name(),
                        mode.access_phrase(),
                    )));
                }
            }
        }
    }
    Ok(())
}

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

    fn policy(rw: &[&str], ro: &[&str]) -> ContainerPolicy {
        ContainerPolicy {
            readwrite_paths: rw.iter().map(|s| s.to_string()).collect(),
            readonly_paths: ro.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        }
    }

    #[test]
    fn accessible_file_is_delegable() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("data.txt");
        std::fs::write(&file, b"test").unwrap();
        let f = file.to_str().unwrap();

        assert_eq!(user_can_access(f, AccessMode::Read), Access::Granted);
        assert_eq!(user_can_access(f, AccessMode::ReadWrite), Access::Granted);
        assert!(check_delegation(&policy(&[f], &[])).is_ok());
    }

    #[test]
    fn accessible_directory_is_delegable() {
        // Directory read+write is the common WSLC `readwritePaths` case; it must
        // be enforced on both Unix and Windows.
        let dir = tempfile::tempdir().unwrap();
        let d = dir.path().to_str().unwrap();

        assert_eq!(user_can_access(d, AccessMode::Read), Access::Granted);
        assert_eq!(user_can_access(d, AccessMode::ReadWrite), Access::Granted);
        assert!(check_delegation(&policy(&[d], &[])).is_ok());
    }

    #[test]
    fn nonexistent_path_is_skipped() {
        // A non-existent path can't be access-checked; delegation skips it
        // (existence is surfaced separately as a warning, not a delegation error).
        assert_eq!(
            user_can_access("/definitely/not/here/mxc-xyz", AccessMode::Read),
            Access::Missing
        );
        assert!(check_delegation(&policy(&["/definitely/not/here/mxc-xyz"], &[])).is_ok());
    }

    #[test]
    fn empty_policy_is_ok() {
        assert!(check_delegation(&ContainerPolicy::default()).is_ok());
    }

    #[test]
    fn slow_probe_rejects_readonly_and_readwrite_grants() {
        use std::sync::mpsc;
        use std::time::Duration;

        for policy in [policy(&["slow"], &[]), policy(&[], &["slow"])] {
            let mut probe = FilesystemProbe::for_test(Duration::from_millis(100));
            let (release, wait) = mpsc::sync_channel(1);
            let mut wait = Some(wait);
            let result = check_delegation_with(&policy, |path, _| {
                let wait = wait.take().unwrap();
                probe.run(path, move |_| {
                    wait.recv_timeout(Duration::from_secs(5)).unwrap();
                    Access::Granted
                })
            });
            let _ = release.send(());
            let error = result.unwrap_err();
            assert!(
                matches!(&error, FilesystemPolicyError::Host(_)),
                "{error:?}"
            );
            assert!(error.message().contains("'slow'"), "{error:?}");
            assert!(
                error.message().contains("timed out after 100ms"),
                "{error:?}"
            );
        }
    }

    #[test]
    fn denied_paths_do_not_need_delegation_probes() {
        let policy = ContainerPolicy {
            denied_paths: vec!["denied".to_string()],
            ..Default::default()
        };
        check_delegation_with(&policy, |_, _| panic!("must not probe a denied path")).unwrap();
    }

    #[cfg(windows)]
    #[test]
    fn an_invalid_path_name_is_refused_as_a_policy_error() {
        let invalid = "C:\\mxc_invalid<name";
        assert_eq!(user_can_access(invalid, AccessMode::Read), Access::Denied);
        assert!(matches!(
            check_delegation(&policy(&[], &[invalid])),
            Err(FilesystemPolicyError::Policy(_))
        ));
    }

    /// A stale mount or I/O error is the host's fault, but still refuses the path.
    #[test]
    fn only_a_denial_blames_the_request() {
        #[cfg(unix)]
        let (denied, uninspectable) = (
            std::io::Error::from_raw_os_error(libc::EACCES),
            std::io::Error::from_raw_os_error(libc::EIO),
        );
        #[cfg(windows)]
        let (denied, uninspectable) = (
            windows::Win32::Foundation::ERROR_ACCESS_DENIED,
            windows::Win32::Foundation::ERROR_SHARING_VIOLATION,
        );

        assert_eq!(classify_access_error(denied), Access::Denied);
        assert!(matches!(
            classify_access_error(uninspectable),
            Access::Uninspectable(_)
        ));
    }

    #[cfg(unix)]
    #[test]
    fn unreadable_path_is_rejected() {
        use std::os::unix::fs::PermissionsExt;

        // Root bypasses permission checks, so this case is only meaningful as a
        // non-root user.
        if unsafe { libc::geteuid() } == 0 {
            return;
        }

        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("secret.txt");
        std::fs::write(&file, b"secret").unwrap();
        // Remove all permissions so the invoking user cannot read it.
        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o000)).unwrap();
        let f = file.to_str().unwrap();

        assert_eq!(user_can_access(f, AccessMode::Read), Access::Denied);
        let err = check_delegation(&policy(&[], &[f])).unwrap_err();
        assert!(
            matches!(err, FilesystemPolicyError::Policy(_))
                && err.message().contains("does not have read access"),
            "expected delegation rejection, got: {err:?}"
        );

        // Restore permissions so the tempdir can be cleaned up.
        let _ = std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600));
    }

    #[cfg(unix)]
    #[test]
    fn untraversable_parent_is_rejected_not_skipped() {
        use std::os::unix::fs::PermissionsExt;

        // Root bypasses permission checks, so this case is only meaningful as a
        // non-root user.
        if unsafe { libc::geteuid() } == 0 {
            return;
        }

        // A readable file inside a directory the caller cannot traverse. The file
        // exists, but reaching it requires execute (traversal) on the parent —
        // which we remove. access(2) then reports EACCES, and the check must
        // treat that as "not accessible" (a real delegation failure), NOT skip it
        // as if the path were missing.
        let dir = tempfile::tempdir().unwrap();
        let locked = dir.path().join("locked");
        std::fs::create_dir(&locked).unwrap();
        let file = locked.join("data.txt");
        std::fs::write(&file, b"data").unwrap();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        let f = file.to_str().unwrap();

        assert_eq!(
            user_can_access(f, AccessMode::Read),
            Access::Denied,
            "an untraversable parent (EACCES) must be reported as inaccessible, not skipped"
        );
        assert!(check_delegation(&policy(&[], &[f])).is_err());

        // Restore traversal so the tempdir can recurse in during cleanup.
        let _ = std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755));
    }

    #[cfg(windows)]
    #[test]
    fn unreadable_path_is_rejected() {
        use std::process::Command;

        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("secret.txt");
        std::fs::write(&file, b"secret").unwrap();
        let f = file.to_str().unwrap();

        // Deny read to Everyone (well-known SID S-1-1-0 — locale/domain
        // independent). A deny ACE blocks FILE_READ_DATA even for the owner
        // (whose implicit rights are only READ_CONTROL / WRITE_DAC), so a
        // GENERIC_READ open must fail with ERROR_ACCESS_DENIED. Parent-dir full
        // control still lets the tempdir delete the child on cleanup.
        let status = Command::new("icacls")
            .args([f, "/deny", "*S-1-1-0:(R)"])
            .output()
            .expect("icacls should run");
        assert!(
            status.status.success(),
            "icacls deny failed: {}",
            String::from_utf8_lossy(&status.stderr)
        );

        assert_eq!(
            user_can_access(f, AccessMode::Read),
            Access::Denied,
            "a path with an explicit deny-read ACE must be reported as inaccessible"
        );
        let err = check_delegation(&policy(&[], &[f])).unwrap_err();
        assert!(
            matches!(err, FilesystemPolicyError::Policy(_))
                && err.message().contains("does not have read access"),
            "expected delegation rejection, got: {err:?}"
        );

        // Remove the deny ACE so the tempdir can clean up without surprises.
        let _ = Command::new("icacls")
            .args([f, "/remove:d", "*S-1-1-0"])
            .output();
    }
}