Skip to main content

mxc_sdk/
sandbox.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! The SDK's sandbox handle: a crate-owned facade over the internal
5//! `mxc_common` streaming handle, so the public API never exposes the
6//! foundation crate's traits.
7
8use std::io::{Read, Write};
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::sync::{Arc, Mutex};
11use std::time::Duration;
12
13pub use crate::mxc_common::models::{
14    CaptureDenialsErrorOutput as CaptureDenialsError, CaptureDenialsOutput as CaptureDenialsResult,
15    SandboxOutputMetadata as ExecutionMetadata,
16};
17use crate::mxc_common::sandbox_process::{
18    NativeStdio, SandboxProcess, StreamCloser as InnerCloser,
19};
20use crate::mxc_common::state_aware_backend::ExecOutcome;
21use crate::mxc_common::state_aware_operation::StateAwareOperation;
22use crate::options::{
23    DeprovisionOptions, ProvisionOptions, SpawnInContainerOptions, SpawnInContainerWithPtyOptions,
24    StartOptions, StopOptions,
25};
26use crate::state_aware_sdk::{
27    lifecycle_sdk_input, ContainerId, ExecutionRequest, LifecycleResult, ProvisionRequest,
28    ProvisionResult, StateAwareResult, ValidationResult,
29};
30use crate::Error;
31
32fn run_typed_state_aware(
33    input: crate::mxc_common::sdk_input::SdkStateAwareInput,
34    dry_run: bool,
35) -> Result<StateAwareResult, Error> {
36    crate::mxc_engine::run_typed_state_aware_request(input, false, dry_run)
37        .map(StateAwareResult::from_engine)
38}
39
40/// Provision a container from typed Rust policy.
41pub fn provision(
42    request: ProvisionRequest,
43    options: ProvisionOptions,
44) -> Result<ProvisionResult, Error> {
45    let input = request
46        .into_sdk_input(options.telemetry)
47        .map_err(Error::from)?;
48    run_typed_state_aware(input, false)?
49        .into_provision()
50        .map_err(Error::from)
51}
52
53/// Validate a provision request without creating a container.
54pub fn validate_provision(
55    request: ProvisionRequest,
56    options: ProvisionOptions,
57) -> Result<ValidationResult, Error> {
58    let input = request
59        .into_sdk_input(options.telemetry)
60        .map_err(Error::from)?;
61    run_typed_state_aware(input, true)?
62        .into_validation()
63        .map_err(Error::from)
64}
65
66/// Start an existing container.
67pub fn start(container_id: &ContainerId, options: StartOptions) -> Result<LifecycleResult, Error> {
68    let input = lifecycle_sdk_input(container_id, options.telemetry, |sandbox_id| {
69        StateAwareOperation::Start { sandbox_id }
70    })
71    .map_err(Error::from)?;
72    run_typed_state_aware(input, false)?
73        .into_lifecycle()
74        .map_err(Error::from)
75}
76
77/// Validate a start request without starting the container.
78pub fn validate_start(
79    container_id: &ContainerId,
80    options: StartOptions,
81) -> Result<ValidationResult, Error> {
82    let input = lifecycle_sdk_input(container_id, options.telemetry, |sandbox_id| {
83        StateAwareOperation::Start { sandbox_id }
84    })
85    .map_err(Error::from)?;
86    run_typed_state_aware(input, true)?
87        .into_validation()
88        .map_err(Error::from)
89}
90
91/// Stop an existing container.
92pub fn stop(container_id: &ContainerId, options: StopOptions) -> Result<LifecycleResult, Error> {
93    let input = lifecycle_sdk_input(container_id, options.telemetry, |sandbox_id| {
94        StateAwareOperation::Stop { sandbox_id }
95    })
96    .map_err(Error::from)?;
97    run_typed_state_aware(input, false)?
98        .into_lifecycle()
99        .map_err(Error::from)
100}
101
102/// Validate a stop request without stopping the container.
103pub fn validate_stop(
104    container_id: &ContainerId,
105    options: StopOptions,
106) -> Result<ValidationResult, Error> {
107    let input = lifecycle_sdk_input(container_id, options.telemetry, |sandbox_id| {
108        StateAwareOperation::Stop { sandbox_id }
109    })
110    .map_err(Error::from)?;
111    run_typed_state_aware(input, true)?
112        .into_validation()
113        .map_err(Error::from)
114}
115
116/// Deprovision an existing container.
117pub fn deprovision(
118    container_id: &ContainerId,
119    options: DeprovisionOptions,
120) -> Result<LifecycleResult, Error> {
121    let input = lifecycle_sdk_input(container_id, options.telemetry, |sandbox_id| {
122        StateAwareOperation::Deprovision { sandbox_id }
123    })
124    .map_err(Error::from)?;
125    run_typed_state_aware(input, false)?
126        .into_lifecycle()
127        .map_err(Error::from)
128}
129
130/// Validate a deprovision request without changing the container.
131pub fn validate_deprovision(
132    container_id: &ContainerId,
133    options: DeprovisionOptions,
134) -> Result<ValidationResult, Error> {
135    let input = lifecycle_sdk_input(container_id, options.telemetry, |sandbox_id| {
136        StateAwareOperation::Deprovision { sandbox_id }
137    })
138    .map_err(Error::from)?;
139    run_typed_state_aware(input, true)?
140        .into_validation()
141        .map_err(Error::from)
142}
143
144/// Spawn a workload in an existing container and return a live process.
145///
146/// On WSLC, killing a workload that is still running, or reaching its timeout,
147/// deletes its container about a minute later, because MXC does not signal a
148/// WSLC process that has stdin.
149pub fn spawn_in_container(
150    container_id: &ContainerId,
151    request: ExecutionRequest,
152    options: SpawnInContainerOptions,
153) -> Result<MxcProcess, Error> {
154    let input = request
155        .into_sdk_input(container_id, options.telemetry)
156        .map_err(Error::from)?;
157    crate::mxc_engine::exec_typed_state_aware_request(input, false, true).map(MxcProcess::new)
158}
159
160/// Spawn a workload in an existing container with a caller-controlled PTY.
161pub fn spawn_in_container_with_pty(
162    container_id: &ContainerId,
163    request: ExecutionRequest,
164    options: SpawnInContainerWithPtyOptions,
165) -> Result<MxcPtyProcess, Error> {
166    options.size.validate()?;
167    let input = request
168        .into_sdk_input(container_id, options.telemetry)
169        .map_err(Error::from)?;
170    crate::mxc_engine::exec_typed_state_aware_pty_request(input, false, options.size.into())
171        .and_then(MxcPtyProcess::new)
172}
173
174/// Validate an execution request without running a workload.
175pub fn validate_process(
176    container_id: &ContainerId,
177    request: ExecutionRequest,
178    options: SpawnInContainerOptions,
179) -> Result<ValidationResult, Error> {
180    let input = request
181        .into_sdk_input(container_id, options.telemetry)
182        .map_err(Error::from)?;
183    run_typed_state_aware(input, true)?
184        .into_validation()
185        .map_err(Error::from)
186}
187
188#[expect(
189    dead_code,
190    reason = "Attached exec is reserved but not exposed by the SDK yet"
191)]
192fn exec_in_attached(
193    container_id: &ContainerId,
194    request: ExecutionRequest,
195    options: SpawnInContainerOptions,
196) -> Result<WaitResult, Error> {
197    let input = request
198        .into_sdk_input(container_id, options.telemetry)
199        .map_err(Error::from)?;
200    crate::mxc_engine::exec_typed_state_aware_attached_request(input, false).map(|outcome| {
201        match outcome {
202            ExecOutcome::Exited(code) => WaitResult::Exited(code),
203            ExecOutcome::TimedOut => WaitResult::TimedOut,
204        }
205    })
206}
207
208/// The outcome of waiting on a [`MxcProcess`] (see [`MxcProcess::wait`]).
209///
210/// An ordinary exit and a timeout are both represented here as success
211/// outcomes; [`MxcProcess::wait`] reserves its `Err` for an actual OS / wait
212/// failure.
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214pub enum WaitResult {
215    /// The process exited with this code. On Unix a process terminated by a
216    /// signal (rather than exiting normally) surfaces as `Exited(-1)`.
217    Exited(i32),
218    /// The request's timeout elapsed while the process was running, and
219    /// the process is no longer running.
220    ///
221    /// **Deadline spent, and the process is gone.** Whether it was killed or
222    /// exited on its own a moment past the deadline is not distinguished: both
223    /// missed the deadline the caller asked for, and reporting the exit code
224    /// one of them happened to produce would hide that.
225    ///
226    /// How far "gone" reaches depends on the backend. A process-spawning
227    /// backend kills the whole tree. A backend whose only primitive is the
228    /// foreground process, such as IsolationSession execution in an existing
229    /// container, confirms that process, and a descendant the workload backgrounded is
230    /// reclaimed when the container is stopped and deprovisioned rather than here.
231    ///
232    /// That lifecycle route is reachable through
233    /// [`spawn_in_container`](crate::v1::container::spawn_in_container) when the
234    /// backend is compiled in via this crate's `isolation_session` feature.
235    /// IsolationSession requires no runtime experimental opt-in.
236    TimedOut,
237}
238
239/// The captured result of running a [`MxcProcess`] to completion via
240/// [`wait_with_output`](MxcProcess::wait_with_output).
241#[derive(Debug, Clone)]
242pub struct ExecutionResult {
243    /// How the process finished.
244    pub outcome: WaitResult,
245    /// Policy and operational warnings from the container, such as security
246    /// warnings, network rules that cannot carry traffic, or a cleanup step
247    /// that failed after the workload exited.
248    pub warnings: Vec<String>,
249    /// Everything the child wrote to stdout.
250    pub stdout: Vec<u8>,
251    /// Everything the child wrote to stderr.
252    pub stderr: Vec<u8>,
253    /// Structured outputs produced by optional container features.
254    pub output_metadata: Option<ExecutionMetadata>,
255}
256
257/// A live container process, returned by [`spawn`](crate::v1::spawn)
258/// and [`spawn_in_container`](crate::v1::container::spawn_in_container).
259///
260/// Stream the child's stdio with the `take_*` accessors, wait for it, or kill
261/// it. No pty is allocated; the streams are ordinary pipes. Any stdout/stderr
262/// the caller does not `take_*` is drained and discarded by [`wait`](Self::wait).
263pub struct MxcProcess {
264    inner: Box<dyn SandboxProcess>,
265    stdio_access: StdioAccess,
266}
267
268#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
269enum StdioAccess {
270    /// No stdio ownership has been transferred from the container process.
271    #[default]
272    Untouched,
273    /// One or more Rust streams were taken; remaining streams may be taken individually.
274    Individual,
275    /// All available native endpoints were transferred; individual access is disabled.
276    Native,
277}
278
279impl MxcProcess {
280    pub(crate) fn new(inner: Box<dyn SandboxProcess>) -> Self {
281        Self {
282            inner,
283            stdio_access: StdioAccess::Untouched,
284        }
285    }
286
287    /// Policy and operational warnings from this container, such as security
288    /// warnings, network rules that cannot carry traffic, or a cleanup step
289    /// that failed after the workload exited.
290    pub fn warnings(&self) -> Vec<String> {
291        self.inner.warnings()
292    }
293
294    /// Structured outputs available after a terminal wait completes.
295    pub fn output_metadata(&self) -> Option<&ExecutionMetadata> {
296        self.inner.output_metadata()
297    }
298
299    /// Take the child's stdin pipe; on WSLC, dropping it gives the child end-of-file.
300    /// Returns `None` after the first call.
301    pub fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>> {
302        if self.stdio_access == StdioAccess::Native {
303            return None;
304        }
305        let stream = self.inner.take_stdin();
306        if stream.is_some() {
307            self.stdio_access = StdioAccess::Individual;
308        }
309        stream
310    }
311
312    /// Take the child's stdout pipe. Returns `None` after the first call.
313    pub fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>> {
314        if self.stdio_access == StdioAccess::Native {
315            return None;
316        }
317        let stream = self.inner.take_stdout();
318        if stream.is_some() {
319            self.stdio_access = StdioAccess::Individual;
320        }
321        stream
322    }
323
324    /// Take the child's stderr pipe. Returns `None` after the first call.
325    pub fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>> {
326        if self.stdio_access == StdioAccess::Native {
327            return None;
328        }
329        let stream = self.inner.take_stderr();
330        if stream.is_some() {
331            self.stdio_access = StdioAccess::Individual;
332        }
333        stream
334    }
335
336    #[doc(hidden)]
337    pub fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
338        match self.stdio_access {
339            StdioAccess::Individual => {
340                return Err(std::io::Error::other(
341                    "native stdio must be taken before taking individual streams",
342                ));
343            }
344            StdioAccess::Native => return Ok(None),
345            StdioAccess::Untouched => {}
346        }
347        let stdio = self.inner.take_native_stdio()?;
348        if stdio.is_some() {
349            self.stdio_access = StdioAccess::Native;
350        }
351        Ok(stdio)
352    }
353
354    /// A [`StreamCloser`] that unblocks a parked blocking read on stdout without
355    /// killing the child. `None` if stdout was not piped.
356    pub fn stdout_closer(&self) -> Option<StreamCloser> {
357        self.inner.stdout_closer().map(StreamCloser::new)
358    }
359
360    /// As [`stdout_closer`](Self::stdout_closer), for stderr.
361    pub fn stderr_closer(&self) -> Option<StreamCloser> {
362        self.inner.stderr_closer().map(StreamCloser::new)
363    }
364
365    /// Non-blocking exit check: `Some(code)` if the child has exited.
366    pub fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
367        self.inner.try_wait()
368    }
369
370    /// Non-blocking terminal check that preserves structured backend failures.
371    pub fn try_wait_detailed(&mut self) -> Result<Option<WaitResult>, Error> {
372        match self.inner.try_wait() {
373            Ok(Some(code)) => Ok(Some(WaitResult::Exited(code))),
374            Ok(None) => Ok(None),
375            Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {
376                Ok(Some(WaitResult::TimedOut))
377            }
378            Err(error) => Err(detailed_wait_error(
379                error,
380                "querying the sandbox process status failed",
381            )),
382        }
383    }
384
385    /// The child's process id.
386    pub fn id(&self) -> u32 {
387        self.inner.id()
388    }
389
390    /// Kill the child.
391    pub fn kill(&mut self) -> std::io::Result<()> {
392        self.inner.kill()
393    }
394
395    /// Request timeout termination and permanently classify a later successful
396    /// terminal observation as timed out. Call only after the deadline elapsed.
397    #[doc(hidden)]
398    pub fn kill_for_timeout(&mut self) -> std::io::Result<()> {
399        self.inner.kill_for_timeout()
400    }
401
402    /// Wait for the child to exit, draining and discarding any untaken
403    /// stdout/stderr so it can't block on a full pipe. On WSLC, it also closes
404    /// a stdin the caller did not take, so the child reads end-of-file.
405    ///
406    /// Returns [`WaitResult::Exited`] with the exit code, or
407    /// [`WaitResult::TimedOut`] if the request's `scriptTimeout` elapsed. `Err`
408    /// is reserved for an actual OS / wait failure.
409    pub fn wait(&mut self) -> std::io::Result<WaitResult> {
410        match self.inner.wait() {
411            Ok(code) => Ok(WaitResult::Exited(code)),
412            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => Ok(WaitResult::TimedOut),
413            Err(e) => Err(e),
414        }
415    }
416
417    /// Wait for the child to finish while preserving structured backend failures.
418    pub fn wait_detailed(&mut self) -> Result<WaitResult, Error> {
419        match self.inner.wait() {
420            Ok(code) => Ok(WaitResult::Exited(code)),
421            Err(error) if error.kind() == std::io::ErrorKind::TimedOut => Ok(WaitResult::TimedOut),
422            Err(error) => Err(detailed_wait_error(
423                error,
424                "waiting for the sandbox process failed",
425            )),
426        }
427    }
428
429    /// Wait for the child to exit, capturing its stdout and stderr.
430    ///
431    /// The safe alternative to [`take_stdout`](Self::take_stdout) +
432    /// [`take_stderr`](Self::take_stderr): it drains both streams **concurrently**
433    /// on separate threads, so an output-heavy child can't deadlock (reading one
434    /// stream to EOF before the other can). Consumes the handle.
435    ///
436    /// `Err` reports an OS / wait or output-read failure; a timeout is reported
437    /// as [`ExecutionResult`] with `outcome: WaitResult::TimedOut` and whatever each
438    /// stream captured before cancellation. Timeout and wait failures cancel
439    /// outstanding reads so descendants retaining pipe ends cannot block capture.
440    pub fn wait_with_output(self) -> std::io::Result<ExecutionResult> {
441        self.wait_with_output_impl(|process| process.wait(), |_, error| error)
442    }
443
444    /// Capture stdout and stderr while preserving structured backend wait failures.
445    pub fn wait_with_output_detailed(self) -> Result<ExecutionResult, Error> {
446        self.wait_with_output_impl(
447            |process| process.wait_detailed(),
448            |stream, error| {
449                Error::new(
450                    crate::ErrorCode::BackendError,
451                    format!("reading sandbox {stream} failed: {error}"),
452                )
453            },
454        )
455    }
456
457    fn wait_with_output_impl<E>(
458        mut self,
459        wait: impl FnOnce(&mut Self) -> Result<WaitResult, E>,
460        map_output_error: impl Fn(&str, std::io::Error) -> E,
461    ) -> Result<ExecutionResult, E> {
462        fn capture(
463            stream: Option<Box<dyn Read + Send>>,
464        ) -> std::thread::JoinHandle<std::io::Result<Vec<u8>>> {
465            std::thread::spawn(move || {
466                let mut buf = Vec::new();
467                if let Some(mut stream) = stream {
468                    stream.read_to_end(&mut buf)?;
469                }
470                Ok(buf)
471            })
472        }
473
474        // Take both streams before waiting so `wait` won't discard them, and
475        // read each on its own thread so the child never blocks on a full pipe.
476        let stdout_closer = self.stdout_closer();
477        let stderr_closer = self.stderr_closer();
478        let stdout = capture(self.inner.take_stdout());
479        let stderr = capture(self.inner.take_stderr());
480        let outcome = wait(&mut self);
481        // Sampled after the wait: a backend whose teardown runs there reports
482        // its failures here.
483        let warnings = self.inner.warnings();
484        let output_metadata = self.inner.output_metadata().cloned();
485        // Some backends keep their original pipe ends until the process object
486        // is released. Drop it before joining readers so they can observe EOF.
487        drop(self);
488        // A timed-out descendant may retain a write end even after the
489        // foreground process has exited. Stop capture rather than wait for it.
490        if !matches!(outcome, Ok(WaitResult::Exited(_))) {
491            if let Some(closer) = stdout_closer {
492                closer.close();
493            }
494            if let Some(closer) = stderr_closer {
495                closer.close();
496            }
497        }
498        let stdout = stdout
499            .join()
500            .unwrap_or_else(|_| Err(std::io::Error::other("stdout capture thread panicked")));
501        let stderr = stderr
502            .join()
503            .unwrap_or_else(|_| Err(std::io::Error::other("stderr capture thread panicked")));
504        Ok(ExecutionResult {
505            outcome: outcome?,
506            warnings,
507            stdout: stdout.map_err(|error| map_output_error("stdout", error))?,
508            stderr: stderr.map_err(|error| map_output_error("stderr", error))?,
509            output_metadata,
510        })
511    }
512}
513
514fn detailed_wait_error(error: std::io::Error, context: &str) -> Error {
515    match crate::mxc_common::mxc_error::from_io_error(&error) {
516        Some(error) => error.into(),
517        None => Error::new(
518            crate::ErrorCode::BackendError,
519            format!("{context}: {error}"),
520        ),
521    }
522}
523
524/// A live container process attached to a caller-controlled pseudo-terminal.
525pub struct MxcPtyProcess {
526    process: Arc<Mutex<Box<dyn SandboxProcess>>>,
527    reader_taken: AtomicBool,
528    writer_taken: AtomicBool,
529    reader_closers: Arc<Mutex<Vec<StreamCloser>>>,
530}
531
532impl std::fmt::Debug for MxcPtyProcess {
533    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
534        formatter
535            .debug_struct("MxcPtyProcess")
536            .field("id", &self.id())
537            .finish_non_exhaustive()
538    }
539}
540
541#[derive(Clone)]
542struct PtyReaderCloserGroup(Arc<Mutex<Vec<StreamCloser>>>);
543
544impl InnerCloser for PtyReaderCloserGroup {
545    fn close(&self) {
546        let closers = self
547            .0
548            .lock()
549            .unwrap_or_else(|poisoned| poisoned.into_inner());
550        for closer in closers.iter() {
551            closer.close();
552        }
553    }
554}
555
556impl MxcPtyProcess {
557    pub(crate) fn new(process: Box<dyn SandboxProcess>) -> Result<Self, Error> {
558        if !process.is_pty() {
559            return Err(Error::new(
560                crate::ErrorCode::BackendError,
561                "the selected backend returned a non-PTY process for a PTY spawn",
562            ));
563        }
564        Ok(Self {
565            process: Arc::new(Mutex::new(process)),
566            reader_taken: AtomicBool::new(false),
567            writer_taken: AtomicBool::new(false),
568            reader_closers: Arc::new(Mutex::new(Vec::new())),
569        })
570    }
571
572    /// The OS process id, or `0` when the backend exposes no host process id.
573    pub fn id(&self) -> u32 {
574        self.lock_process().id()
575    }
576
577    /// Warnings collected during spawn and teardown.
578    pub fn warnings(&self) -> Vec<String> {
579        self.lock_process().warnings()
580    }
581
582    /// Structured output available after terminal teardown completes.
583    pub fn output_metadata(&self) -> Option<ExecutionMetadata> {
584        self.lock_process().output_metadata().cloned()
585    }
586
587    /// Non-blocking exit check.
588    pub fn try_wait(&self) -> std::io::Result<Option<i32>> {
589        self.lock_process().try_wait()
590    }
591
592    /// Kill the container process tree.
593    pub fn kill(&self) -> std::io::Result<()> {
594        self.lock_process().kill()
595    }
596
597    /// Mark the process timed out and kill it using the backend's timeout path.
598    pub fn kill_for_timeout(&self) -> std::io::Result<()> {
599        self.lock_process().kill_for_timeout()
600    }
601
602    /// Wait for the container process to exit, draining untaken terminal output.
603    ///
604    /// Untaken input requests canonical-mode terminal EOF. Raw-mode applications
605    /// must use their own completion protocol. Output draining is cancelled after
606    /// the foreground process exits so descendants cannot keep this call waiting.
607    pub fn wait(&self) -> std::io::Result<WaitResult> {
608        if !self.writer_taken.load(Ordering::Acquire) {
609            drop(self.take_writer()?);
610        }
611        let output_drain = if self.reader_taken.load(Ordering::Acquire) {
612            None
613        } else {
614            let (mut reader, closer) = self.clone_reader_with_closer()?;
615            Some((
616                std::thread::spawn(move || {
617                    let _ = std::io::copy(&mut reader, &mut std::io::sink());
618                }),
619                closer,
620            ))
621        };
622
623        loop {
624            let terminal = match self.lock_process().try_wait() {
625                Ok(Some(_)) => true,
626                Ok(None) => false,
627                Err(error) if error.kind() == std::io::ErrorKind::TimedOut => true,
628                Err(error) => return Err(error),
629            };
630            if terminal {
631                break;
632            }
633            std::thread::sleep(Duration::from_millis(10));
634        }
635
636        let result = match self.lock_process().wait() {
637            Ok(code) => Ok(WaitResult::Exited(code)),
638            Err(error) if error.kind() == std::io::ErrorKind::TimedOut => Ok(WaitResult::TimedOut),
639            Err(error) => Err(error),
640        };
641        if let Some((drain, closer)) = output_drain {
642            if let Some(closer) = closer {
643                closer.close();
644                let _ = drain.join();
645            } else if drain.is_finished() {
646                let _ = drain.join();
647            }
648        }
649        result
650    }
651
652    /// Clone a reader for the PTY's merged output stream.
653    pub fn try_clone_reader(&self) -> std::io::Result<Box<dyn Read + Send>> {
654        let (reader, closer) = self.clone_reader_with_closer()?;
655        if let Some(closer) = closer {
656            self.reader_closers
657                .lock()
658                .unwrap_or_else(|poisoned| poisoned.into_inner())
659                .push(closer);
660        }
661        self.reader_taken.store(true, Ordering::Release);
662        Ok(reader)
663    }
664
665    /// A closer that unblocks reads from cloned PTY output readers.
666    pub fn stdout_closer(&self) -> Option<StreamCloser> {
667        if self
668            .reader_closers
669            .lock()
670            .unwrap_or_else(|poisoned| poisoned.into_inner())
671            .is_empty()
672        {
673            return None;
674        }
675        Some(StreamCloser::new(Box::new(PtyReaderCloserGroup(
676            Arc::clone(&self.reader_closers),
677        ))))
678    }
679
680    /// Take the PTY input writer. This may succeed only once.
681    pub fn take_writer(&self) -> std::io::Result<Box<dyn Write + Send>> {
682        let writer = self.lock_process().pty_take_writer()?;
683        self.writer_taken.store(true, Ordering::Release);
684        Ok(writer)
685    }
686
687    /// Resize the PTY.
688    pub fn resize(&self, size: MxcPtySize) -> std::io::Result<()> {
689        size.validate().map_err(|error| {
690            std::io::Error::new(std::io::ErrorKind::InvalidInput, error.message)
691        })?;
692        self.lock_process().pty_resize(size.into())
693    }
694
695    /// Return the current PTY dimensions.
696    pub fn size(&self) -> std::io::Result<MxcPtySize> {
697        self.lock_process().pty_size().map(Into::into)
698    }
699
700    #[doc(hidden)]
701    pub fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
702        let stdio = self.lock_process().take_native_stdio()?;
703        if let Some(stdio) = &stdio {
704            if stdio.stdin.is_some() {
705                self.writer_taken.store(true, Ordering::Release);
706            }
707            if stdio.stdout.is_some() {
708                self.reader_taken.store(true, Ordering::Release);
709            }
710        }
711        Ok(stdio)
712    }
713
714    fn lock_process(&self) -> std::sync::MutexGuard<'_, Box<dyn SandboxProcess>> {
715        self.process
716            .lock()
717            .unwrap_or_else(|poisoned| poisoned.into_inner())
718    }
719
720    fn clone_reader_with_closer(
721        &self,
722    ) -> std::io::Result<(Box<dyn Read + Send>, Option<StreamCloser>)> {
723        let (reader, closer) = self.lock_process().pty_clone_reader_with_closer()?;
724        Ok((reader, closer.map(StreamCloser::new)))
725    }
726}
727
728/// Dimensions of an [`MxcPtyProcess`].
729#[derive(Clone, Copy, Debug, Eq, PartialEq)]
730pub struct MxcPtySize {
731    pub rows: u16,
732    pub cols: u16,
733    pub pixel_width: u16,
734    pub pixel_height: u16,
735}
736
737impl MxcPtySize {
738    /// Validate dimensions against the supported PTY backend range.
739    pub fn validate(self) -> Result<(), Error> {
740        crate::mxc_common::sandbox_process::PtySize::from(self)
741            .validate()
742            .map_err(Error::from)
743    }
744}
745
746impl Default for MxcPtySize {
747    fn default() -> Self {
748        Self {
749            rows: 24,
750            cols: 80,
751            pixel_width: 0,
752            pixel_height: 0,
753        }
754    }
755}
756
757impl From<MxcPtySize> for crate::mxc_common::sandbox_process::PtySize {
758    fn from(size: MxcPtySize) -> Self {
759        Self {
760            rows: size.rows,
761            cols: size.cols,
762            pixel_width: size.pixel_width,
763            pixel_height: size.pixel_height,
764        }
765    }
766}
767
768impl From<crate::mxc_common::sandbox_process::PtySize> for MxcPtySize {
769    fn from(size: crate::mxc_common::sandbox_process::PtySize) -> Self {
770        Self {
771            rows: size.rows,
772            cols: size.cols,
773            pixel_width: size.pixel_width,
774            pixel_height: size.pixel_height,
775        }
776    }
777}
778
779/// Closes one of a [`MxcProcess`]'s streams, unblocking a read parked on it without
780/// killing the process. Obtained from [`MxcProcess::stdout_closer`] /
781/// [`MxcProcess::stderr_closer`].
782pub struct StreamCloser {
783    inner: Box<dyn InnerCloser>,
784}
785
786impl StreamCloser {
787    fn new(inner: Box<dyn InnerCloser>) -> Self {
788        Self { inner }
789    }
790
791    /// Close the stream, making any read currently parked on it return.
792    pub fn close(&self) {
793        self.inner.close();
794    }
795}
796
797#[cfg(test)]
798mod tests {
799    use super::*;
800    use crate::mxc_common::mxc_error::{ApiFailure, MxcError};
801
802    struct FakeProcess {
803        warnings: Vec<String>,
804        wait_warning: Option<String>,
805        output_metadata: Option<ExecutionMetadata>,
806        stdout: Option<Box<dyn Read + Send>>,
807        release_output: Option<std::sync::mpsc::Sender<()>>,
808        output_closer: Option<std::sync::mpsc::Sender<()>>,
809        timed_out: bool,
810    }
811
812    impl Drop for FakeProcess {
813        fn drop(&mut self) {
814            if let Some(release) = self.release_output.take() {
815                let _ = release.send(());
816            }
817        }
818    }
819
820    struct ReleaseBoundReader {
821        release: std::sync::mpsc::Receiver<()>,
822        tail: std::io::Cursor<Vec<u8>>,
823        released: bool,
824    }
825
826    impl Read for ReleaseBoundReader {
827        fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
828            if !self.released {
829                self.release
830                    .recv_timeout(std::time::Duration::from_secs(2))
831                    .map_err(std::io::Error::other)?;
832                self.released = true;
833            }
834            self.tail.read(output)
835        }
836    }
837
838    struct OutputCloser(std::sync::mpsc::Sender<()>);
839
840    impl InnerCloser for OutputCloser {
841        fn close(&self) {
842            let _ = self.0.send(());
843        }
844    }
845
846    struct FailedReader;
847
848    impl Read for FailedReader {
849        fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
850            Err(std::io::Error::other("capture read failed"))
851        }
852    }
853
854    struct NativeOnlyFake;
855
856    struct StructuredWaitErrorFake {
857        error: MxcError,
858        stdout: Option<Box<dyn Read + Send>>,
859    }
860
861    impl SandboxProcess for NativeOnlyFake {
862        fn warnings(&self) -> Vec<String> {
863            Vec::new()
864        }
865
866        fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>> {
867            panic!("individual stdin must not be delegated after native transfer")
868        }
869
870        fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>> {
871            panic!("individual stdout must not be delegated after native transfer")
872        }
873
874        fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>> {
875            panic!("individual stderr must not be delegated after native transfer")
876        }
877
878        fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
879            Ok(Some(NativeStdio {
880                stdin: None,
881                stdout: None,
882                stderr: None,
883            }))
884        }
885
886        fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
887            Ok(Some(0))
888        }
889
890        fn id(&self) -> u32 {
891            1
892        }
893
894        fn kill(&mut self) -> std::io::Result<()> {
895            Ok(())
896        }
897
898        fn wait(&mut self) -> std::io::Result<i32> {
899            Ok(0)
900        }
901    }
902
903    impl SandboxProcess for FakeProcess {
904        fn warnings(&self) -> Vec<String> {
905            self.warnings.clone()
906        }
907
908        fn output_metadata(&self) -> Option<&ExecutionMetadata> {
909            self.output_metadata.as_ref()
910        }
911
912        fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>> {
913            None
914        }
915
916        fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>> {
917            self.stdout.take()
918        }
919
920        fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>> {
921            None
922        }
923
924        fn stdout_closer(&self) -> Option<Box<dyn InnerCloser>> {
925            self.output_closer
926                .as_ref()
927                .map(|sender| Box::new(OutputCloser(sender.clone())) as Box<dyn InnerCloser>)
928        }
929
930        fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
931            panic!("native stdio must not be delegated after taking a stream")
932        }
933
934        fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
935            Ok(Some(0))
936        }
937
938        fn id(&self) -> u32 {
939            1
940        }
941
942        fn kill(&mut self) -> std::io::Result<()> {
943            Ok(())
944        }
945
946        fn wait(&mut self) -> std::io::Result<i32> {
947            if let Some(warning) = self.wait_warning.take() {
948                self.warnings.push(warning);
949            }
950            if self.timed_out {
951                return Err(std::io::Error::new(
952                    std::io::ErrorKind::TimedOut,
953                    "workload timed out",
954                ));
955            }
956            Ok(0)
957        }
958    }
959
960    impl SandboxProcess for StructuredWaitErrorFake {
961        fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>> {
962            None
963        }
964
965        fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>> {
966            self.stdout.take()
967        }
968
969        fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>> {
970            None
971        }
972
973        fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
974            Err(crate::mxc_common::mxc_error::into_io_error(
975                self.error.clone(),
976            ))
977        }
978
979        fn id(&self) -> u32 {
980            1
981        }
982
983        fn kill(&mut self) -> std::io::Result<()> {
984            Ok(())
985        }
986
987        fn wait(&mut self) -> std::io::Result<i32> {
988            Err(crate::mxc_common::mxc_error::into_io_error(
989                self.error.clone(),
990            ))
991        }
992    }
993
994    fn structured_wait_error() -> MxcError {
995        MxcError::backend_unavailable("the process status is unavailable")
996            .with_details(serde_json::json!({"phase": "wait"}))
997            .with_api_failure(
998                ApiFailure::new("WslcGetProcessExitCode").with_native_code("0x80004005"),
999            )
1000            .with_remediation("Retry the process wait.")
1001    }
1002
1003    #[test]
1004    fn sandbox_and_output_expose_security_warnings() {
1005        let warning = "permissive mode weakens containment".to_string();
1006        let wait_warning = "telemetry emission failed".to_string();
1007        let sandbox = MxcProcess::new(Box::new(FakeProcess {
1008            warnings: vec![warning.clone()],
1009            wait_warning: Some(wait_warning.clone()),
1010            output_metadata: Some(ExecutionMetadata {
1011                capture_denials: Some(CaptureDenialsResult {
1012                    kind: CaptureDenialsResult::KIND.to_string(),
1013                    output_path: "denials.json".to_string(),
1014                    exit_code: 0,
1015                    total_denials: 2,
1016                    denied_resources_truncated: false,
1017                    etl_path: None,
1018                }),
1019                capture_denials_error: None,
1020            }),
1021            stdout: None,
1022            release_output: None,
1023            output_closer: None,
1024            timed_out: false,
1025        }));
1026
1027        assert_eq!(sandbox.warnings(), [warning.as_str()]);
1028
1029        let output = sandbox.wait_with_output().expect("wait succeeds");
1030        assert_eq!(output.warnings, [warning, wait_warning]);
1031        assert_eq!(
1032            output
1033                .output_metadata
1034                .unwrap()
1035                .capture_denials
1036                .unwrap()
1037                .total_denials,
1038            2
1039        );
1040    }
1041
1042    #[test]
1043    fn captured_output_releases_backend_pipe_owners_before_joining_readers() {
1044        let (release, released) = std::sync::mpsc::channel();
1045        let sandbox = MxcProcess::new(Box::new(FakeProcess {
1046            warnings: vec!["native warning".to_string()],
1047            wait_warning: Some("completion warning".to_string()),
1048            output_metadata: None,
1049            stdout: Some(Box::new(ReleaseBoundReader {
1050                release: released,
1051                tail: std::io::Cursor::new(b"buffered tail".to_vec()),
1052                released: false,
1053            })),
1054            release_output: Some(release),
1055            output_closer: None,
1056            timed_out: false,
1057        }));
1058        let output = sandbox.wait_with_output().expect("captured output");
1059        assert_eq!(output.stdout, b"buffered tail");
1060        assert_eq!(output.outcome, WaitResult::Exited(0));
1061        assert_eq!(output.warnings, ["native warning", "completion warning"]);
1062    }
1063
1064    #[test]
1065    fn captured_timeout_closes_reads_retained_by_descendants() {
1066        let (close, closed) = std::sync::mpsc::channel();
1067        let sandbox = MxcProcess::new(Box::new(FakeProcess {
1068            warnings: Vec::new(),
1069            wait_warning: None,
1070            output_metadata: None,
1071            stdout: Some(Box::new(ReleaseBoundReader {
1072                release: closed,
1073                tail: std::io::Cursor::new(Vec::new()),
1074                released: false,
1075            })),
1076            release_output: None,
1077            output_closer: Some(close),
1078            timed_out: true,
1079        }));
1080        let output = sandbox.wait_with_output().expect("timeout capture");
1081        assert_eq!(output.outcome, WaitResult::TimedOut);
1082        assert!(output.stdout.is_empty());
1083    }
1084
1085    #[test]
1086    fn captured_read_failure_is_not_returned_as_successful_output() {
1087        let sandbox = MxcProcess::new(Box::new(FakeProcess {
1088            warnings: Vec::new(),
1089            wait_warning: None,
1090            output_metadata: None,
1091            stdout: Some(Box::new(FailedReader)),
1092            release_output: None,
1093            output_closer: None,
1094            timed_out: false,
1095        }));
1096        let error = sandbox.wait_with_output().expect_err("read must fail");
1097        assert_eq!(error.to_string(), "capture read failed");
1098    }
1099
1100    #[test]
1101    fn detailed_wait_methods_preserve_structured_backend_errors() {
1102        let expected = Error::from(structured_wait_error());
1103        let mut process = MxcProcess::new(Box::new(StructuredWaitErrorFake {
1104            error: structured_wait_error(),
1105            stdout: None,
1106        }));
1107
1108        assert_eq!(
1109            process
1110                .try_wait_detailed()
1111                .expect_err("polling must preserve the failure"),
1112            expected
1113        );
1114        assert_eq!(
1115            process
1116                .wait_detailed()
1117                .expect_err("waiting must preserve the failure"),
1118            expected
1119        );
1120
1121        let legacy = process.wait().expect_err("legacy wait still fails");
1122        assert_eq!(legacy.kind(), std::io::ErrorKind::Other);
1123        assert_eq!(legacy.to_string(), expected.message);
1124    }
1125
1126    #[test]
1127    fn detailed_capture_prefers_the_wait_failure_over_a_read_failure() {
1128        let expected = Error::from(structured_wait_error());
1129        let process = MxcProcess::new(Box::new(StructuredWaitErrorFake {
1130            error: structured_wait_error(),
1131            stdout: Some(Box::new(FailedReader)),
1132        }));
1133
1134        assert_eq!(
1135            process
1136                .wait_with_output_detailed()
1137                .expect_err("the structured wait failure wins"),
1138            expected
1139        );
1140    }
1141
1142    #[test]
1143    fn detailed_capture_contextualizes_output_read_failures() {
1144        let process = MxcProcess::new(Box::new(FakeProcess {
1145            warnings: Vec::new(),
1146            wait_warning: None,
1147            output_metadata: None,
1148            stdout: Some(Box::new(FailedReader)),
1149            release_output: None,
1150            output_closer: None,
1151            timed_out: false,
1152        }));
1153
1154        let error = process
1155            .wait_with_output_detailed()
1156            .expect_err("read must fail");
1157
1158        assert_eq!(error.code, crate::ErrorCode::BackendError);
1159        assert_eq!(
1160            error.message,
1161            "reading sandbox stdout failed: capture read failed"
1162        );
1163    }
1164
1165    #[test]
1166    fn native_stdio_is_rejected_after_an_individual_stream_is_taken() {
1167        let mut sandbox = MxcProcess::new(Box::new(FakeProcess {
1168            warnings: Vec::new(),
1169            wait_warning: None,
1170            output_metadata: None,
1171            stdout: Some(Box::new(std::io::Cursor::new(Vec::<u8>::new()))),
1172            release_output: None,
1173            output_closer: None,
1174            timed_out: false,
1175        }));
1176
1177        assert!(sandbox.take_stdout().is_some());
1178        let error = sandbox
1179            .take_native_stdio()
1180            .expect_err("mixed stream ownership must be rejected");
1181
1182        assert_eq!(
1183            error.to_string(),
1184            "native stdio must be taken before taking individual streams"
1185        );
1186    }
1187
1188    #[test]
1189    fn individual_streams_are_not_delegated_after_native_stdio_is_taken() {
1190        let mut sandbox = MxcProcess::new(Box::new(NativeOnlyFake));
1191
1192        assert!(sandbox
1193            .take_native_stdio()
1194            .expect("native stdio transfer succeeds")
1195            .is_some());
1196        assert!(sandbox.take_stdin().is_none());
1197        assert!(sandbox.take_stdout().is_none());
1198        assert!(sandbox.take_stderr().is_none());
1199        assert!(sandbox
1200            .take_native_stdio()
1201            .expect("repeated native transfer is empty")
1202            .is_none());
1203    }
1204}