mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Manager selection and shared helpers for the IsolationSession lifecycle.

use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;

use crate::mxc_common::audit::{AuditEvent, AuditEventName, TeardownStatus};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::process_util::{OwnedHandle, PipeReadCanceller};
use crate::mxc_common::state_aware_backend::{ExecHandle, ExecOutcome};

use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::Storage::FileSystem::{GetFileType, FILE_TYPE_CHAR};
use windows::Win32::System::Com::{CoDecrementMTAUsage, CoIncrementMTAUsage, CO_MTA_USAGE_COOKIE};
use windows::Win32::System::Console::{GetConsoleMode, CONSOLE_MODE};
use windows::Win32::System::Threading::WaitForSingleObject;

use super::console_relay::{create_console_relay_thread, ConsoleRelayParams};
use super::error::{lifecycle_err, op, transport_err, IsolationSessionError};
use super::manager_legacy::IsolationSessionManagerLegacy;
use super::manager_new::IsolationSessionManagerNew;
use super::pipe_relay::{
    create_relay_thread_with_stdin_closer, create_relay_thread_with_stop, duplicate_handle,
    PipeRelayWithStopParams, StdinCloser,
};
use super::process::ClosingProcess;
use super::process_options::ProcessOptions;
use super::use_new_implementation;

// The OS account name is lifecycle addressing data, not diagnostic identity.
pub(super) const AGENT_IDENTITY_MARKER: &str = "isolation-session-agent";

#[cfg(feature = "isosession-test-support")]
pub(super) fn check_expected_manager(actual: &str) -> Result<(), IsolationSessionError> {
    if let Some(expected) = std::env::var_os("MXC_TEST_EXPECT_ISOLATION_SESSION_IMPL") {
        if expected != actual {
            return Err(lifecycle_err(format!(
                "expected {expected:?} IsolationSession implementation, activated {actual}"
            )));
        }
    }
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StdinHandleKind {
    Console,
    PipeOrFile,
}

fn classify_stdin_handle(handle: HANDLE) -> StdinHandleKind {
    let file_type = unsafe { GetFileType(handle) };
    if file_type == FILE_TYPE_CHAR {
        let mut mode = CONSOLE_MODE(0);
        if unsafe { GetConsoleMode(handle, &mut mode) }.is_ok() {
            return StdinHandleKind::Console;
        }
    }
    StdinHandleKind::PipeOrFile
}

pub(super) fn stdin_closer_with_diagnostics(
    callback: impl FnOnce() -> Result<(), IsolationSessionError> + Send + 'static,
    mut diagnostics: Logger,
) -> StdinCloser {
    Box::new(move || match catch_unwind(AssertUnwindSafe(callback)) {
        Ok(Ok(())) => {}
        Ok(Err(error)) => {
            diagnostics.log_diagnostic_line(&format!("Closing stdin at EOF failed: {error}"))
        }
        Err(_) => diagnostics.log_diagnostic_line("Closing stdin at EOF panicked"),
    })
}

/// # Safety
/// Handles must be valid during setup. Console input is borrowed and must
/// remain valid until the relay exits; the other handles are duplicated.
pub(super) unsafe fn create_stdin_relay(
    stdin: HANDLE,
    destination: HANDLE,
    stop_event: HANDLE,
    interactive: bool,
    stdin_closer: Option<StdinCloser>,
    resize_callback: impl Fn(u16, u16) + Send + 'static,
) -> Result<(OwnedHandle, Option<PipeReadCanceller>), IsolationSessionError> {
    // Choose the relay from stdin itself; `interactive` describes stdout.
    if classify_stdin_handle(stdin) == StdinHandleKind::PipeOrFile {
        let stdin_closer = if !interactive { stdin_closer } else { None };
        let (thread, canceller) =
            unsafe { create_relay_thread_with_stdin_closer(stdin, destination, stdin_closer) }
                .map_err(|e| lifecycle_err(format!("create stdin relay: {e}")))?
                .into_thread_and_canceller();
        return Ok((thread, Some(canceller)));
    }

    // process.Close() can release the original while the relay is still writing.
    let h_write = duplicate_handle(destination)
        .map_err(|e| lifecycle_err(format!("duplicate stdin handle: {e}")))?;
    let h_stop_event = duplicate_handle(stop_event)
        .map_err(|e| lifecycle_err(format!("duplicate stdin stop event: {e}")))?;
    let thread = if interactive {
        unsafe {
            create_console_relay_thread(ConsoleRelayParams {
                h_read: stdin,
                h_write,
                h_stop_event,
                resize_callback: Box::new(resize_callback),
            })
        }
        .map_err(|e| lifecycle_err(format!("create console-aware stdin relay: {e}")))?
    } else {
        unsafe {
            create_relay_thread_with_stop(PipeRelayWithStopParams {
                h_read: stdin,
                h_write,
                h_stop_event,
            })
        }
        .map_err(|e| lifecycle_err(format!("create stdin relay: {e}")))?
    };
    Ok((thread, None))
}

/// Keeps the process's MTA alive for as long as the lifecycle's WinRT objects,
/// which outlive the call that created them.
/// `CoIncrementMTAUsage` holds a reference releasable from any thread;
/// `CoUninitialize` is thread-affine and would tear the apartment down under a
/// live object.
pub(super) struct MtaReference {
    cookie: CO_MTA_USAGE_COOKIE,
}

impl MtaReference {
    pub(super) fn acquire() -> Result<Self, IsolationSessionError> {
        // SAFETY: the out-parameter is a valid, writable local.
        let cookie = unsafe { CoIncrementMTAUsage() }.map_err(|e| {
            transport_err(
                op::CO_INCREMENT_MTA_USAGE,
                "could not keep a multi-threaded apartment alive",
                &e,
            )
        })?;
        Ok(Self { cookie })
    }
}

impl Drop for MtaReference {
    fn drop(&mut self) {
        // SAFETY: balances the `CoIncrementMTAUsage` in `acquire`. The cookie is
        // not thread-affine, so this is sound on whichever thread drops it.
        unsafe {
            let _ = CoDecrementMTAUsage(self.cookie);
        }
    }
}

// SAFETY: the cookie is an opaque token, never dereferenced, and
// `CoDecrementMTAUsage` accepts it from any thread.
unsafe impl Send for MtaReference {}
unsafe impl Sync for MtaReference {}

/// `GetFeatureLevel` fails on a host that does not recognize the feature
/// value, so an error reads as not supported.
pub(super) fn feature_supported_from(level: windows_core::Result<i32>) -> bool {
    matches!(level, Ok(level) if level > 0)
}

/// The provision-time facts the OS assigns to a freshly-created agent user,
/// read from `IsoSessionUserResult` at `add_user`. The addressing key for
/// every later lifecycle op remains `agent_user_name`; the other two fields
/// are provision metadata surfaced to the caller.
pub(super) struct ProvisionedUser {
    /// The OS-assigned agent account name (also the `sandboxId` tail).
    pub agent_user_name: String,
    /// The security identifier (SID) of the agent user. Diagnostic only.
    pub agent_user_sid: String,
    /// A directory shared between the calling user and this isolated agent
    /// user, through which the caller can stage files into the session. Each
    /// isolated user can access only its own workspace; the caller can access
    /// all of them. Deleted when the agent user is deprovisioned.
    pub ephemeral_workspace_path: String,
}

pub(super) trait IsolationSessionManager: Send {
    fn pty_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&Logger>,
    ) -> Result<Arc<ClosingProcess>, IsolationSessionError>;
    fn start_session(&self) -> Result<(), IsolationSessionError>;
    fn create_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&mut Logger>,
    ) -> Result<ExecOutcome, IsolationSessionError>;
    fn piped_exec_handle(
        &self,
        options: &ProcessOptions,
        timeout_ms: u32,
        logger: Option<&Logger>,
    ) -> Result<ExecHandle, IsolationSessionError>;
    fn stop_session(&self) -> Result<(), IsolationSessionError>;
    fn deprovision_agent_user(&self) -> Result<(), IsolationSessionError>;
}

pub(super) fn open_manager(
    use_new: Option<bool>,
    agent_user_name: &str,
) -> Result<Box<dyn IsolationSessionManager>, IsolationSessionError> {
    if use_new_implementation(use_new) {
        Ok(Box::new(IsolationSessionManagerNew::new(agent_user_name)?))
    } else {
        Ok(Box::new(IsolationSessionManagerLegacy::new(
            agent_user_name,
        )?))
    }
}

pub(super) fn add_user(
    use_new: Option<bool>,
    app_id: Option<&str>,
) -> Result<(ProvisionedUser, Box<dyn IsolationSessionManager>), IsolationSessionError> {
    if use_new_implementation(use_new) {
        let (user, manager) = IsolationSessionManagerNew::add_user(app_id)?;
        Ok((user, Box::new(manager)))
    } else {
        let (user, manager) = IsolationSessionManagerLegacy::add_user(app_id)?;
        Ok((user, Box::new(manager)))
    }
}

#[derive(Debug, Default, Clone, Copy)]
pub struct TeardownOutcome {
    pub session_stopped: Option<bool>,
    pub agent_user_deprovisioned: Option<bool>,
}

impl TeardownOutcome {
    fn status(&self) -> TeardownStatus {
        let steps = [self.session_stopped, self.agent_user_deprovisioned];
        if steps.contains(&Some(false)) {
            TeardownStatus::Failure
        } else if steps.iter().all(Option::is_none) {
            TeardownStatus::Skipped
        } else {
            TeardownStatus::Success
        }
    }
}

pub fn log_sandbox_torn_down(logger: &mut Logger, phase: &str, outcome: TeardownOutcome) {
    if !logger.has_diagnostic_sink() && !crate::mxc_common::telemetry::is_active() {
        return;
    }
    crate::mxc_common::telemetry::log_sandbox_torn_down(
        AGENT_IDENTITY_MARKER,
        outcome.status().as_str(),
        &format!(
            "session_stopped={},agent_user_deprovisioned={}",
            outcome.session_stopped == Some(true),
            outcome.agent_user_deprovisioned == Some(true),
        ),
    );
    let record = AuditEvent::new(AuditEventName::SandboxTornDown)
        .str("backend", "isolation_session")
        .str("identity", AGENT_IDENTITY_MARKER)
        .str("phase", phase)
        .str("status", outcome.status().as_str())
        .bool("session_stopped", outcome.session_stopped == Some(true))
        .bool(
            "agent_user_deprovisioned",
            outcome.agent_user_deprovisioned == Some(true),
        );
    logger.log_audit_event(&record);
}

pub(super) fn wait_for_relay(
    relay: Option<&OwnedHandle>,
    timeout_ms: u32,
) -> Result<bool, IsolationSessionError> {
    let Some(relay) = relay else {
        return Ok(true);
    };
    // SAFETY: the relay's owned thread handle remains valid throughout the wait.
    match unsafe { WaitForSingleObject(relay.get(), timeout_ms) } {
        WAIT_OBJECT_0 => Ok(true),
        WAIT_TIMEOUT => Ok(false),
        _ => Err(lifecycle_err(format!(
            "waiting for relay failed: {}",
            std::io::Error::last_os_error()
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::logger::Mode;
    use crate::mxc_common::sandbox_process::StreamCloser;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use windows::Win32::System::Threading::{CreateEventW, SetEvent};
    use windows_core::PCWSTR;

    fn counting_stdin_closer(calls: Arc<AtomicUsize>) -> StdinCloser {
        Box::new(move || {
            calls.fetch_add(1, Ordering::SeqCst);
        })
    }

    #[test]
    fn stdin_closer_reports_errors_and_panics() {
        for panic in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("stdin.log");
            let mut logger = Logger::new(Mode::Buffer);
            logger.enable_file_sink(&path).unwrap();
            let closer = stdin_closer_with_diagnostics(
                move || {
                    if panic {
                        panic!("injected stdin close panic");
                    }
                    Err(lifecycle_err("injected stdin close error"))
                },
                logger,
            );
            closer();
            let logged = std::fs::read_to_string(path).unwrap();
            assert_eq!(logged.lines().count(), 1, "{logged}");
            assert!(
                logged.contains(if panic {
                    "Closing stdin at EOF panicked"
                } else {
                    "Closing stdin at EOF failed:"
                }),
                "{logged}"
            );
            if !panic {
                assert!(logged.contains("injected stdin close error"), "{logged}");
            }
        }
    }

    fn read_stdin_test_payload(handle: HANDLE, size: usize) -> Vec<u8> {
        use std::time::{Duration, Instant};
        use windows::Win32::Storage::FileSystem::ReadFile;
        use windows::Win32::System::Pipes::PeekNamedPipe;

        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let mut available = 0;
            unsafe { PeekNamedPipe(handle, None, 0, None, Some(&mut available), None) }
                .expect("destination pipe should remain readable");
            if available as usize >= size {
                let mut payload = vec![0; size];
                let mut read = 0;
                unsafe { ReadFile(handle, Some(&mut payload), Some(&mut read), None) }.unwrap();
                payload.truncate(read as usize);
                return payload;
            }
            assert!(
                Instant::now() < deadline,
                "selected stdin relay did not deliver the payload"
            );
            std::thread::sleep(Duration::from_millis(1));
        }
    }

    #[test]
    fn stdin_routing_delivers_pipe_input_and_releases_writer_for_both_output_modes() {
        use crate::mxc_common::process_util::{create_local_pipe, PipeWriter};
        use std::io::Write;
        use windows::Win32::Foundation::ERROR_BROKEN_PIPE;
        use windows::Win32::System::Pipes::PeekNamedPipe;

        for (interactive, cancel) in [(true, true), (true, false), (false, true), (false, false)] {
            let (source_read, source_write) = create_local_pipe().unwrap();
            let mut source_write = PipeWriter::new(source_write);
            let (dest_read, dest_write) = create_local_pipe().unwrap();
            let stop = OwnedHandle::new(unsafe {
                CreateEventW(None, true, false, PCWSTR::null()).unwrap()
            });
            let calls = Arc::new(AtomicUsize::new(0));
            // SAFETY: all handles remain valid until the relay has exited.
            let (relay, canceller) = unsafe {
                create_stdin_relay(
                    source_read.get(),
                    dest_write.get(),
                    stop.get(),
                    interactive,
                    Some(counting_stdin_closer(Arc::clone(&calls))),
                    |_, _| panic!("pipe input must not handle console resize"),
                )
            }
            .unwrap();

            let payload = b"stdin payload\r\n";
            source_write.write_all(payload).unwrap();
            let received = read_stdin_test_payload(dest_read.get(), payload.len());
            assert!(!wait_for_relay(Some(&relay), 0).unwrap());
            if cancel {
                canceller
                    .expect("pipe input must have a read canceller")
                    .close();
            } else {
                drop(source_write);
            }
            assert!(wait_for_relay(Some(&relay), 5000).unwrap());
            assert_eq!(received, payload);

            assert_eq!(
                calls.load(Ordering::SeqCst),
                if !interactive && !cancel { 1 } else { 0 }
            );
            drop(dest_write);
            let error = unsafe { PeekNamedPipe(dest_read.get(), None, 0, None, None, None) }
                .expect_err("the selected relay must release its write duplicate");
            assert_eq!(error.code(), ERROR_BROKEN_PIPE.to_hresult());
        }
    }

    #[test]
    fn stdin_routing_delivers_file_input_for_both_output_modes() {
        use crate::mxc_common::process_util::create_local_pipe;
        use std::io::{Seek, Write};
        use std::os::windows::io::AsRawHandle;

        for interactive in [true, false] {
            let mut input = tempfile::tempfile().unwrap();
            let payload = b"file input\r\n";
            input.write_all(payload).unwrap();
            input.rewind().unwrap();
            let (dest_read, dest_write) = create_local_pipe().unwrap();
            let stop = OwnedHandle::new(unsafe {
                CreateEventW(None, true, false, PCWSTR::null()).unwrap()
            });
            let calls = Arc::new(AtomicUsize::new(0));
            // SAFETY: all handles remain valid until the relay has exited.
            let (relay, canceller) = unsafe {
                create_stdin_relay(
                    HANDLE(input.as_raw_handle()),
                    dest_write.get(),
                    stop.get(),
                    interactive,
                    Some(counting_stdin_closer(Arc::clone(&calls))),
                    |_, _| panic!("file input must not handle console resize"),
                )
            }
            .unwrap();
            let received = read_stdin_test_payload(dest_read.get(), payload.len());
            assert!(wait_for_relay(Some(&relay), 5000).unwrap());
            assert!(
                canceller.is_some(),
                "file input must select the cancellable relay"
            );
            assert_eq!(received, payload);
            assert_eq!(
                calls.load(Ordering::SeqCst),
                if interactive { 0 } else { 1 }
            );
        }
    }

    #[test]
    fn stdin_routing_console_uses_stop_event_for_both_output_modes() {
        use crate::mxc_common::process_util::create_local_pipe;
        use std::os::windows::process::CommandExt;
        use std::process::{Command, Stdio};
        use std::time::{Duration, Instant};
        use windows::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE};
        use windows::Win32::Storage::FileSystem::{
            CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
        };
        use windows::Win32::System::Threading::CREATE_NEW_CONSOLE;

        const CHILD: &str = "MXC_STDIN_ROUTING_CONSOLE_CHILD";
        if std::env::var_os(CHILD).is_none() {
            // Restart this test with a real console; the runner may have none.
            let test_name = "backend_modules::isolation_session::common::manager::tests::\
                stdin_routing_console_uses_stop_event_for_both_output_modes";
            let mut child = Command::new(std::env::current_exe().unwrap())
                .args(["--exact", test_name])
                .env(CHILD, "1")
                .creation_flags(CREATE_NEW_CONSOLE.0)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()
                .unwrap();
            let deadline = Instant::now() + Duration::from_secs(20);
            while child.try_wait().unwrap().is_none() {
                if Instant::now() >= deadline {
                    child.kill().unwrap();
                    let output = child.wait_with_output().unwrap();
                    panic!("console routing child timed out: {output:?}");
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            let output = child.wait_with_output().unwrap();
            assert!(
                output.status.success(),
                "console routing child failed: {output:?}"
            );
            assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
            return;
        }

        let console = OwnedHandle::new(unsafe {
            CreateFileW(
                windows_core::w!("CONIN$"),
                GENERIC_READ.0 | GENERIC_WRITE.0,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                None,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                None,
            )
            .unwrap()
        });
        assert_eq!(
            classify_stdin_handle(console.get()),
            StdinHandleKind::Console
        );
        for interactive in [true, false] {
            let (_dest_read, dest_write) = create_local_pipe().unwrap();
            let stop = OwnedHandle::new(unsafe {
                CreateEventW(None, true, false, PCWSTR::null()).unwrap()
            });
            let calls = Arc::new(AtomicUsize::new(0));
            // SAFETY: the private console and pipes outlive the relay.
            let (relay, canceller) = unsafe {
                create_stdin_relay(
                    console.get(),
                    dest_write.get(),
                    stop.get(),
                    interactive,
                    Some(counting_stdin_closer(Arc::clone(&calls))),
                    |_, _| {},
                )
            }
            .unwrap();
            assert!(canceller.is_none(), "console input must use the stop event");
            unsafe { SetEvent(stop.get()).unwrap() };
            assert!(wait_for_relay(Some(&relay), 5000).unwrap());
            assert_eq!(calls.load(Ordering::SeqCst), 0);
        }
    }

    #[test]
    fn stdin_shutdown_reports_wait_failure() {
        let invalid = OwnedHandle::new(HANDLE::default());
        let error = wait_for_relay(Some(&invalid), 0).unwrap_err();
        assert!(error.to_string().contains("waiting for relay failed"));
        assert!(wait_for_relay(None, 0).unwrap());
    }

    #[test]
    fn teardown_status_distinguishes_failure_success_and_skipped() {
        assert_eq!(TeardownOutcome::default().status(), TeardownStatus::Skipped);
        assert_eq!(
            TeardownOutcome {
                session_stopped: Some(true),
                agent_user_deprovisioned: Some(true),
            }
            .status(),
            TeardownStatus::Success
        );
        assert_eq!(
            TeardownOutcome {
                session_stopped: Some(true),
                ..Default::default()
            }
            .status(),
            TeardownStatus::Success
        );
        assert_eq!(
            TeardownOutcome {
                session_stopped: Some(true),
                agent_user_deprovisioned: Some(false),
            }
            .status(),
            TeardownStatus::Failure
        );
    }

    #[test]
    fn teardown_record_satisfies_the_requirement_contract() {
        let outcome = TeardownOutcome {
            session_stopped: Some(true),
            agent_user_deprovisioned: Some(false),
        };
        let event = AuditEvent::new(AuditEventName::SandboxTornDown)
            .str("backend", "isolation_session")
            .str("identity", AGENT_IDENTITY_MARKER)
            .str("phase", "deprovision")
            .str("status", outcome.status().as_str())
            .bool("agent_user_deprovisioned", false);
        assert!(event.missing_required_fields().is_empty());
        assert!(event.to_json_line().contains(r#""status":"failure""#));
    }

    #[test]
    fn feature_support_requires_a_positive_feature_level() {
        // Supported: any positive level.
        assert!(feature_supported_from(Ok(1)));
        assert!(feature_supported_from(Ok(7)));

        // Not supported: the host knows the feature but does not offer it.
        assert!(!feature_supported_from(Ok(0)));
        assert!(!feature_supported_from(Ok(-1)));

        // Not supported: an older host rejects the unknown feature value.
        assert!(!feature_supported_from(Err(
            windows_core::Error::from_hresult(
                windows_core::HRESULT(0x8007_0057u32 as i32), // E_INVALIDARG
            )
        )));
    }
}