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

//! Read-only fallback-detector probe.
//!
//! This module wraps [`crate::process_container_common::fallback_detector`] in a serde-friendly
//! surface so the SDK can invoke `wxc-exec --probe` and learn which
//! isolation tier would be selected on the current machine without
//! actually spawning a sandbox.
//!
//! The probe must have no side effects: it does not write logs, modify
//! the filesystem, or spawn child processes.

use serde::Serialize;

use crate::mxc_common::models::ExecutionRequest;
use crate::mxc_common::ui_policy::EffectiveUiRestrictions;
use crate::process_container_common::fallback_detector::{self, FallbackError};

/// JSON output emitted by `wxc-exec --probe`.
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProbeOutput {
    /// Selected tier (omitted when the detector returned an error).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<&'static str>,
    /// True when the selected tier needs DACL deny-augmentation on host
    /// paths. Omitted when the detector returned an error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub needs_dacl_augmentation: Option<bool>,
    /// Operator-visible degradation warnings — one per tier fall-through.
    pub warnings: Vec<String>,
    /// Raw machine probes, independent of the policy argument.
    pub probes: ProbeFacts,
    /// Detector error message (only set when detection failed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Raw machine facts gathered prior to running tier selection.
#[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProbeFacts {
    /// The process security environment API set is resolvable.
    pub base_container_api_present: bool,
    /// Whether the preferred native PSEC plus Learning Mode capture path is usable.
    ///
    /// A false value does not mean `captureDenials` is unsupported: the executor
    /// can use guarded WPR on a compatible fallback tier. A true value reports
    /// host capability, not request compatibility; a request can still require
    /// guarded WPR when its policy cannot be represented by PSEC.
    pub native_capture_available: bool,
    /// Whether the guarded WPR capture fallback is available.
    pub guarded_capture_available: bool,
    /// `bfscfg.exe` is on disk in `%SystemRoot%\System32`.
    ///
    /// Always `false` when [`Self::bfs_compiled_in`] is `false`, because
    /// `find_bfscfg_exe` returns `Ok(None)` unconditionally with the
    /// `tier2_bfs` feature off — i.e. this field reports what the
    /// detector itself would see, not what is on disk.
    pub bfscfg_present: bool,
    /// Whether this binary was compiled with the `tier2_bfs` Cargo
    /// feature. When `false`, Tier 2 (AppContainer + BFS) is
    /// unreachable: the detector falls through to Tier 3 on any host
    /// that would otherwise select T2, and the `bfscfg.exe` spawn site
    /// is itself gated. Harnesses on hang-prone hosts (e.g. Windows
    /// 11 25H2 where `bfscfg.exe` locks `bfs.sys`) should refuse to
    /// run a binary that reports `true` here.
    pub bfs_compiled_in: bool,
    /// Whether PSEC can enforce `filesystem.deniedPaths` at Tier 1.
    pub base_container_supports_deny_paths: bool,
    /// Whether PSEC 1.1 can enforce `processContainer.filesystem.enumeratePaths` at Tier 1.
    pub base_container_supports_enumerate_paths: bool,
    /// Whether BaseContainer can honor
    /// `network.ingress.hostLoopback = "allow"`.
    pub base_container_supports_ingress_host_loopback_allow: bool,
    /// Whether the in-proc IsolationSession service can be activated on this
    /// host. Always `false` here — `process_container_common` has no dependency on
    /// the isolation-session backend; `wxc-exec --probe` overrides it when
    /// that backend is compiled in.
    pub isolation_session_available: bool,
    /// Whether Hyperlight (WHP micro-VM) is available on this host. Always
    /// `false` here — overridden by `wxc-exec --probe` when the hyperlight
    /// feature is compiled in and WHP is loadable.
    pub hyperlight_available: bool,
    /// Platform-agnostic UI restrictions this host can enforce.
    pub ui_capabilities: UiCapabilitySupport,
}

/// Host support for enforcing sandbox UI restrictions.
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UiCapabilitySupport {
    /// Whether the host can block reads from the clipboard.
    pub can_block_clipboard_read: bool,
    /// Whether the host can block writes to the clipboard.
    pub can_block_clipboard_write: bool,
    /// Whether the host can block synthetic keyboard/mouse input.
    pub can_block_input_injection: bool,
    /// Whether the host can block input method / IME changes.
    pub can_block_input_method_changes: bool,
    /// Whether the host can block access to external UI object handles.
    pub can_block_external_ui_objects: bool,
    /// Whether the host can block access to global UI namespaces.
    pub can_block_global_ui_namespace: bool,
    /// Whether the host can block desktop switching.
    pub can_block_desktop_switching: bool,
    /// Whether the host can block logoff or shutdown requests.
    pub can_block_logoff_or_shutdown: bool,
    /// Whether the host can block system parameter changes.
    pub can_block_system_parameter_changes: bool,
    /// Whether the host can block display settings changes.
    pub can_block_display_settings_changes: bool,
}

impl From<EffectiveUiRestrictions> for UiCapabilitySupport {
    fn from(value: EffectiveUiRestrictions) -> Self {
        Self {
            can_block_clipboard_read: value.block_clipboard_read,
            can_block_clipboard_write: value.block_clipboard_write,
            can_block_input_injection: value.block_input_injection,
            can_block_input_method_changes: value.block_input_method_changes,
            can_block_external_ui_objects: value.block_external_ui_objects,
            can_block_global_ui_namespace: value.block_global_ui_namespace,
            can_block_desktop_switching: value.block_desktop_switching,
            can_block_logoff_or_shutdown: value.block_logoff_or_shutdown,
            can_block_system_parameter_changes: value.block_system_parameter_changes,
            can_block_display_settings_changes: value.block_display_settings_changes,
        }
    }
}

/// Run the probe with the availability of the guarded WPR capture fallback.
///
/// The concrete guarded-capture implementation lives above this crate in
/// `mxc_engine`, which supplies this capability to the executor probe.
pub fn run_probe(request: &ExecutionRequest, guarded_capture_available: bool) -> ProbeOutput {
    use crate::process_container_common::base_container_runner::BaseContainerRunner;

    let probes = ProbeFacts {
        base_container_api_present: BaseContainerRunner::is_base_container_api_present(),
        native_capture_available: BaseContainerRunner::is_native_capture_available(),
        guarded_capture_available,
        bfscfg_present: fallback_detector::find_bfscfg_exe()
            .ok()
            .flatten()
            .is_some(),
        bfs_compiled_in: cfg!(feature = "tier2_bfs"),
        base_container_supports_deny_paths: BaseContainerRunner::supports_native_denied_paths(),
        base_container_supports_enumerate_paths: BaseContainerRunner::supports_enumerate_paths(),
        base_container_supports_ingress_host_loopback_allow:
            BaseContainerRunner::supports_ingress_host_loopback_allow(),
        isolation_session_available: false,
        hyperlight_available: false,
        ui_capabilities: crate::process_container_common::job_object::supported_ui_restrictions()
            .into(),
    };

    run_probe_with_tier_decision(
        request,
        probes,
        fallback_detector::choose_backend_tier(request),
    )
}

fn run_probe_with_tier_decision(
    request: &ExecutionRequest,
    probes: ProbeFacts,
    tier_decision: Result<fallback_detector::TierDecision, FallbackError>,
) -> ProbeOutput {
    match tier_decision {
        Ok(decision)
            if request.policy.capture_denials.is_some()
                && decision.tier != fallback_detector::IsolationTier::BaseContainer
                && !probes.guarded_capture_available =>
        {
            ProbeOutput {
                tier: None,
                needs_dacl_augmentation: None,
                warnings: decision.warnings,
                probes,
                error: Some("guarded WPR captureDenials fallback is unavailable".to_string()),
            }
        }
        Ok(decision) => ProbeOutput {
            tier: Some(decision.tier.as_str()),
            needs_dacl_augmentation: Some(decision.needs_dacl_augmentation),
            warnings: decision.warnings,
            probes,
            error: None,
        },
        Err(e) => ProbeOutput {
            tier: None,
            needs_dacl_augmentation: None,
            warnings: vec![],
            probes,
            error: Some(format_fallback_error(&e)),
        },
    }
}

fn format_fallback_error(e: &FallbackError) -> String {
    match e {
        FallbackError::DaclFallbackDisabled => {
            "DACL fallback required but fallback.allowDaclMutation is false".to_string()
        }
        FallbackError::WriteDacUnavailable { path, reason } => {
            format!("WRITE_DAC unavailable on path {}: {reason}", path.display())
        }
        FallbackError::SystemRootUnresolved { reason } => {
            format!("Could not resolve Windows system directory: {reason}")
        }
        FallbackError::EnumeratePathsUnsupported | FallbackError::IngressUnsupported => {
            e.to_string()
        }
    }
}

/// Serialize a [`ProbeOutput`] as pretty-printed JSON.
///
/// Returns `Err` only if the underlying serializer fails — in practice
/// this should be infallible for the well-formed `ProbeOutput` we
/// produce, but we surface the error rather than panic.
pub fn to_json_pretty(output: &ProbeOutput) -> Result<String, serde_json::Error> {
    serde_json::to_string_pretty(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::{
        ContainerPolicy, ExecutionRequest, NetworkAction, NetworkIngressPolicy,
    };
    use crate::process_container_common::fallback_detector::IsolationTier;
    use crate::process_container_common::test_env::{CaptureCapabilityGuard, ForceTierGuard};

    fn all_ui_capabilities() -> UiCapabilitySupport {
        UiCapabilitySupport {
            can_block_clipboard_read: true,
            can_block_clipboard_write: true,
            can_block_input_injection: true,
            can_block_input_method_changes: true,
            can_block_external_ui_objects: true,
            can_block_global_ui_namespace: true,
            can_block_desktop_switching: true,
            can_block_logoff_or_shutdown: true,
            can_block_system_parameter_changes: true,
            can_block_display_settings_changes: true,
        }
    }

    fn request_with_policy(policy: ContainerPolicy) -> ExecutionRequest {
        ExecutionRequest {
            policy,
            ..Default::default()
        }
    }

    fn test_probe_facts(
        native_capture_available: bool,
        guarded_capture_available: bool,
    ) -> ProbeFacts {
        ProbeFacts {
            base_container_api_present: true,
            native_capture_available,
            guarded_capture_available,
            bfscfg_present: false,
            bfs_compiled_in: false,
            base_container_supports_deny_paths: false,
            base_container_supports_enumerate_paths: false,
            base_container_supports_ingress_host_loopback_allow: false,
            isolation_session_available: false,
            hyperlight_available: false,
            ui_capabilities: all_ui_capabilities(),
        }
    }

    #[test]
    fn probe_output_serializes() {
        let out = ProbeOutput {
            tier: Some("base-container"),
            needs_dacl_augmentation: Some(false),
            warnings: vec!["a warning".to_string()],
            probes: ProbeFacts {
                base_container_api_present: true,
                native_capture_available: true,
                guarded_capture_available: true,
                bfscfg_present: false,
                bfs_compiled_in: false,
                base_container_supports_deny_paths: false,
                base_container_supports_enumerate_paths: false,
                base_container_supports_ingress_host_loopback_allow: false,
                isolation_session_available: true,
                hyperlight_available: false,
                ui_capabilities: all_ui_capabilities(),
            },
            error: None,
        };
        let json = serde_json::to_string(&out).expect("serialize");
        let v: serde_json::Value = serde_json::from_str(&json).expect("parse");
        assert_eq!(v["tier"], "base-container");
        assert_eq!(v["needsDaclAugmentation"], false);
        assert_eq!(v["warnings"][0], "a warning");
        assert_eq!(v["probes"]["baseContainerApiPresent"], true);
        assert_eq!(v["probes"]["nativeCaptureAvailable"], true);
        assert_eq!(v["probes"]["guardedCaptureAvailable"], true);
        assert_eq!(v["probes"]["bfscfgPresent"], false);
        assert_eq!(v["probes"]["bfsCompiledIn"], false);
        assert_eq!(v["probes"]["baseContainerSupportsDenyPaths"], false);
        assert_eq!(v["probes"]["baseContainerSupportsEnumeratePaths"], false);
        assert_eq!(
            v["probes"]["baseContainerSupportsIngressHostLoopbackAllow"],
            false
        );
        assert_eq!(v["probes"]["isolationSessionAvailable"], true);
        assert_eq!(v["probes"]["uiCapabilities"]["canBlockClipboardRead"], true);
        assert_eq!(
            v["probes"]["uiCapabilities"]["canBlockInputInjection"],
            true
        );
        assert_eq!(
            v["probes"]["uiCapabilities"]["canBlockInputMethodChanges"],
            true
        );
        assert!(v.get("error").is_none());
    }

    #[test]
    fn probe_serializes_partial_ui_capabilities() {
        let out = ProbeOutput {
            tier: Some("appcontainer-dacl"),
            needs_dacl_augmentation: Some(true),
            warnings: vec![],
            probes: ProbeFacts {
                base_container_api_present: false,
                native_capture_available: false,
                guarded_capture_available: false,
                bfscfg_present: false,
                bfs_compiled_in: false,
                base_container_supports_deny_paths: false,
                base_container_supports_enumerate_paths: false,
                base_container_supports_ingress_host_loopback_allow: false,
                isolation_session_available: false,
                hyperlight_available: false,
                ui_capabilities: UiCapabilitySupport {
                    can_block_input_injection: false,
                    can_block_input_method_changes: false,
                    ..all_ui_capabilities()
                },
            },
            error: None,
        };
        let v = serde_json::to_value(&out).expect("to_value");
        let probes = v["probes"].as_object().expect("probes object");
        assert!(probes.contains_key("uiCapabilities"));
        assert_eq!(
            v["probes"]["uiCapabilities"]["canBlockInputInjection"],
            false
        );
        assert_eq!(
            v["probes"]["uiCapabilities"]["canBlockInputMethodChanges"],
            false
        );
        assert_eq!(v["probes"]["uiCapabilities"]["canBlockClipboardRead"], true);
    }

    #[test]
    fn request_capabilities_control_base_container_selection() {
        let _lock = crate::process_container_common::test_env::lock();
        // SAFETY: env-var mutation is serialized by the shared test lock.
        unsafe {
            std::env::set_var("MXC_FORCE_BC_USABLE", "1");
        }
        let request = ExecutionRequest::default();
        let selected = run_probe(&request, false);
        // SAFETY: env-var mutation is serialized by the shared test lock.
        unsafe {
            std::env::remove_var("MXC_FORCE_BC_USABLE");
        }

        assert_eq!(selected.tier, Some("base-container"));
        assert!(selected.error.is_none());
    }

    #[test]
    fn capture_denials_remains_launchable_on_appcontainer_fallback() {
        let _guard = ForceTierGuard::set_tier(IsolationTier::AppContainerDacl);
        let policy = ContainerPolicy {
            capture_denials: Some(Default::default()),
            ..Default::default()
        };
        let request = request_with_policy(policy);

        let output = run_probe_with_tier_decision(
            &request,
            test_probe_facts(false, true),
            fallback_detector::choose_backend_tier(&request),
        );

        assert_eq!(output.tier, Some("appcontainer-dacl"));
        assert!(!output.probes.native_capture_available);
        assert!(output.error.is_none());
    }

    #[test]
    fn capture_denials_requires_guarded_capture_on_appcontainer_fallback() {
        let _guard = ForceTierGuard::set_tier(IsolationTier::AppContainerDacl);
        let policy = ContainerPolicy {
            capture_denials: Some(Default::default()),
            ..Default::default()
        };
        let request = request_with_policy(policy);
        let output = run_probe_with_tier_decision(
            &request,
            test_probe_facts(false, false),
            fallback_detector::choose_backend_tier(&request),
        );

        assert!(output.tier.is_none());
        assert!(output.needs_dacl_augmentation.is_none());
        assert!(!output.probes.guarded_capture_available);
        assert_eq!(
            output.error.as_deref(),
            Some("guarded WPR captureDenials fallback is unavailable")
        );
    }

    #[test]
    fn native_capture_does_not_require_guarded_capture_on_base_container() {
        let _guard = ForceTierGuard::set_tier(IsolationTier::BaseContainer);
        let policy = ContainerPolicy {
            capture_denials: Some(Default::default()),
            ..Default::default()
        };
        let request = request_with_policy(policy);
        let output = run_probe_with_tier_decision(
            &request,
            test_probe_facts(true, false),
            fallback_detector::choose_backend_tier(&request),
        );

        assert_eq!(output.tier, Some("base-container"));
        assert!(!output.probes.guarded_capture_available);
        assert!(output.error.is_none());
    }

    #[test]
    fn public_probe_reports_native_capture_and_selects_base_container() {
        let _guard = CaptureCapabilityGuard::set(true, true);
        let policy = ContainerPolicy {
            capture_denials: Some(Default::default()),
            ..Default::default()
        };

        let output = run_probe(&request_with_policy(policy), true);

        assert_eq!(output.tier, Some("base-container"));
        assert!(output.probes.native_capture_available);
        assert!(output.error.is_none());
    }

    #[test]
    fn public_probe_keeps_capture_launchable_without_native_capture() {
        let _guard = CaptureCapabilityGuard::set(false, false);
        let policy = ContainerPolicy {
            capture_denials: Some(Default::default()),
            ..Default::default()
        };

        let output = run_probe(&request_with_policy(policy), true);

        assert_ne!(output.tier, Some("base-container"));
        assert!(!output.probes.native_capture_available);
        assert!(output.error.is_none());
    }

    #[test]
    fn public_probe_rejects_unavailable_guarded_capture() {
        let _guard = CaptureCapabilityGuard::set(false, false);
        let policy = ContainerPolicy {
            capture_denials: Some(Default::default()),
            ..Default::default()
        };

        let output = run_probe(&request_with_policy(policy), false);

        assert!(output.tier.is_none());
        assert!(!output.probes.native_capture_available);
        assert!(!output.probes.guarded_capture_available);
        assert_eq!(
            output.error.as_deref(),
            Some("guarded WPR captureDenials fallback is unavailable")
        );
    }

    #[test]
    fn tier_strings_stable() {
        assert_eq!(IsolationTier::BaseContainer.as_str(), "base-container");
        assert_eq!(IsolationTier::AppContainerBfs.as_str(), "appcontainer-bfs");
        assert_eq!(
            IsolationTier::AppContainerDacl.as_str(),
            "appcontainer-dacl"
        );
    }

    #[test]
    fn run_probe_with_force_tier() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerBfs);
        let request = ExecutionRequest::default();
        let out = run_probe(&request, true);
        assert_eq!(out.tier, Some("appcontainer-bfs"));
        assert_eq!(out.needs_dacl_augmentation, Some(false));
        assert!(out.error.is_none());
    }

    #[test]
    fn run_probe_handles_dacl_disabled_error() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerDacl);
        let mut policy = ContainerPolicy::default();
        policy.fallback.allow_dacl_mutation = false;
        let out = run_probe(&request_with_policy(policy), true);
        assert!(out.tier.is_none());
        assert!(out.needs_dacl_augmentation.is_none());
        assert!(out.error.is_some());
        let msg = out.error.unwrap();
        assert!(
            msg.contains("DACL fallback"),
            "expected DACL fallback message, got: {msg}"
        );
    }

    #[test]
    fn omitted_fields_when_error() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerDacl);
        let mut policy = ContainerPolicy::default();
        policy.fallback.allow_dacl_mutation = false;
        let out = run_probe(&request_with_policy(policy), true);
        let v = serde_json::to_value(&out).expect("to_value");
        let obj = v.as_object().expect("object");
        assert!(
            !obj.contains_key("tier"),
            "tier key should be absent on error, got: {v}"
        );
        assert!(
            !obj.contains_key("needsDaclAugmentation"),
            "needsDaclAugmentation key should be absent on error, got: {v}"
        );
        assert!(obj.contains_key("error"));
        assert!(obj.contains_key("warnings"));
        assert!(obj.contains_key("probes"));
    }

    #[test]
    fn probe_always_emits_isolation_session_available() {
        // The SDK's isolation-session gate reads this non-optional field, so
        // it must always serialize (never omitted), even when false.
        let out = run_probe(&ExecutionRequest::default(), true);
        let v = serde_json::to_value(&out).expect("to_value");
        let probes = v["probes"].as_object().expect("probes object");
        assert!(
            probes.contains_key("isolationSessionAvailable"),
            "isolationSessionAvailable must always be present, got: {v}"
        );
    }

    #[test]
    fn request_detector_keeps_supported_denied_paths_on_base_container() {
        let _guard = crate::process_container_common::test_env::lock();
        // SAFETY: env-var mutation is serialized by the shared test lock.
        unsafe {
            std::env::set_var("MXC_FORCE_BC_USABLE", "1");
            std::env::set_var("MXC_FORCE_DENY_PATHS", "1");
        }
        let mut request = ExecutionRequest::default();
        request.policy.denied_paths = vec!["C:\\secret".to_string()];

        let decision = fallback_detector::choose_backend_tier(&request)
            .expect("BaseContainer should be selected");
        // SAFETY: env-var mutation is serialized by the shared test lock.
        unsafe {
            std::env::remove_var("MXC_FORCE_BC_USABLE");
            std::env::remove_var("MXC_FORCE_DENY_PATHS");
        }

        assert_eq!(decision.tier, IsolationTier::BaseContainer);
    }

    #[test]
    fn request_detector_rejects_enumerate_paths_without_compatible_base_container() {
        let _guard = crate::process_container_common::test_env::BcUsableGuard::set(false);
        let mut request = ExecutionRequest::default();
        request.policy.enumerate_paths = vec!["C:\\tools".to_string()];

        let error = fallback_detector::choose_backend_tier(&request)
            .expect_err("enumeratePaths must not fall through to AppContainer");

        assert!(matches!(error, FallbackError::EnumeratePathsUnsupported));
    }

    #[test]
    fn request_detector_rejects_host_loopback_without_compatible_base_container() {
        let _guard = crate::process_container_common::test_env::BcUsableGuard::set(false);
        let mut request = ExecutionRequest::default();
        request.policy.network_ingress = Some(NetworkIngressPolicy {
            default: NetworkAction::Deny,
            host_loopback: NetworkAction::Allow,
        });

        let error = fallback_detector::choose_backend_tier(&request)
            .expect_err("host-loopback ingress must not fall through to AppContainer");

        assert!(matches!(error, FallbackError::IngressUnsupported));
    }
}