use super::error::{lifecycle_err, op, transport_err, IsolationSessionError};
use super::manager::MtaReference;
use super::owned_thread::{self, Impersonation};
use crate::isolation_session_bindings::bindings::IsoSessionProcess;
use crate::mxc_common::audit::{AuditEvent, AuditEventName, KillMethod};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::state_aware_backend::ExecOutcome;
use std::sync::{Arc, Mutex, PoisonError};
pub(super) struct StartedProcess {
pub(super) process: IsoSessionProcess,
pub(super) close_lock: Arc<Mutex<()>>,
pub(super) stdout: u64,
pub(super) stderr: u64,
pub(super) stdin: u64,
identity: &'static str,
audit_logger: Mutex<Logger>,
}
impl StartedProcess {
pub(super) fn new(
process: IsoSessionProcess,
identity: &'static str,
logger: Option<&Logger>,
) -> Result<Self, IsolationSessionError> {
let stdout = process
.OutputHandle()
.map_err(|e| transport_err(op::RUN_PROCESS, "get OutputHandle failed", &e))?;
let stderr = process
.ErrorHandle()
.map_err(|e| transport_err(op::RUN_PROCESS, "get ErrorHandle failed", &e))?;
let stdin = process
.InputHandle()
.map_err(|e| transport_err(op::RUN_PROCESS, "get InputHandle failed", &e))?;
Ok(Self {
process,
close_lock: Arc::new(Mutex::new(())),
stdout,
stderr,
stdin,
identity,
audit_logger: Mutex::new(
logger
.map(Logger::clone_diagnostic_sink)
.unwrap_or_else(Logger::inherit_thread_diagnostic_sink),
),
})
}
fn audit(&self, name: AuditEventName) -> AuditEvent {
AuditEvent::new(name)
.str("backend", "isolation_session")
.str("identity", self.identity)
.u64("pid", 0)
}
fn record_exited(&self, exit_code: i32) {
crate::mxc_common::telemetry::log_process_event(
self.identity,
0,
crate::mxc_common::telemetry::ProcessEvent::Exited(exit_code),
);
let mut logger = self.audit_logger.lock().unwrap_or_else(|e| e.into_inner());
logger.log_audit_event(
&self
.audit(AuditEventName::ProcessExited)
.i64("exit_code", exit_code as i64),
);
}
fn record_timed_out(&self, timeout_ms: u32) {
crate::mxc_common::telemetry::log_process_event(
self.identity,
0,
crate::mxc_common::telemetry::ProcessEvent::TimedOut(timeout_ms as u64),
);
let mut logger = self.audit_logger.lock().unwrap_or_else(|e| e.into_inner());
logger.log_audit_event(
&self
.audit(AuditEventName::ProcessTimedOut)
.u64("timeout_ms", timeout_ms as u64),
);
}
fn record_kill_failed(&self, error_code: i32) {
crate::mxc_common::telemetry::log_process_event(
self.identity,
0,
crate::mxc_common::telemetry::ProcessEvent::KillFailed(
KillMethod::TerminateProcess.as_str(),
error_code,
),
);
let mut logger = self.audit_logger.lock().unwrap_or_else(|e| e.into_inner());
logger.log_audit_event(
&self
.audit(AuditEventName::ProcessKillFailed)
.str("kill_method", KillMethod::TerminateProcess.as_str())
.i64("error_code", error_code as i64),
);
}
pub(super) fn wait(
&self,
timeout_ms: u32,
before_shutdown: impl FnOnce() -> Result<bool, IsolationSessionError>,
) -> Result<ExecOutcome, IsolationSessionError> {
let waited = self
.process
.WaitForExit(timeout_ms)
.map_err(|e| transport_err(op::RUN_PROCESS, "WaitForExit failed", &e))?;
let plan = plan_wait(timeout_ms, waited, || {
self.process
.ExitCode()
.map_err(|e| transport_err(op::RUN_PROCESS, "get ExitCode failed", &e))
})?;
match plan {
WaitPlan::Exited(exit_code) => {
self.record_exited(exit_code);
return Ok(ExecOutcome::Exited(exit_code));
}
WaitPlan::TimedOutAfterDeadline => {
self.record_timed_out(timeout_ms);
return Ok(ExecOutcome::TimedOut);
}
WaitPlan::KillThenReportTimeout => {}
}
self.record_timed_out(timeout_ms);
let stdin_released = before_shutdown()?;
let (_, terminate_error) = wait_with_graceful_shutdown(self, stdin_released)?;
if let Some(error_code) = terminate_error {
self.record_kill_failed(error_code);
}
let after = self
.process
.ExitCode()
.map_err(|e| transport_err(op::RUN_PROCESS, "get ExitCode failed", &e))?;
if after == STILL_ACTIVE {
return Err(lifecycle_err(
"the sandboxed process was still running after timeout shutdown; \
it timed out but could not be confirmed killed",
));
}
Ok(ExecOutcome::TimedOut)
}
pub(super) fn terminate(&self) -> Result<(), IsolationSessionError> {
if let Err(error) = self.process.Terminate() {
self.record_kill_failed(error.code().0);
return Err(transport_err(op::RUN_PROCESS, "Terminate failed", &error));
}
let _ = self.process.WaitForExit(TERMINATE_WAIT_MS);
Ok(())
}
fn terminate_and_confirm(&self) -> Result<(), IsolationSessionError> {
let termination_error = self.process.Terminate().err();
if let Some(error) = &termination_error {
self.record_kill_failed(error.code().0);
}
let waited = self
.process
.WaitForExit(TERMINATE_WAIT_MS)
.map_err(|error| transport_err(op::RUN_PROCESS, "WaitForExit failed", &error))?;
let exit_code =
if waited == WAIT_FOR_EXIT_TIMEOUT {
Some(self.process.ExitCode().map_err(|error| {
transport_err(op::RUN_PROCESS, "get ExitCode failed", &error)
})?)
} else {
None
};
if termination_is_confirmed(waited, exit_code) {
return Ok(());
}
if let Some(error) = termination_error {
return Err(transport_err(op::RUN_PROCESS, "Terminate failed", &error));
}
Err(lifecycle_err(
"the sandboxed process was still running after the bounded terminate wait",
))
}
}
pub(super) struct ClosingProcess {
started: StartedProcess,
impersonation: Impersonation,
_mta: MtaReference,
}
impl ClosingProcess {
pub(super) fn new(
started: StartedProcess,
impersonation: Impersonation,
mta: MtaReference,
) -> Self {
Self {
started,
impersonation,
_mta: mta,
}
}
pub(super) fn resize_console(
&self,
columns: u16,
rows: u16,
) -> Result<(), IsolationSessionError> {
owned_thread::call(&self.impersonation, || {
self.process
.ResizeConsole(columns, rows)
.map_err(|error| lifecycle_err(format!("ResizeConsole failed: {error}")))
})
}
pub(super) fn close_standard_input(&self) -> Result<(), IsolationSessionError> {
owned_thread::call(&self.impersonation, || {
self.process
.CloseStandardInput()
.map_err(|error| lifecycle_err(format!("CloseStandardInput failed: {error}")))
})
}
pub(super) fn wait_for_exit(
&self,
timeout_ms: u32,
) -> Result<ExecOutcome, IsolationSessionError> {
owned_thread::call(&self.impersonation, || self.wait(timeout_ms, || Ok(true)))
}
pub(super) fn terminate_process(&self) -> Result<(), IsolationSessionError> {
owned_thread::call(&self.impersonation, || self.terminate())
}
pub(super) fn terminate_and_confirm_process(&self) -> Result<(), IsolationSessionError> {
owned_thread::call(&self.impersonation, || self.terminate_and_confirm())
}
}
impl std::ops::Deref for ClosingProcess {
type Target = StartedProcess;
fn deref(&self) -> &Self::Target {
&self.started
}
}
impl Drop for ClosingProcess {
fn drop(&mut self) {
let process = &self.started.process;
let _ = owned_thread::call(&self.impersonation, || {
let _ = process.Close();
Ok(())
});
}
}
const STILL_ACTIVE: i32 = windows::Win32::Foundation::STATUS_PENDING.0;
pub(super) const WAIT_FOR_EXIT_TIMEOUT: i32 = -1;
const TERMINATE_WAIT_MS: u32 = 5_000;
fn termination_is_confirmed(waited: i32, exit_code: Option<i32>) -> bool {
waited != WAIT_FOR_EXIT_TIMEOUT || exit_code.is_some_and(|code| code != STILL_ACTIVE)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum WaitPlan {
Exited(i32),
KillThenReportTimeout,
TimedOutAfterDeadline,
}
fn plan_wait(
timeout_ms: u32,
waited: i32,
exit_code: impl FnOnce() -> Result<i32, IsolationSessionError>,
) -> Result<WaitPlan, IsolationSessionError> {
if timeout_ms == 0 || waited != WAIT_FOR_EXIT_TIMEOUT {
return Ok(WaitPlan::Exited(waited));
}
let code = exit_code()?;
match code {
STILL_ACTIVE => Ok(WaitPlan::KillThenReportTimeout),
WAIT_FOR_EXIT_TIMEOUT => Ok(WaitPlan::Exited(WAIT_FOR_EXIT_TIMEOUT)),
_ => Ok(WaitPlan::TimedOutAfterDeadline),
}
}
fn wait_with_graceful_shutdown(
started: &StartedProcess,
stdin_released: bool,
) -> Result<(i32, Option<i32>), IsolationSessionError> {
let process = &started.process;
let mut exit_code = process
.ExitCode()
.map_err(|e| transport_err(op::RUN_PROCESS, "get ExitCode failed", &e))?;
if exit_code != STILL_ACTIVE {
return Ok((exit_code, None));
}
if stdin_released {
{
let _close = started
.close_lock
.lock()
.unwrap_or_else(PoisonError::into_inner);
let _ = process.CloseStandardInput();
}
let _ = process.WaitForExit(5000);
exit_code = process.ExitCode().unwrap_or(STILL_ACTIVE);
if exit_code != STILL_ACTIVE {
return Ok((exit_code, None));
}
}
let _ = process.SendCtrlClose();
let _ = process.WaitForExit(3000);
exit_code = process.ExitCode().unwrap_or(STILL_ACTIVE);
if exit_code != STILL_ACTIVE {
return Ok((exit_code, None));
}
let terminate_error = process.Terminate().err().map(|error| error.code().0);
let _ = process.WaitForExit(0);
Ok((process.ExitCode().unwrap_or(-1), terminate_error))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bounded_termination_requires_confirmation_after_a_timeout_sentinel() {
assert!(termination_is_confirmed(0, None));
assert!(termination_is_confirmed(
WAIT_FOR_EXIT_TIMEOUT,
Some(WAIT_FOR_EXIT_TIMEOUT)
));
assert!(!termination_is_confirmed(
WAIT_FOR_EXIT_TIMEOUT,
Some(STILL_ACTIVE)
));
}
fn probe(value: i32) -> impl FnOnce() -> Result<i32, IsolationSessionError> {
move || Ok(value)
}
#[test]
fn timeout_needs_both_signals_not_either() {
assert_eq!(
plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(STILL_ACTIVE)).unwrap(),
WaitPlan::KillThenReportTimeout
);
assert_eq!(
plan_wait(5_000, -1, probe(-1)).unwrap(),
WaitPlan::Exited(-1)
);
assert_eq!(
plan_wait(5_000, STILL_ACTIVE, probe(STILL_ACTIVE)).unwrap(),
WaitPlan::Exited(STILL_ACTIVE)
);
assert_eq!(plan_wait(5_000, 0, probe(0)).unwrap(), WaitPlan::Exited(0));
}
#[test]
fn a_deadline_spent_before_a_late_exit_is_still_a_timeout() {
assert_eq!(
plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(7)).unwrap(),
WaitPlan::TimedOutAfterDeadline
);
assert_eq!(
plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(0)).unwrap(),
WaitPlan::TimedOutAfterDeadline,
"a clean exit past the deadline is still a missed deadline"
);
}
#[test]
fn the_sentinel_colliding_with_a_real_minus_one_exit_is_read_as_the_exit() {
assert_eq!(
plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(-1)).unwrap(),
WaitPlan::Exited(-1)
);
}
#[test]
fn infinite_timeout_can_never_be_a_timeout() {
assert_eq!(
plan_wait(0, WAIT_FOR_EXIT_TIMEOUT, probe(STILL_ACTIVE)).unwrap(),
WaitPlan::Exited(WAIT_FOR_EXIT_TIMEOUT)
);
}
#[test]
fn exit_code_is_not_queried_unless_it_could_change_the_answer() {
let calls = std::cell::Cell::new(0);
let counting = || {
calls.set(calls.get() + 1);
Ok(STILL_ACTIVE)
};
assert_eq!(plan_wait(5_000, 0, counting).unwrap(), WaitPlan::Exited(0));
assert_eq!(calls.get(), 0, "no COM round-trip for a plain exit");
}
#[test]
fn unreadable_exit_code_propagates_rather_than_guessing() {
let err = plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, || {
Err(lifecycle_err("handle is broken"))
});
assert!(
err.is_err(),
"a failed probe must not be reported as an exit"
);
}
}