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

//! Host platform support detection — the Rust port of the SDK's
//! `getPlatformSupport`.
//!
//! Reports whether MXC can run on the current host and which containment
//! backends are available. This lets callers stop depending on the TypeScript
//! SDK for platform discovery.
//!
//! This host probing lives in the engine alongside the backend dispatch in
//! `dispatch.rs`, so both the public SDK and the executor binaries can share a
//! single implementation.

use serde::Serialize;

use crate::mxc_common::models::ContainmentBackend;

/// Whether the host can enforce Bubblewrap proxy-only egress.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ProxyEnforcement {
    Supported,
    Unsupported,
}

/// Bubblewrap host network capability, with the reason when it is unsupported.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BubblewrapNetworkSupport {
    pub proxy_enforcement: ProxyEnforcement,
    pub warnings: Vec<String>,
}

/// Platform support information — the Rust analogue of the SDK
/// `PlatformSupport` type.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformSupport {
    /// Whether MXC is supported on the current host.
    pub is_supported: bool,
    /// Why the platform is unsupported, when `is_supported` is false.
    pub reason: Option<String>,
    /// Containment backends available on this host, using their JSON `containment` values
    /// (e.g. `"seatbelt"`, `"bubblewrap"`, `"processcontainer"`).
    ///
    /// Reports that the backend's tooling is present and usable, not that the
    /// calling process is privileged enough to reach it. `"lxc"` in particular
    /// needs root for a system container, or a configured subuid/subgid
    /// delegation for an unprivileged one; neither is probed here.
    pub available_methods: Vec<String>,
    /// Bubblewrap host network capability. `None` off Linux, and when
    /// `bubblewrap` itself is unavailable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bubblewrap_network: Option<BubblewrapNetworkSupport>,
}

/// The `bwrap --version` gate, injected so the reporting is testable without a
/// host that has (or lacks) a suitable `bwrap`.
#[cfg(target_os = "linux")]
struct BwrapProbe<F>(F);

/// The proxy-enforcement dependency walk, injected for the same reason.
/// A distinct type from [`BwrapProbe`] so the two adjacent arguments read as
/// themselves rather than positionally.
#[cfg(target_os = "linux")]
struct ProxyEnforcementProbe<G>(G);

/// The `lxc-ls` gate, injected for the same reason.
#[cfg(target_os = "linux")]
struct LxcProbe<H>(H);

#[cfg(target_os = "windows")]
struct WindowsPlatformAvailability {
    process_container: bool,
    wslc: bool,
    isolation_session: bool,
    microvm: bool,
}

#[cfg(target_os = "windows")]
fn windows_platform_support_with(availability: WindowsPlatformAvailability) -> PlatformSupport {
    let mut available_methods = Vec::new();
    for (backend, available) in [
        (
            ContainmentBackend::ProcessContainer,
            availability.process_container,
        ),
        (ContainmentBackend::Wslc, availability.wslc),
        (
            ContainmentBackend::IsolationSession,
            availability.isolation_session,
        ),
        (ContainmentBackend::MicroVm, availability.microvm),
    ] {
        if available {
            available_methods.push(backend.wire_name().to_string());
        }
    }
    let is_supported = !available_methods.is_empty();
    PlatformSupport {
        is_supported,
        reason: (!is_supported).then(|| {
            "No supported Windows containment backend is available; ProcessContainer requires PSEC"
                .to_string()
        }),
        available_methods,
        ..Default::default()
    }
}

#[cfg(target_os = "linux")]
fn linux_platform_support_with<F, G, H>(
    lxc: LxcProbe<H>,
    bwrap: BwrapProbe<F>,
    proxy_enforcement: ProxyEnforcementProbe<G>,
) -> PlatformSupport
where
    F: FnOnce() -> Result<
        crate::bwrap_common::bwrap_version::BwrapVersion,
        crate::bwrap_common::bwrap_version::BwrapUnavailable,
    >,
    G: FnOnce() -> Result<(), String>,
    H: FnOnce() -> bool,
{
    let lxc_available = (lxc.0)();
    let bwrap_probe = (bwrap.0)();

    // Listed in the TypeScript SDK's order, so a caller moving off
    // `getPlatformSupport` reads the same answer.
    let mut available_methods = Vec::new();
    if lxc_available {
        available_methods.push(ContainmentBackend::Lxc.wire_name().to_string());
    }
    if bwrap_probe.is_ok() {
        available_methods.push(ContainmentBackend::Bubblewrap.wire_name().to_string());
    }

    match bwrap_probe {
        Ok(_) => PlatformSupport {
            is_supported: true,
            available_methods,
            // Walked only once `bwrap` itself is usable: the network
            // dependencies say nothing on a host that cannot run the backend,
            // and the walk costs several subprocess spawns.
            bubblewrap_network: Some(bubblewrap_network_support((proxy_enforcement.0)())),
            ..Default::default()
        },
        // `reason` says why the platform is unsupported, and LXC alone makes it
        // supported, so the bwrap detail has nowhere to go here.
        Err(_) if lxc_available => PlatformSupport {
            is_supported: true,
            available_methods,
            ..Default::default()
        },
        Err(err) => PlatformSupport {
            reason: Some(format!(
                "Neither LXC nor Bubblewrap is available on this system ({err})"
            )),
            ..Default::default()
        },
    }
}

/// Detect MXC support on the current host.
///
/// Mirrors the SDK's `getPlatformSupport`, restricted to the backends the
/// `mxc-sdk` library can actually run. On Linux both `bubblewrap` and `lxc` are
/// reported when present, and either one alone makes the host supported. On
/// Windows the native capability probe supplies isolation and UI capabilities,
/// `wslc` is reported when its runtime is available, and `microvm` is reported
/// when its development JSON backend is available. The broader host-capability
/// set (backends the host can run but the SDK cannot launch) is reported separately by
/// [`available_backends`](crate::v1::available_backends).
///
/// Every probe here answers "is the tooling usable", not "may this process use
/// it" — see [`PlatformSupport::available_methods`].
pub fn platform_support() -> PlatformSupport {
    #[cfg(target_os = "macos")]
    {
        if crate::seatbelt_common::seatbelt_runner::sandbox_init_available() {
            PlatformSupport {
                is_supported: true,
                available_methods: vec![ContainmentBackend::Seatbelt.wire_name().to_string()],
                ..Default::default()
            }
        } else {
            PlatformSupport {
                reason: Some(
                    "Seatbelt could not be found on this installation of macOS. Your macOS install might be incomplete. (sandbox_init not found)".to_string(),
                ),
                ..Default::default()
            }
        }
    }

    #[cfg(target_os = "linux")]
    {
        // Presence alone is not enough for `bwrap`: it must also be new enough
        // for every flag the argument builder emits (see
        // `crate::bwrap_common::bwrap_version::MIN_BWRAP_VERSION`). LXC has no such
        // floor, so a clean `lxc-ls --version` is its whole gate.
        linux_platform_support_with(
            LxcProbe(crate::lxc_common::availability::is_lxc_available),
            BwrapProbe(crate::bwrap_common::bwrap_version::probe_bwrap),
            ProxyEnforcementProbe(crate::bwrap_common::proxy_network::probe_proxy_enforcement),
        )
    }

    #[cfg(target_os = "windows")]
    {
        // `windows_sandbox` is a host-capability backend the SDK can't launch,
        // so it is reported by `available_backends()` rather than here.
        windows_platform_support_with(WindowsPlatformAvailability {
            process_container: crate::process_container_common::base_container_runner::BaseContainerRunner::is_base_container_api_present(),
            wslc: wslc_available(),
            isolation_session: isolation_session_present(),
            microvm: crate::mxc_engine::probe::microvm_host_available(),
        })
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    {
        PlatformSupport {
            reason: Some("MXC is not supported on this platform".to_string()),
            ..Default::default()
        }
    }
}

/// Split from [`platform_support`] so the reporting is testable without a host
/// that has (or lacks) the private-network dependencies.
#[cfg(target_os = "linux")]
fn bubblewrap_network_support(probe: Result<(), String>) -> BubblewrapNetworkSupport {
    match probe {
        Ok(()) => BubblewrapNetworkSupport {
            proxy_enforcement: ProxyEnforcement::Supported,
            warnings: Vec::new(),
        },
        Err(reason) => BubblewrapNetworkSupport {
            proxy_enforcement: ProxyEnforcement::Unsupported,
            warnings: vec![reason],
        },
    }
}

/// Whether this host can run the WSL Container backend, probing the WSLC
/// runtime the same way the runner's preflight does. Always `false` when the
/// backend isn't compiled in, so the caller needs no `cfg` of its own.
#[cfg(target_os = "windows")]
fn wslc_available() -> bool {
    #[cfg(feature = "wslc")]
    {
        crate::wslc_common::is_available()
    }
    #[cfg(not(feature = "wslc"))]
    {
        false
    }
}

/// Read-only activation probe of the in-process IsolationSession service.
///
/// Reports whether the isolation-session backend's OS-side service is
/// available on this host. Exposed from the engine so `wxc` reaches the
/// isolation-session backend through `mxc_engine` rather than depending on
/// `isolation_session_common` directly.
///
/// Delegates to the backend's own availability probe — the same one
/// [`available_backends`](crate::mxc_engine::available_backends) consults — so the CLI
/// `--probe` surface and the Rust SDK surface can never disagree about this
/// host.
#[cfg(all(target_os = "windows", feature = "isolation_session"))]
pub fn isolation_session_available() -> bool {
    crate::isolation_session_common::availability::is_isolation_session_available()
}

/// Whether this host has the IsolationSession backend. Always `false` when the
/// backend isn't compiled in, so the caller needs no `cfg` of its own.
#[cfg(target_os = "windows")]
fn isolation_session_present() -> bool {
    #[cfg(feature = "isolation_session")]
    {
        isolation_session_available()
    }
    #[cfg(not(feature = "isolation_session"))]
    {
        false
    }
}

#[cfg(test)]
mod tests {
    #[cfg(target_os = "linux")]
    use super::linux_platform_support_with;
    use super::platform_support;
    #[cfg(target_os = "linux")]
    use super::{
        bubblewrap_network_support, BwrapProbe, LxcProbe, ProxyEnforcement, ProxyEnforcementProbe,
    };
    #[cfg(target_os = "linux")]
    use crate::bwrap_common::bwrap_version::{BwrapUnavailable, BwrapVersion, MIN_BWRAP_VERSION};
    use crate::mxc_engine::backend_registry::{self, CANONICAL_BACKEND_NAMES};

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_support_uses_native_psec_availability() {
        use crate::process_container_common::test_env::CaptureCapabilityGuard;

        for available in [false, true] {
            let _guard = CaptureCapabilityGuard::set(available, false);
            let support = platform_support();
            assert_eq!(
                support
                    .available_methods
                    .iter()
                    .any(|method| method == "processcontainer"),
                available
            );
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_support_requires_an_available_backend() {
        use super::{windows_platform_support_with, WindowsPlatformAvailability};

        let cases: &[(bool, bool, bool, bool, &[&str])] = &[
            (false, false, false, false, &[]),
            (true, false, false, false, &["processcontainer"]),
            (false, true, false, false, &["wslc"]),
            (false, false, true, false, &["isolation_session"]),
            (false, false, false, true, &["microvm"]),
            (
                true,
                true,
                true,
                true,
                &["processcontainer", "wslc", "isolation_session", "microvm"],
            ),
        ];
        for &(process_container, wslc, isolation_session, microvm, expected) in cases {
            let support = windows_platform_support_with(WindowsPlatformAvailability {
                process_container,
                wslc,
                isolation_session,
                microvm,
            });
            assert_eq!(support.available_methods, expected);
            assert_eq!(support.is_supported, !expected.is_empty());
            if expected.is_empty() {
                assert!(support
                    .reason
                    .as_deref()
                    .is_some_and(|reason| reason.contains("PSEC")));
            } else {
                assert_eq!(support.reason, None);
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn bubblewrap_network_is_supported_when_probe_succeeds() {
        let support = bubblewrap_network_support(Ok(()));
        assert_eq!(support.proxy_enforcement, ProxyEnforcement::Supported);
        assert!(support.warnings.is_empty());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn bubblewrap_network_is_unsupported_with_reason_when_probe_fails() {
        let support = bubblewrap_network_support(Err("slirp4netns not found".to_string()));
        assert_eq!(support.proxy_enforcement, ProxyEnforcement::Unsupported);
        assert_eq!(support.warnings, vec!["slirp4netns not found".to_string()]);
    }

    /// `bubblewrap_network` is a Linux-only fact. Off Linux the field must be
    /// *absent* rather than `unsupported`, which would claim the host was
    /// evaluated and found wanting. Nothing else pins the non-Linux shape.
    #[cfg(not(target_os = "linux"))]
    #[test]
    fn non_linux_hosts_report_no_bubblewrap_network() {
        let support = platform_support();
        assert!(
            support.bubblewrap_network.is_none(),
            "bubblewrap_network must be absent off Linux, got: {:?}",
            support.bubblewrap_network
        );

        let json = serde_json::to_string(&support).expect("PlatformSupport serializes");
        assert!(
            !json.contains("bubblewrapNetwork"),
            "the field must be omitted from the wire form off Linux, got: {json}"
        );
    }

    fn all_containment_names() -> Vec<String> {
        backend_registry::all_containment_names()
    }

    /// Guards the reported string literals against drift from canonical runtime
    /// backend names.
    #[test]
    fn reported_method_names_match_the_containment_wire_names() {
        for (backend, expected) in CANONICAL_BACKEND_NAMES {
            assert_eq!(backend.wire_name(), *expected, "{backend:?}");
        }
    }

    /// Exercises the live per-target arm, catching a typo'd literal (e.g.
    /// `"wsb"`) that the assertions above would miss.
    #[test]
    fn every_reported_method_is_a_real_wire_name() {
        let known = all_containment_names();
        for method in platform_support().available_methods {
            assert!(
                known.contains(&method),
                "reported method {method:?} is not a Containment wire name"
            );
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_support_reports_bubblewrap_when_probe_succeeds() {
        let support = linux_platform_support_with(
            LxcProbe(|| false),
            BwrapProbe(|| Ok(MIN_BWRAP_VERSION)),
            ProxyEnforcementProbe(|| Ok(())),
        );
        assert!(support.is_supported);
        assert_eq!(support.reason, None);
        assert_eq!(support.available_methods, ["bubblewrap"]);
        assert_eq!(
            support
                .bubblewrap_network
                .expect("network support is reported alongside a usable bwrap")
                .proxy_enforcement,
            ProxyEnforcement::Supported
        );
    }

    /// Both Linux backends are SDK-launchable, so a host carrying both must
    /// advertise both.
    #[cfg(target_os = "linux")]
    #[test]
    fn linux_support_reports_lxc_alongside_bubblewrap() {
        let support = linux_platform_support_with(
            LxcProbe(|| true),
            BwrapProbe(|| Ok(MIN_BWRAP_VERSION)),
            ProxyEnforcementProbe(|| Ok(())),
        );
        assert!(support.is_supported);
        assert_eq!(support.available_methods, ["lxc", "bubblewrap"]);
    }

    /// An LXC-only host can launch a sandbox, so reporting it unsupported would
    /// send every discovery caller away from a backend that works.
    #[cfg(target_os = "linux")]
    #[test]
    fn linux_support_stands_on_lxc_alone() {
        let support = linux_platform_support_with(
            LxcProbe(|| true),
            BwrapProbe(|| {
                Err(BwrapUnavailable::TooOld {
                    found: BwrapVersion::new(0, 4, 1),
                    path: "/usr/bin/bwrap".into(),
                })
            }),
            ProxyEnforcementProbe(|| {
                panic!("the network walk must not run without a usable bwrap")
            }),
        );
        assert!(support.is_supported);
        assert_eq!(support.reason, None);
        assert_eq!(support.available_methods, ["lxc"]);
        assert!(support.bubblewrap_network.is_none());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_support_preserves_probe_failure_reason() {
        let failure = BwrapUnavailable::TooOld {
            found: BwrapVersion::new(0, 4, 1),
            path: "/usr/bin/bwrap".into(),
        };
        let expected = failure.to_string();
        let support = linux_platform_support_with(
            LxcProbe(|| false),
            BwrapProbe(|| Err(failure)),
            ProxyEnforcementProbe(|| {
                panic!("the network walk must not run without a usable bwrap")
            }),
        );
        assert!(!support.is_supported);
        let reason = support.reason.expect("an unsupported host explains itself");
        assert!(reason.contains(&expected), "got: {reason}");
        assert!(reason.contains("LXC"), "got: {reason}");
        assert!(support.available_methods.is_empty());
        assert!(support.bubblewrap_network.is_none());
    }

    /// A host with `bwrap` but without the private-network tooling is still a
    /// supported platform: only the proxy-enforcement capability is absent.
    #[cfg(target_os = "linux")]
    #[test]
    fn linux_support_reports_bubblewrap_without_proxy_enforcement() {
        let support = linux_platform_support_with(
            LxcProbe(|| false),
            BwrapProbe(|| Ok(MIN_BWRAP_VERSION)),
            ProxyEnforcementProbe(|| Err("slirp4netns not found".to_string())),
        );
        assert!(support.is_supported);
        assert_eq!(support.available_methods, ["bubblewrap"]);
        let network = support
            .bubblewrap_network
            .expect("network support is reported alongside a usable bwrap");
        assert_eq!(network.proxy_enforcement, ProxyEnforcement::Unsupported);
        assert_eq!(network.warnings, ["slirp4netns not found".to_string()]);
    }
}