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

//! Host backend-availability probe — the read-only [`available_backends`] API.
//!
//! Reports only the containment backends the current host can run, each with
//! its effective isolation tier when it has a tier ladder. Answers "what can I
//! use here?"; a backend's absence means "not currently usable, for any reason".
//! Separate from [`platform_support`](crate::mxc_engine::platform_support), which answers the
//! narrower "what can `mxc-sdk` itself launch?" question and reports no tier.

use crate::mxc_common::models::ContainmentBackend;
use serde::Serialize;

#[cfg(target_os = "windows")]
use crate::mxc_engine::guarded_capture;

/// Optional feature supported by a containment backend on the current host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub enum BackendCapability {
    /// Windows ProcessContainer denial capture.
    CaptureDenials,
    /// Native `filesystem.deniedPaths` enforcement at the reported tier.
    FilesystemDeniedPaths,
    /// Native `processContainer.filesystem.enumeratePaths` enforcement at the reported tier.
    FilesystemEnumeratePaths,
    /// `network.ingress.hostLoopback = "allow"` at the reported tier.
    IngressHostLoopbackAllow,
    /// Bubblewrap proxy-only egress in a private network namespace.
    ProxyEnforcement,
}

/// One host-available backend, plus its effective isolation tier (if any).
///
/// Serializes to camelCase JSON such as `{"backend":"seatbelt"}` or
/// `{"backend":"processcontainer","tier":"base-container","capabilities":
/// ["captureDenials"]}`; empty optional fields are omitted.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AvailableBackend {
    /// Canonical [`ContainmentBackend::wire_name`] value.
    pub backend: String,
    /// Highest-isolation tier the host supports for this backend (a canonical
    /// `IsolationTier::as_str()` name); `None`, and omitted from JSON, for
    /// backends with no tier ladder.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<String>,
    /// Optional features supported by the reported tier.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<BackendCapability>,
    /// Diagnostics for a capability this host cannot offer.
    ///
    /// Not a guarantee for every absent capability: only checks that produce a
    /// reason populate this. Bubblewrap's `ProxyEnforcement` does, since its
    /// dependency walk names what is missing; Windows omits `CaptureDenials`
    /// without a warning.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
}

impl AvailableBackend {
    fn tierless(backend: &str) -> Self {
        Self {
            backend: backend.to_string(),
            tier: None,
            capabilities: Vec::new(),
            warnings: Vec::new(),
        }
    }
}

/// Probe the host and return only the backends it can currently run.
///
/// An empty `Vec` is a normal result (unsupported platform, or Linux with
/// neither `bwrap` nor `lxc`), not an error. Order is stable but callers should
/// match by `backend` name, not position.
///
/// Not cached — read once at startup, not in a hot loop. The reported `tier` is
/// a ceiling: policy can still force a weaker tier at dispatch.
pub fn available_backends() -> Vec<AvailableBackend> {
    #[cfg(target_os = "macos")]
    {
        macos_backends()
    }
    #[cfg(target_os = "linux")]
    {
        linux_backends()
    }
    #[cfg(target_os = "windows")]
    {
        use crate::process_container_common::base_container_runner::BaseContainerRunner;

        let tier = select_tier(
            BaseContainerRunner::is_base_container_api_present(),
            cfg!(feature = "tier2_bfs"),
        );
        windows_backends(
            tier,
            ProcessContainerCapabilities {
                capture_denials: capture_denials_available(
                    crate::process_container_common::base_container_runner::BaseContainerRunner::is_native_capture_available(),
                    guarded_capture::is_available(),
                ),
                filesystem_denied_paths: crate::process_container_common::base_container_runner::BaseContainerRunner::supports_native_denied_paths(),
                filesystem_enumerate_paths: crate::process_container_common::base_container_runner::BaseContainerRunner::supports_enumerate_paths(),
                ingress_host_loopback_allow: crate::process_container_common::base_container_runner::BaseContainerRunner::supports_ingress_host_loopback_allow(),
            },
        )
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    {
        Vec::new()
    }
}

/// Serialize [`available_backends`] for the `--available-backends` CLI surface.
///
/// Distinct from `wxc-exec --probe`, which emits the AppContainer diagnostics
/// object; this is the backend-availability array.
pub fn to_json_pretty(backends: &[AvailableBackend]) -> Result<String, serde_json::Error> {
    serde_json::to_string_pretty(backends)
}

#[cfg(target_os = "macos")]
fn macos_backends() -> Vec<AvailableBackend> {
    let mut backends = Vec::new();
    if std::path::Path::new("/usr/bin/sandbox-exec").exists() {
        backends.push(AvailableBackend::tierless(
            ContainmentBackend::Seatbelt.wire_name(),
        ));
    }
    backends
}

#[cfg(target_os = "linux")]
fn linux_backends() -> Vec<AvailableBackend> {
    let mut backends = Vec::new();
    if crate::bwrap_common::bwrap_version::probe_bwrap().is_ok() {
        backends.push(bubblewrap_backend(
            crate::bwrap_common::proxy_network::probe_proxy_enforcement(),
        ));
    }
    if crate::lxc_common::availability::is_lxc_available() {
        backends.push(AvailableBackend::tierless(
            ContainmentBackend::Lxc.wire_name(),
        ));
    }
    backends
}

/// Split from [`linux_backends`] so the reporting is testable without a host
/// that has (or lacks) the private-network dependencies.
#[cfg(target_os = "linux")]
fn bubblewrap_backend(proxy_enforcement: Result<(), String>) -> AvailableBackend {
    let mut backend = AvailableBackend::tierless(ContainmentBackend::Bubblewrap.wire_name());
    match proxy_enforcement {
        Ok(()) => backend
            .capabilities
            .push(BackendCapability::ProxyEnforcement),
        Err(reason) => backend.warnings.push(reason),
    }
    backend
}

#[cfg(target_os = "windows")]
#[derive(Debug, Clone, Copy, Default)]
struct ProcessContainerCapabilities {
    capture_denials: bool,
    filesystem_denied_paths: bool,
    filesystem_enumerate_paths: bool,
    ingress_host_loopback_allow: bool,
}

#[cfg(target_os = "windows")]
fn capture_denials_available(native_capture: bool, guarded_capture: bool) -> bool {
    native_capture || guarded_capture
}

#[cfg(target_os = "windows")]
fn windows_backends(
    tier: crate::process_container_common::fallback_detector::IsolationTier,
    support: ProcessContainerCapabilities,
) -> Vec<AvailableBackend> {
    // `processcontainer` is always present and the only backend with a tier
    // ladder, so it carries its effective (highest-reachable) tier.
    let mut capabilities = Vec::new();
    if support.capture_denials {
        capabilities.push(BackendCapability::CaptureDenials);
    }
    if tier == crate::process_container_common::fallback_detector::IsolationTier::BaseContainer {
        if support.filesystem_denied_paths {
            capabilities.push(BackendCapability::FilesystemDeniedPaths);
        }
        if support.filesystem_enumerate_paths {
            capabilities.push(BackendCapability::FilesystemEnumeratePaths);
        }
        if support.ingress_host_loopback_allow {
            capabilities.push(BackendCapability::IngressHostLoopbackAllow);
        }
    }
    let process_container = AvailableBackend {
        backend: ContainmentBackend::ProcessContainer.wire_name().to_string(),
        tier: Some(tier.as_str().to_string()),
        capabilities,
        warnings: Vec::new(),
    };
    let mut backends = vec![process_container];

    if crate::windows_sandbox_lifecycle::availability::is_windows_sandbox_available() {
        backends.push(AvailableBackend::tierless(
            ContainmentBackend::WindowsSandbox.wire_name(),
        ));
    }

    // Report WSLC only when the host can actually run it (WSL2 + the WSLC
    // runtime present), matching `platform_support()` and the runner preflight.
    // `WslcSdk::load()` alone only proves the DLL and its exports resolve.
    #[cfg(feature = "wslc")]
    if crate::wslc_common::is_available() {
        backends.push(AvailableBackend::tierless(
            ContainmentBackend::Wslc.wire_name(),
        ));
    }

    // Available when the `IsoSessionOps` WinRT class is registered on the OS.
    #[cfg(feature = "isolation_session")]
    if crate::isolation_session_common::availability::is_isolation_session_available() {
        backends.push(AvailableBackend::tierless(
            ContainmentBackend::IsolationSession.wire_name(),
        ));
    }

    // WHP is delay-loaded; check before setup boots a VM.
    #[cfg(all(feature = "hyperlight", target_arch = "x86_64"))]
    if crate::hyperlight_common::is_whp_available() {
        backends.push(AvailableBackend::tierless(
            ContainmentBackend::Hyperlight.wire_name(),
        ));
    }

    backends
}

/// Effective process-container tier, strongest reachable rung first:
/// BaseContainer → AppContainerBfs → AppContainerDacl. Split from the host
/// detectors so precedence is testable without a real Windows host or the
/// `tier2_bfs` feature.
///
/// This reports the tier **ceiling** — the strongest tier the host can reach
/// for *some* request. On a `tier2_bfs` build that is `AppContainerBfs`
/// regardless of `bfscfg.exe`: a request with no filesystem policy reaches BFS
/// without it (`fallback_detector::detect`). `bfscfg.exe` only decides whether a
/// *policy-carrying* request stays at BFS or drops to DACL, so it belongs in
/// request-time dispatch, not in the ceiling.
#[cfg(target_os = "windows")]
fn select_tier(
    base_container_usable: bool,
    tier2_bfs_enabled: bool,
) -> crate::process_container_common::fallback_detector::IsolationTier {
    use crate::process_container_common::fallback_detector::IsolationTier;
    if base_container_usable {
        IsolationTier::BaseContainer
    } else if tier2_bfs_enabled {
        IsolationTier::AppContainerBfs
    } else {
        IsolationTier::AppContainerDacl
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::ContainmentBackend;

    const CANONICAL_BACKEND_NAMES: &[(ContainmentBackend, &str)] = &[
        (ContainmentBackend::ProcessContainer, "processcontainer"),
        (ContainmentBackend::Wslc, "wslc"),
        (ContainmentBackend::Lxc, "lxc"),
        (ContainmentBackend::Vm, "vm"),
        (ContainmentBackend::MicroVm, "microvm"),
        (ContainmentBackend::Hyperlight, "hyperlight"),
        (ContainmentBackend::WindowsSandbox, "windows_sandbox"),
        (ContainmentBackend::IsolationSession, "isolation_session"),
        (ContainmentBackend::Seatbelt, "seatbelt"),
        (ContainmentBackend::Bubblewrap, "bubblewrap"),
    ];

    fn all_containment_names() -> Vec<String> {
        CANONICAL_BACKEND_NAMES
            .iter()
            .map(|(_, name)| (*name).to_string())
            .collect()
    }

    #[test]
    fn backend_wire_names_match_the_canonical_table() {
        for (backend, expected) in CANONICAL_BACKEND_NAMES {
            assert_eq!(backend.wire_name(), *expected, "{backend:?}");
        }
    }

    const CANONICAL_TIERS: [&str; 3] = ["base-container", "appcontainer-bfs", "appcontainer-dacl"];

    #[test]
    fn tier_is_omitted_from_json_when_none() {
        let backend = AvailableBackend::tierless("seatbelt");
        let json = serde_json::to_string(&backend).expect("serializes");
        assert_eq!(json, r#"{"backend":"seatbelt"}"#);
    }

    #[test]
    fn tier_is_serialized_in_camel_case_when_present() {
        let backend = AvailableBackend {
            backend: "processcontainer".to_string(),
            tier: Some("appcontainer-dacl".to_string()),
            capabilities: Vec::new(),
            warnings: Vec::new(),
        };
        let json = serde_json::to_string(&backend).expect("serializes");
        assert_eq!(
            json,
            r#"{"backend":"processcontainer","tier":"appcontainer-dacl"}"#
        );
    }

    #[test]
    fn capabilities_are_serialized_in_camel_case_when_present() {
        let backend = AvailableBackend {
            backend: "processcontainer".to_string(),
            tier: Some("base-container".to_string()),
            capabilities: vec![BackendCapability::CaptureDenials],
            warnings: Vec::new(),
        };
        let json = serde_json::to_string(&backend).expect("serializes");
        assert_eq!(
            json,
            r#"{"backend":"processcontainer","tier":"base-container","capabilities":["captureDenials"]}"#
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn bubblewrap_reports_proxy_enforcement_capability_when_probe_succeeds() {
        let backend = bubblewrap_backend(Ok(()));
        assert_eq!(backend.backend, "bubblewrap");
        assert_eq!(
            backend.capabilities,
            vec![BackendCapability::ProxyEnforcement]
        );
        assert!(backend.warnings.is_empty());
        let json = serde_json::to_string(&backend).expect("serializes");
        assert_eq!(
            json,
            r#"{"backend":"bubblewrap","capabilities":["proxyEnforcement"]}"#
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn bubblewrap_reports_reason_instead_of_capability_when_probe_fails() {
        let backend = bubblewrap_backend(Err("slirp4netns not found".to_string()));
        assert!(backend.capabilities.is_empty());
        assert_eq!(backend.warnings, vec!["slirp4netns not found".to_string()]);
        let json = serde_json::to_string(&backend).expect("serializes");
        assert_eq!(
            json,
            r#"{"backend":"bubblewrap","warnings":["slirp4netns not found"]}"#
        );
    }

    #[test]
    fn to_json_pretty_emits_an_array() {
        let rendered =
            to_json_pretty(&[AvailableBackend::tierless("seatbelt")]).expect("serializes");
        assert!(
            rendered.starts_with('['),
            "probe output must be a JSON array"
        );
        assert!(rendered.contains("\"seatbelt\""));
    }

    #[test]
    fn policy_capabilities_are_serialized_in_camel_case() {
        assert_eq!(
            serde_json::to_string(&BackendCapability::FilesystemDeniedPaths).expect("serializes"),
            r#""filesystemDeniedPaths""#
        );
        assert_eq!(
            serde_json::to_string(&BackendCapability::FilesystemEnumeratePaths)
                .expect("serializes"),
            r#""filesystemEnumeratePaths""#
        );
        assert_eq!(
            serde_json::to_string(&BackendCapability::IngressHostLoopbackAllow)
                .expect("serializes"),
            r#""ingressHostLoopbackAllow""#
        );
    }

    #[test]
    fn every_reported_backend_uses_a_canonical_name() {
        let known = all_containment_names();
        for entry in available_backends() {
            assert!(
                known.contains(&entry.backend),
                "reported backend {:?} is not a canonical backend name",
                entry.backend
            );
        }
    }

    #[test]
    fn every_reported_tier_is_a_canonical_tier_string() {
        for entry in available_backends() {
            if let Some(tier) = entry.tier {
                assert!(
                    CANONICAL_TIERS.contains(&tier.as_str()),
                    "reported tier {tier:?} is not a canonical IsolationTier string"
                );
            }
        }
    }

    /// Guards `CANONICAL_TIERS` against drift from `IsolationTier::as_str()`.
    #[cfg(target_os = "windows")]
    #[test]
    fn canonical_tier_strings_match_isolation_tier() {
        use crate::process_container_common::fallback_detector::IsolationTier;
        assert_eq!(IsolationTier::BaseContainer.as_str(), CANONICAL_TIERS[0]);
        assert_eq!(IsolationTier::AppContainerBfs.as_str(), CANONICAL_TIERS[1]);
        assert_eq!(IsolationTier::AppContainerDacl.as_str(), CANONICAL_TIERS[2]);
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_always_reports_processcontainer_with_a_tier() {
        let backends = available_backends();
        let pc = backends
            .iter()
            .find(|b| b.backend == "processcontainer")
            .expect("processcontainer must always be reported on Windows");
        let tier = pc.tier.as_deref().expect("processcontainer carries a tier");
        assert!(
            CANONICAL_TIERS.contains(&tier),
            "unexpected processcontainer tier: {tier:?}"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn capture_denials_is_available_with_either_provider() {
        for (native, guarded, expected) in [
            (false, false, false),
            (true, false, true),
            (false, true, true),
            (true, true, true),
        ] {
            assert_eq!(capture_denials_available(native, guarded), expected);
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_reports_capture_denials_from_combined_provider_result() {
        use crate::process_container_common::fallback_detector::IsolationTier;

        for capture_denials_available in [false, true] {
            let backends = windows_backends(
                IsolationTier::BaseContainer,
                ProcessContainerCapabilities {
                    capture_denials: capture_denials_available,
                    ..Default::default()
                },
            );
            let process_container = backends
                .iter()
                .find(|backend| backend.backend == "processcontainer")
                .expect("processcontainer must always be reported on Windows");
            assert_eq!(
                process_container
                    .capabilities
                    .contains(&BackendCapability::CaptureDenials),
                capture_denials_available
            );
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_reports_policy_capabilities_for_base_container() {
        use crate::process_container_common::fallback_detector::IsolationTier;

        let backends = windows_backends(
            IsolationTier::BaseContainer,
            ProcessContainerCapabilities {
                filesystem_denied_paths: true,
                filesystem_enumerate_paths: true,
                ingress_host_loopback_allow: true,
                ..Default::default()
            },
        );
        let process_container = backends
            .iter()
            .find(|backend| backend.backend == "processcontainer")
            .expect("processcontainer must always be reported on Windows");

        assert_eq!(
            process_container.capabilities,
            vec![
                BackendCapability::FilesystemDeniedPaths,
                BackendCapability::FilesystemEnumeratePaths,
                BackendCapability::IngressHostLoopbackAllow,
            ]
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_omits_base_container_capabilities_from_lower_tiers() {
        use crate::process_container_common::fallback_detector::IsolationTier;

        for tier in [
            IsolationTier::AppContainerBfs,
            IsolationTier::AppContainerDacl,
        ] {
            let backends = windows_backends(
                tier,
                ProcessContainerCapabilities {
                    filesystem_denied_paths: true,
                    filesystem_enumerate_paths: true,
                    ingress_host_loopback_allow: true,
                    ..Default::default()
                },
            );
            let process_container = backends
                .iter()
                .find(|backend| backend.backend == "processcontainer")
                .expect("processcontainer must always be reported on Windows");

            assert!(process_container.capabilities.is_empty());
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn tier_precedence_prefers_the_strongest_reachable_rung() {
        use crate::process_container_common::fallback_detector::IsolationTier;
        // BaseContainer wins whenever usable, regardless of tier2_bfs.
        assert_eq!(select_tier(true, false), IsolationTier::BaseContainer);
        assert_eq!(select_tier(true, true), IsolationTier::BaseContainer);
        // The ceiling is BFS on any tier2_bfs build (a no-policy request reaches
        // it without bfscfg.exe); bfscfg gating lives in request-time dispatch.
        assert_eq!(select_tier(false, true), IsolationTier::AppContainerBfs);
        assert_eq!(select_tier(false, false), IsolationTier::AppContainerDacl);
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn processcontainer_never_appears_off_windows() {
        assert!(available_backends()
            .iter()
            .all(|b| b.backend != "processcontainer"));
    }
}