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
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Streaming backend dispatch for the `mxc-sdk` library.
//!
//! Spawns the right [`SandboxProcess`] for the request's containment backend.
//! It lives here — rather than in `mxc_common` — because constructing a
//! backend runner requires depending on the `backends/*` crates, and
//! `mxc_common` must not (it is the cross-platform foundation those backends
//! build on).
//!
//! Only the backends with a streaming path are handled here: ProcessContainer
//! (native PSEC, constructed through `BaseContainerRunner::for_request` as on
//! the run-to-completion path), Bubblewrap
//! and LXC (Linux), Seatbelt (macOS), WSLC, and IsolationSession (Windows,
//! behind the `wslc` and `isolation_session` features). Every other backend —
//! including the remaining experimental ones (Windows Sandbox, MicroVM,
//! Hyperlight) — returns [`MxcError::unsupported_containment`]; callers that
//! need those must drive the standalone executor binaries (whose
//! run-to-completion path will, in a later increment, also route through this
//! engine).

use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainmentBackend, ExecutionRequest, ScriptResponse};
use crate::mxc_common::mxc_error::MxcError;
use crate::mxc_common::sandbox_process::{PtySize, SandboxProcess, StdioMode};

/// `Err` when the host OS has no MXC sandbox backend. Checked before backend
/// selection so an unsupported platform reports a clear message rather than a
/// backend-specific one (the default/abstract intent resolves to
/// ProcessContainer on non-Linux/macOS hosts).
fn ensure_host_supported() -> Result<(), MxcError> {
    #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
    {
        Ok(())
    }
    #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
    {
        Err(MxcError::unsupported_containment(
            "the mxc engine has no sandbox backend for this host OS \
             (supported: Windows, Linux, macOS)",
        ))
    }
}

// ---------------------------------------------------------------------------
// Streaming (handle-based) spawn
// ---------------------------------------------------------------------------

/// Spawn a [`SandboxProcess`] handle for `request` on the current host.
///
/// Spawns the sandboxed process with piped stdio and returns a handle the
/// caller can write to, read from, wait on, and kill. Backends without a
/// streaming implementation return [`MxcError::unsupported_containment`].
///
/// `wslc_stdin` gives a WSLc process a writable stdin rather than end-of-file;
/// the other supported backends keep their normal streaming behavior.
pub fn spawn_runner(
    request: &ExecutionRequest,
    logger: &mut Logger,
    wslc_stdin: bool,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    crate::mxc_engine::experimental::require_experimental_optin(
        &request.containment,
        request.experimental_enabled,
    )?;
    ensure_host_supported()?;
    // `dry_run` means "validate, don't execute" — there is no process to
    // stream, so reject it rather than silently ignoring it.
    if request.dry_run {
        return Err(MxcError::malformed_request(
            "dry_run is not supported for streaming spawns",
        ));
    }

    // Anchor the run to its policy identity before any backend is engaged, so
    // the streaming surface produces the same `mxc.PolicyHash` record as the
    // run-to-completion one.
    crate::mxc_engine::run::log_policy_hash(request, logger);
    match &request.containment {
        ContainmentBackend::Seatbelt => spawn_seatbelt(request, logger),
        ContainmentBackend::Bubblewrap => spawn_bubblewrap(request, logger),
        ContainmentBackend::Lxc => spawn_lxc(request, logger),
        ContainmentBackend::ProcessContainer => spawn_process_container(request, logger),
        ContainmentBackend::Wslc => spawn_wslc(request, logger, wslc_stdin),
        ContainmentBackend::IsolationSession => spawn_isolation_session(request, logger),
        ContainmentBackend::MicroVm => spawn_microvm(request, logger),
        ContainmentBackend::W365Agents => {
            use crate::mxc_common::sandbox_process::SandboxBackend;
            crate::backend_modules::W365AgentsRunner
                .spawn(request, logger, StdioMode::Pipes)
                .map_err(map_spawn_error)
        }
        other => Err(MxcError::unsupported_containment(format!(
            "the mxc engine does not yet support streaming for the '{}' backend",
            other.wire_name()
        ))),
    }
}

#[cfg(all(target_os = "windows", target_arch = "x86_64", feature = "microvm"))]
fn spawn_microvm(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    crate::nvx_runner::spawn_streaming(request, logger, false)
}

#[cfg(not(all(target_os = "windows", target_arch = "x86_64", feature = "microvm")))]
fn spawn_microvm(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "the mxc engine does not yet support streaming for the 'microvm' backend",
    ))
}

/// Spawn a caller-driven pseudo-terminal for `request`.
pub fn spawn_pty_runner(
    request: &ExecutionRequest,
    logger: &mut Logger,
    size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    size.validate()?;
    ensure_host_supported()?;
    if request.dry_run {
        return Err(MxcError::malformed_request(
            "dry_run is not supported for PTY spawns",
        ));
    }
    crate::mxc_engine::run::log_policy_hash(request, logger);
    match &request.containment {
        ContainmentBackend::IsolationSession => spawn_isolation_session_pty(request, logger, size),
        ContainmentBackend::Bubblewrap => {
            spawn_bubblewrap_with_stdio(request, logger, StdioMode::Pty(size))
        }
        ContainmentBackend::Seatbelt => {
            spawn_seatbelt_with_stdio(request, logger, StdioMode::Pty(size))
        }
        ContainmentBackend::Lxc => spawn_lxc_with_stdio(request, logger, StdioMode::Pty(size)),
        other => Err(MxcError::unsupported_containment(format!(
            "the mxc engine does not yet support PTY spawning for the '{}' backend",
            other.wire_name()
        ))),
    }
}

pub fn spawn_inherited_stdio_runner(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    ensure_host_supported()?;
    if request.dry_run {
        return Err(MxcError::malformed_request(
            "dry_run is not supported for inherited-stdio spawns",
        ));
    }
    crate::mxc_engine::run::log_policy_hash(request, logger);
    match &request.containment {
        ContainmentBackend::ProcessContainer => {
            spawn_process_container_with_stdio(request, logger, StdioMode::Inherit)
        }
        ContainmentBackend::Bubblewrap => {
            spawn_bubblewrap_with_stdio(request, logger, StdioMode::Inherit)
        }
        ContainmentBackend::Seatbelt => {
            spawn_seatbelt_with_stdio(request, logger, StdioMode::Inherit)
        }
        other => Err(MxcError::unsupported_containment(format!(
            "the mxc engine does not support inherited-stdio spawning for the '{}' backend",
            other.wire_name()
        ))),
    }
}

/// Map a backend's `spawn` failure `ScriptResponse` to an
/// [`MxcError`], preserving the failure phase (so callers can fall back to a
/// lower tier, or tell a rejected request from a broken one) and folding any
/// `extended_error` detail into the message — rather than flattening
/// everything to a generic `BackendError`.
fn map_spawn_error(resp: ScriptResponse) -> MxcError {
    use crate::mxc_common::models::FailurePhase;

    let mut message = resp.error_message;
    if !resp.extended_error.is_empty() {
        if message.is_empty() {
            message = resp.extended_error;
        } else {
            message = format!("{message} ({})", resp.extended_error);
        }
    }
    match resp.failure_phase {
        FailurePhase::BackendUnavailable => MxcError::backend_unavailable(message),
        // The request itself cannot be honored, so a blind retry will not help.
        FailurePhase::Rejected => MxcError::policy_validation(message),
        _ => MxcError::backend_error(message),
    }
}

#[cfg(target_os = "linux")]
fn spawn_bubblewrap(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    spawn_bubblewrap_with_stdio(request, logger, StdioMode::Pipes)
}

#[cfg(target_os = "linux")]
fn spawn_bubblewrap_with_stdio(
    request: &ExecutionRequest,
    logger: &mut Logger,
    stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    use crate::mxc_common::sandbox_process::SandboxBackend;
    let mut runner = crate::bwrap_common::bwrap_runner::BubblewrapScriptRunner::new();
    runner
        .spawn(request, logger, stdio)
        .map_err(map_spawn_error)
}

#[cfg(not(target_os = "linux"))]
fn spawn_bubblewrap(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "Bubblewrap is only available on Linux",
    ))
}

#[cfg(not(target_os = "linux"))]
fn spawn_bubblewrap_with_stdio(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
    _stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "Bubblewrap is only available on Linux",
    ))
}

/// Serves piped stdio and caller-owned PTYs through the in-process LXC handle.
#[cfg(target_os = "linux")]
fn spawn_lxc(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    spawn_lxc_with_stdio(request, logger, StdioMode::Pipes)
}

#[cfg(target_os = "linux")]
fn spawn_lxc_with_stdio(
    request: &ExecutionRequest,
    logger: &mut Logger,
    stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    use crate::mxc_common::sandbox_process::SandboxBackend;
    let mut runner = crate::lxc_common::lxc_runner::LxcScriptRunner::new(
        &request.lxc_config,
        &request.container_id,
        &request.lifecycle,
    );
    runner
        .spawn(request, logger, stdio)
        .map_err(map_spawn_error)
}

#[cfg(not(target_os = "linux"))]
fn spawn_lxc(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "LXC is only available on Linux",
    ))
}

#[cfg(not(target_os = "linux"))]
fn spawn_lxc_with_stdio(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
    _stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "LXC is only available on Linux",
    ))
}

#[cfg(target_os = "macos")]
fn spawn_seatbelt(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    spawn_seatbelt_with_stdio(request, logger, StdioMode::Pipes)
}

#[cfg(target_os = "macos")]
fn spawn_seatbelt_with_stdio(
    request: &ExecutionRequest,
    logger: &mut Logger,
    stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    use crate::mxc_common::sandbox_process::SandboxBackend;
    let mut runner = crate::seatbelt_common::seatbelt_runner::SeatbeltScriptRunner::new();
    runner
        .spawn(request, logger, stdio)
        .map_err(map_spawn_error)
}

#[cfg(not(target_os = "macos"))]
fn spawn_seatbelt(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "Seatbelt is only available on macOS",
    ))
}

#[cfg(not(target_os = "macos"))]
fn spawn_seatbelt_with_stdio(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
    _stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "Seatbelt is only available on macOS",
    ))
}

fn spawn_process_container(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    spawn_process_container_with_stdio(request, logger, StdioMode::Pipes)
}

#[cfg(target_os = "windows")]
fn spawn_process_container_with_stdio(
    request: &ExecutionRequest,
    logger: &mut Logger,
    stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    use crate::mxc_common::sandbox_process::SandboxBackend;
    use crate::process_container_common::base_container_runner::BaseContainerRunner;

    let mut backend = BaseContainerRunner::for_request(request)?;
    backend
        .spawn(request, logger, stdio)
        .map_err(map_spawn_error)
}

#[cfg(not(target_os = "windows"))]
fn spawn_process_container_with_stdio(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
    _stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    Err(MxcError::unsupported_containment(
        "ProcessContainer (PSEC) is only available on Windows",
    ))
}

/// Spawn the WSL Container backend.
#[cfg(all(target_os = "windows", feature = "wslc"))]
fn spawn_wslc(
    request: &ExecutionRequest,
    logger: &mut Logger,
    stdin: bool,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    use crate::mxc_common::sandbox_process::{SandboxBackend, StdioMode};

    let config = request.wslc.clone().unwrap_or_default();
    let mut runner = if stdin {
        crate::wslc_common::WSLContainerRunner::with_piped_stdin(&config)
    } else {
        crate::wslc_common::WSLContainerRunner::new(&config)
    };
    runner
        .spawn(request, logger, StdioMode::Pipes)
        .map_err(map_spawn_error)
}

#[cfg(not(all(target_os = "windows", feature = "wslc")))]
fn spawn_wslc(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
    _stdin: bool,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    #[cfg(target_os = "windows")]
    {
        // SDK v2: backend_unavailable. See docs/development/plans/sdk-v2-error-codes.md.
        Err(MxcError::unsupported_containment(
            "WSLC backend not compiled. Rebuild with --features wslc.",
        ))
    }
    #[cfg(not(target_os = "windows"))]
    {
        Err(MxcError::unsupported_containment(
            "WSLC (WSL Container) is only available on Windows",
        ))
    }
}

/// Spawn the IsolationSession backend.
///
/// Serves piped stdio. Goes through the backend's own launch rather than the
/// `SandboxBackend` trait so a lifecycle failure keeps the API call and status
/// the trait's `ScriptResponse` cannot carry; a refusal has no such detail, so
/// it maps the same way every other backend's does.
#[cfg(all(target_os = "windows", feature = "isolation_session"))]
fn spawn_isolation_session(
    request: &ExecutionRequest,
    logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    use crate::isolation_session_common::OneShotSpawnFailure;

    crate::isolation_session_common::spawn_one_shot(request, logger).map_err(|e| match e {
        OneShotSpawnFailure::Refused(resp) => map_spawn_error(resp),
        OneShotSpawnFailure::Launch(err) => err,
    })
}

#[cfg(all(target_os = "windows", feature = "isolation_session"))]
fn spawn_isolation_session_pty(
    request: &ExecutionRequest,
    logger: &mut Logger,
    size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    use crate::isolation_session_common::OneShotSpawnFailure;

    crate::isolation_session_common::spawn_one_shot_pty(request, logger, size).map_err(
        |e| match e {
            OneShotSpawnFailure::Refused(resp) => map_spawn_error(resp),
            OneShotSpawnFailure::Launch(err) => err,
        },
    )
}

#[cfg(not(all(target_os = "windows", feature = "isolation_session")))]
fn spawn_isolation_session(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    #[cfg(target_os = "windows")]
    {
        // SDK v2: backend_unavailable. See docs/development/plans/sdk-v2-error-codes.md.
        Err(MxcError::unsupported_containment(
            "IsolationSession backend not compiled. Rebuild with --features isolation_session.",
        ))
    }
    #[cfg(not(target_os = "windows"))]
    {
        Err(MxcError::unsupported_containment(
            "IsolationSession is only available on Windows",
        ))
    }
}

#[cfg(not(all(target_os = "windows", feature = "isolation_session")))]
fn spawn_isolation_session_pty(
    _request: &ExecutionRequest,
    _logger: &mut Logger,
    _size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
    #[cfg(target_os = "windows")]
    {
        // SDK v2: backend_unavailable. See docs/development/plans/sdk-v2-error-codes.md.
        Err(MxcError::unsupported_containment(
            "IsolationSession backend not compiled. Rebuild with --features isolation_session.",
        ))
    }
    #[cfg(not(target_os = "windows"))]
    {
        Err(MxcError::unsupported_containment(
            "IsolationSession is only available on Windows",
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ensure_host_supported, map_spawn_error, spawn_inherited_stdio_runner, spawn_pty_runner,
        spawn_runner,
    };
    use crate::mxc_common::logger::{Logger, Mode};
    use crate::mxc_common::models::{ContainmentBackend, ExecutionRequest};
    use crate::mxc_common::mxc_error::MxcErrorCode;
    use crate::mxc_common::sandbox_process::PtySize;

    fn minimal_request() -> ExecutionRequest {
        ExecutionRequest {
            script_code: "echo hello".to_string(),
            ..ExecutionRequest::default()
        }
    }

    fn spawn_failure(
        phase: crate::mxc_common::models::FailurePhase,
    ) -> crate::mxc_common::models::ScriptResponse {
        crate::mxc_common::models::ScriptResponse {
            error_message: "wslc rejected the request".to_string(),
            failure_phase: phase,
            ..Default::default()
        }
    }

    #[test]
    fn rejected_phase_maps_to_policy_validation() {
        use crate::mxc_common::models::FailurePhase;

        let err = map_spawn_error(spawn_failure(FailurePhase::Rejected));
        assert_eq!(err.code, MxcErrorCode::PolicyValidation);
        assert_eq!(err.message, "wslc rejected the request");
    }

    #[test]
    fn unavailable_and_unset_phases_keep_their_codes() {
        use crate::mxc_common::models::FailurePhase;

        // `None` is the default, so an unclassified failure must stay a generic
        // backend error rather than being mistaken for a rejection.
        assert_eq!(
            map_spawn_error(spawn_failure(FailurePhase::BackendUnavailable)).code,
            MxcErrorCode::BackendUnavailable
        );
        assert_eq!(
            map_spawn_error(spawn_failure(FailurePhase::None)).code,
            MxcErrorCode::BackendError
        );
        assert_eq!(
            map_spawn_error(spawn_failure(FailurePhase::LaunchFailed)).code,
            MxcErrorCode::BackendError
        );
    }

    #[test]
    fn streaming_rejects_dry_run() {
        // `dry_run` ("validate, don't execute") has no process to stream, so
        // the streaming spawn rejects it.
        let mut request = minimal_request();
        request.dry_run = true;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("dry_run must be rejected"),
            Err(e) => e,
        };
        assert_eq!(err.code, MxcErrorCode::MalformedRequest);
    }

    #[test]
    fn streaming_rejects_unsupported_containment() {
        // `Vm` has no streaming arm on any host, so it stands in for every
        // backend the catch-all must refuse. Drive dispatch with the internal
        // model now that SDK authoring lives outside the engine.
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Vm;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("Vm must be rejected"),
            Err(e) => e,
        };
        assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
        assert!(err.message.contains("vm"), "got: {}", err.message);
    }

    #[test]
    fn pty_spawn_rejects_unsupported_containment_before_launch() {
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Vm;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_pty_runner(
            &request,
            &mut logger,
            PtySize {
                rows: 24,
                cols: 80,
                pixel_width: 0,
                pixel_height: 0,
            },
        ) {
            Ok(_) => panic!("VM PTY spawn must be rejected"),
            Err(error) => error,
        };
        assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
        assert!(err.message.contains("vm"), "got: {}", err.message);
    }

    #[test]
    fn inherited_stdio_spawn_rejects_backends_without_inherited_stdio() {
        for containment in [
            ContainmentBackend::Lxc,
            ContainmentBackend::Wslc,
            ContainmentBackend::IsolationSession,
            ContainmentBackend::Vm,
        ] {
            let mut request = minimal_request();
            request.containment = containment.clone();
            let mut logger = Logger::new(Mode::Buffer);
            let err = match spawn_inherited_stdio_runner(&request, &mut logger) {
                Ok(_) => panic!("{} must be rejected", containment.wire_name()),
                Err(error) => error,
            };
            assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
            assert!(
                err.message.contains(containment.wire_name()),
                "got: {}",
                err.message
            );
        }
    }

    #[test]
    fn inherited_stdio_spawn_rejects_dry_run() {
        let mut request = minimal_request();
        request.dry_run = true;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_inherited_stdio_runner(&request, &mut logger) {
            Ok(_) => panic!("dry_run must be rejected"),
            Err(error) => error,
        };
        assert_eq!(err.code, MxcErrorCode::MalformedRequest);
    }

    #[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
    #[test]
    fn host_support_ok_on_supported_platforms() {
        // The three platforms the library supports must all pass the host gate
        // `spawn_runner` checks before backend selection; this guards against a
        // regression in the `cfg` list dropping one of them.
        assert!(ensure_host_supported().is_ok());
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn streaming_rejects_gui_access() {
        // A windowed (guiAccess) app needs inherited stdio, so it can't stream
        // over pipes — the backend must reject it rather than drop the GUI cap.
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Seatbelt;
        request.seatbelt = Some(crate::mxc_common::models::SeatbeltConfig {
            gui_access: true,
            ..Default::default()
        });
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("guiAccess must be rejected"),
            Err(e) => e,
        };
        assert!(err.message.contains("guiAccess"), "got: {}", err.message);
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn streaming_rejects_wslc_off_windows() {
        // WSLC is a Windows-host backend; selecting it anywhere else must be a
        // clear `UnsupportedContainment` rather than a confusing spawn failure.
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Wslc;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("WSLC must be rejected off Windows"),
            Err(e) => e,
        };
        assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
        assert!(err.message.contains("Windows"), "got: {}", err.message);
    }

    #[cfg(all(target_os = "windows", not(feature = "wslc")))]
    #[test]
    fn streaming_matches_run_to_completion_for_a_backend_this_build_omits() {
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Wslc;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("a backend this build omits must not spawn"),
            Err(e) => e,
        };
        assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn streaming_rejects_lxc_off_linux() {
        // LXC is a Linux-host backend; selecting it anywhere else must be a
        // clear `UnsupportedContainment` rather than a confusing spawn failure.
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Lxc;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("LXC must be rejected off Linux"),
            Err(e) => e,
        };
        assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
        assert!(err.message.contains("Linux"), "got: {}", err.message);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn streaming_lxc_reaches_the_backend_on_linux() {
        // Locks the dispatch arm itself on the one host where it exists. The
        // empty distribution is a backstop: whichever of LXC's own refusals
        // fires first, all of them are reached only through this arm, and all
        // of them come before a container name is claimed or a container
        // created — so this needs neither LXC nor root.
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Lxc;
        request.lxc_config.distribution = String::new();
        request.lxc_config.release = String::new();
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("an LXC request the backend refuses must not spawn"),
            Err(e) => e,
        };
        assert_ne!(err.code, MxcErrorCode::UnsupportedContainment);
        // Only `lxc_common` produces a message opening with `LXC`, so this is
        // the request having reached the backend rather than the catch-all.
        assert!(err.message.starts_with("LXC"), "got: {}", err.message);
    }

    #[cfg(all(target_os = "windows", feature = "wslc"))]
    #[test]
    fn streaming_wslc_without_optin_reaches_policy_validation() {
        let mut request = minimal_request();
        request.containment = ContainmentBackend::Wslc;
        request.policy.ui_specified = true;
        let mut logger = Logger::new(Mode::Buffer);
        let err = match spawn_runner(&request, &mut logger, false) {
            Ok(_) => panic!("WSLC must reject an unsupported UI policy"),
            Err(e) => e,
        };
        assert_eq!(err.code, MxcErrorCode::PolicyValidation);
        assert!(err.message.contains("ui section"), "got: {}", err.message);
        assert!(
            !err.message.contains("experimental"),
            "got: {}",
            err.message
        );
    }
}