use std::sync::Arc;
use std::time::Duration;
use crate::mxc_common::audit::{AuditEvent, AuditEventName, KillMethod, TeardownStatus};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::process_util::{OwnedHandle, PipeReadCanceller};
use crate::mxc_common::sandbox_process::StreamCloser;
use crate::mxc_common::state_aware_backend::{ExecHandle, ExecOutcome};
use crate::isolation_session_bindings::bindings::{
IsoSessionFeature, IsoSessionOps, IsoSessionProcess, IsoSessionProcessResult,
IsoSessionUserResult,
};
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, GetStdHandle, CONSOLE_MODE, STD_ERROR_HANDLE, STD_INPUT_HANDLE,
STD_OUTPUT_HANDLE,
};
use windows::Win32::System::Threading::{CreateEventW, SetEvent, WaitForSingleObject};
use windows::UI::WindowId;
use windows_core::{HSTRING, PCWSTR};
use super::console_mode::{get_local_console_size, ConsoleModeRestorer, CtrlHandlerGuard};
use super::console_relay::{create_console_relay_thread, ConsoleRelayParams};
use super::error::{
activation_error, check_result, format_iso_error, lifecycle_err, op, transport_err,
IsolationSessionError, StalePromotion,
};
use super::owned_thread::{self, Impersonation};
use super::pipe_relay::{
create_relay_thread, create_relay_thread_with_stop, drain_output_relays_within,
duplicate_handle, OutputRelayDrain, PipeRelay, PipeRelayWithStopParams,
};
use super::process_options::{
build_iso_process_options, with_service_timeout_grace, ProcessOptions,
};
const AGENT_IDENTITY_MARKER: &str = "isolation-session-agent";
#[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
}
unsafe fn create_stdin_relay(
stdin: HANDLE,
destination: HANDLE,
stop_event: HANDLE,
interactive: bool,
resize_callback: impl Fn(u16, u16) + Send + 'static,
) -> Result<(OwnedHandle, Option<PipeReadCanceller>), IsolationSessionError> {
if classify_stdin_handle(stdin) == StdinHandleKind::PipeOrFile {
let (thread, canceller) = unsafe { create_relay_thread(stdin, destination) }
.map_err(|e| lifecycle_err(format!("create stdin relay: {e}")))?
.into_thread_and_canceller();
return Ok((thread, Some(canceller)));
}
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))
}
pub(super) struct MtaReference {
cookie: CO_MTA_USAGE_COOKIE,
}
impl MtaReference {
pub(super) fn acquire() -> Result<Self, IsolationSessionError> {
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) {
unsafe {
let _ = CoDecrementMTAUsage(self.cookie);
}
}
}
unsafe impl Send for MtaReference {}
unsafe impl Sync for MtaReference {}
fn check_service_available_and_activate() -> Result<IsoSessionOps, IsolationSessionError> {
match IsoSessionOps::new() {
Ok(ops) => Ok(ops),
Err(e) => Err(activation_error(e.code().0 as u32, &e.message())),
}
}
fn feature_supported_from(level: windows_core::Result<i32>) -> bool {
matches!(level, Ok(level) if level > 0)
}
const ZERO_WINDOW_ID: WindowId = WindowId { Value: 0 };
pub(super) struct ProvisionedUser {
pub agent_user_name: String,
pub agent_user_sid: String,
pub ephemeral_workspace_path: String,
}
pub struct IsolationSessionManager {
agent_user_name: HSTRING,
ops: IsoSessionOps,
impersonation: Impersonation,
_mta: MtaReference,
}
impl IsolationSessionManager {
pub(super) fn pty_process(
&self,
options: &ProcessOptions,
logger: Option<&Logger>,
) -> Result<Arc<ClosingProcess>, IsolationSessionError> {
owned_thread::call(&self.impersonation, || {
let mta = MtaReference::acquire()?;
Ok(Arc::new(ClosingProcess::new(
self.start_process(options, logger)?,
self.impersonation.clone(),
mta,
)))
})
}
pub(super) fn new(agent_user_name: &str) -> Result<Self, IsolationSessionError> {
let impersonation = Impersonation::of_this_thread()?;
owned_thread::call(&impersonation, || {
let mta = MtaReference::acquire()?;
let ops = check_service_available_and_activate()?;
Ok(Self {
agent_user_name: HSTRING::from(agent_user_name),
ops,
impersonation: impersonation.clone(),
_mta: mta,
})
})
}
pub(super) fn add_user(
app_id: Option<&str>,
) -> Result<(ProvisionedUser, Self), IsolationSessionError> {
let impersonation = Impersonation::of_this_thread()?;
owned_thread::call(&impersonation, || {
let mta = MtaReference::acquire()?;
let ops = check_service_available_and_activate()?;
let (op_add_user, started) = if feature_supported_from(
ops.GetFeatureLevel(IsoSessionFeature::DeducedEnterpriseAgentUser),
) {
(
op::ADD_USER_DEDUCED,
ops.AddUserAsync3(&HSTRING::from(app_id.unwrap_or_default()), ZERO_WINDOW_ID),
)
} else if feature_supported_from(
ops.GetFeatureLevel(IsoSessionFeature::AppScopedRegistration),
) {
(
op::ADD_USER,
ops.AddUserAsync2(
&HSTRING::from(app_id.unwrap_or_default()),
&HSTRING::new(),
&HSTRING::new(),
),
)
} else {
(
op::ADD_USER_LEGACY,
ops.AddUserAsync(&HSTRING::new(), &HSTRING::new()),
)
};
let user_result: IsoSessionUserResult = owned_thread::wait_for(op_add_user, started)?;
let err = user_result
.Error()
.map_err(|e| transport_err(op_add_user, "get Error failed", &e))?;
let is_error = err
.IsError()
.map_err(|e| transport_err(op_add_user, "get IsError failed", &e))?;
if is_error {
return Err(format_iso_error(
op_add_user,
&err,
StalePromotion::NotEligible,
));
}
let agent_user_name = user_result
.AgentUserName()
.map_err(|e| transport_err(op_add_user, "get AgentUserName failed", &e))?;
let manager = Self {
agent_user_name: agent_user_name.clone(),
ops,
impersonation: impersonation.clone(),
_mta: mta,
};
let provisioned =
match Self::read_remaining_facts(&user_result, &agent_user_name, op_add_user) {
Ok(provisioned) => provisioned,
Err(e) => {
let _ = manager.deprovision_agent_user();
return Err(e);
}
};
Ok((provisioned, manager))
})
}
fn read_remaining_facts(
user_result: &IsoSessionUserResult,
agent_user_name: &HSTRING,
op_add_user: &'static str,
) -> Result<ProvisionedUser, IsolationSessionError> {
let agent_user_sid = user_result
.AgentUserSid()
.map_err(|e| transport_err(op_add_user, "get AgentUserSid failed", &e))?;
let ephemeral_workspace_path = user_result
.EphemeralWorkspacePath()
.map_err(|e| transport_err(op_add_user, "get EphemeralWorkspacePath failed", &e))?;
Ok(ProvisionedUser {
agent_user_name: agent_user_name.to_string(),
agent_user_sid: agent_user_sid.to_string(),
ephemeral_workspace_path: ephemeral_workspace_path.to_string(),
})
}
pub(super) fn start_session(&self) -> Result<(), IsolationSessionError> {
owned_thread::call(&self.impersonation, || {
let (op_start_session, started) = if feature_supported_from(
self.ops
.GetFeatureLevel(IsoSessionFeature::DeducedEnterpriseAgentUser),
) {
(
op::START_SESSION_DEDUCED,
self.ops
.StartSessionAsync2(&self.agent_user_name, ZERO_WINDOW_ID),
)
} else {
(
op::START_SESSION,
self.ops
.StartSessionAsync(&self.agent_user_name, &HSTRING::new()),
)
};
let result = owned_thread::wait_for(op_start_session, started)?;
check_result(&result, op_start_session, StalePromotion::Eligible)
})
}
fn start_process(
&self,
options: &ProcessOptions,
logger: Option<&Logger>,
) -> Result<StartedProcess, IsolationSessionError> {
let proc_options = build_iso_process_options(options)?;
let result: IsoSessionProcessResult = owned_thread::wait_for(
op::RUN_PROCESS,
self.ops.RunProcessWithOptionsAsync(
&self.agent_user_name,
&HSTRING::from(&options.process_path),
&HSTRING::from(&options.arguments),
&proc_options,
),
)?;
let err = result
.Error()
.map_err(|e| transport_err(op::RUN_PROCESS, "get Error failed", &e))?;
let is_error = err
.IsError()
.map_err(|e| transport_err(op::RUN_PROCESS, "get IsError failed", &e))?;
if is_error {
return Err(format_iso_error(
op::RUN_PROCESS,
&err,
StalePromotion::Eligible,
));
}
let process: IsoSessionProcess = result
.Process()
.map_err(|e| transport_err(op::RUN_PROCESS, "get Process failed", &e))?;
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(StartedProcess {
process,
stdout,
stderr,
stdin,
identity: AGENT_IDENTITY_MARKER,
audit_logger: std::sync::Mutex::new(
logger
.map(Logger::clone_diagnostic_sink)
.unwrap_or_else(Logger::inherit_thread_diagnostic_sink),
),
})
}
pub(super) fn create_process(
&self,
options: &ProcessOptions,
logger: Option<&mut Logger>,
) -> Result<ExecOutcome, IsolationSessionError> {
owned_thread::call(&self.impersonation, || {
let wxc_stdout = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }
.map_err(|e| lifecycle_err(format!("GetStdHandle(stdout) failed: {}", e)))?;
let wxc_stderr = unsafe { GetStdHandle(STD_ERROR_HANDLE) }
.map_err(|e| lifecycle_err(format!("GetStdHandle(stderr) failed: {}", e)))?;
let wxc_stdin = unsafe { GetStdHandle(STD_INPUT_HANDLE) }
.map_err(|e| lifecycle_err(format!("GetStdHandle(stdin) failed: {}", e)))?;
let stdin_stop_event = unsafe {
CreateEventW(None, true, false, PCWSTR::null())
.map_err(|e| lifecycle_err(format!("CreateEventW(stdin stop): {}", e)))?
};
let stdin_stop_owned = OwnedHandle::new(stdin_stop_event);
let service_options = with_service_timeout_grace(options.clone());
let started = self.start_process(&service_options, logger.as_deref())?;
let process = &started.process;
let stdout_handle_val = started.stdout;
let stderr_handle_val = started.stderr;
let stdin_handle_val = started.stdin;
let mut scope = RelayScope::new(process, stdin_stop_owned.get());
let _console_guard = if options.interactive {
Some(ConsoleModeRestorer::install_raw_vt())
} else {
None
};
let _ctrl_guard = if options.interactive {
Some(CtrlHandlerGuard::install(stdin_stop_owned.get()))
} else {
None
};
if options.interactive {
if let Some((cols, rows)) = get_local_console_size() {
let _ = process.ResizeConsole(cols, rows);
}
}
scope.stdout = if stdout_handle_val != 0 {
Some(
unsafe {
create_relay_thread(
HANDLE(stdout_handle_val as *mut core::ffi::c_void),
wxc_stdout,
)
}
.map_err(|e| lifecycle_err(format!("create stdout relay: {}", e)))?,
)
} else {
None
};
scope.stderr = if stderr_handle_val != 0 {
Some(
unsafe {
create_relay_thread(
HANDLE(stderr_handle_val as *mut core::ffi::c_void),
wxc_stderr,
)
}
.map_err(|e| lifecycle_err(format!("create stderr relay: {}", e)))?,
)
} else {
None
};
if stdin_handle_val != 0 {
let process_for_resize = process.clone();
let impersonation = self.impersonation.clone();
let (thread, canceller) = unsafe {
create_stdin_relay(
wxc_stdin,
HANDLE(stdin_handle_val as *mut core::ffi::c_void),
stdin_stop_owned.get(),
options.interactive,
move |cols, rows| {
let _ = owned_thread::call(&impersonation, || {
let _ = process_for_resize.ResizeConsole(cols, rows);
Ok(())
});
},
)
}?;
scope.stdin = Some(thread);
scope.stdin_canceller = canceller;
}
let outcome = started.wait(options.timeout_ms, || scope.stop_stdin())?;
scope.finish()?;
Ok(outcome)
})
}
pub(super) fn piped_exec_handle(
&self,
options: &ProcessOptions,
timeout_ms: u32,
logger: Option<&Logger>,
) -> Result<ExecHandle, IsolationSessionError> {
let started = owned_thread::call(&self.impersonation, || {
let mta = MtaReference::acquire()?;
Ok(Arc::new(ClosingProcess::new(
self.start_process(options, logger)?,
self.impersonation.clone(),
mta,
)))
})?;
let stdout = HANDLE(started.stdout as *mut std::ffi::c_void);
let stderr = HANDLE(started.stderr as *mut std::ffi::c_void);
let stdin = HANDLE(started.stdin as *mut std::ffi::c_void);
let waiter_process = Arc::clone(&started);
let stdin_process = Arc::clone(&started);
Ok(ExecHandle {
stdout,
stderr,
stdin,
stdin_closer: Some(Box::new(move || {
let _ = owned_thread::call(&stdin_process.impersonation, || {
let _ = stdin_process.process.CloseStandardInput();
Ok(())
});
})),
waiter: Box::new(move || {
owned_thread::call(&waiter_process.impersonation, || {
waiter_process.wait(timeout_ms, || Ok(true))
})
.map_err(super::error::map_lifecycle_error)
}),
terminator: Box::new(move || {
owned_thread::call(&started.impersonation, || started.terminate())
.map_err(super::error::map_lifecycle_error)
}),
})
}
pub(super) fn stop_session(&self) -> Result<(), IsolationSessionError> {
owned_thread::call(&self.impersonation, || {
let result = owned_thread::wait_for(
op::STOP_SESSION,
self.ops.StopSessionAsync(&self.agent_user_name),
)?;
check_result(&result, op::STOP_SESSION, StalePromotion::Eligible)
})
}
pub(super) fn deprovision_agent_user(&self) -> Result<(), IsolationSessionError> {
owned_thread::call(&self.impersonation, || {
let result = owned_thread::wait_for(
op::REMOVE_USER,
self.ops.RemoveUserAsync(&self.agent_user_name),
)?;
check_result(&result, op::REMOVE_USER, StalePromotion::Eligible)
})
}
}
#[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) struct StartedProcess {
pub(super) process: IsoSessionProcess,
pub(super) stdout: u64,
pub(super) stderr: u64,
pub(super) stdin: u64,
identity: &'static str,
audit_logger: std::sync::Mutex<Logger>,
}
impl StartedProcess {
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.process, 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",
))
}
}
struct RelayScope<'a> {
process: &'a IsoSessionProcess,
stop_event: HANDLE,
stdout: Option<PipeRelay>,
stderr: Option<PipeRelay>,
stdin: Option<OwnedHandle>,
stdin_canceller: Option<PipeReadCanceller>,
finished: bool,
}
impl<'a> RelayScope<'a> {
const JOIN_MS: u32 = 1000;
const IDLE_MS: u64 = 5000;
const ABSOLUTE_CAP_MS: u64 = 60_000;
fn new(process: &'a IsoSessionProcess, stop_event: HANDLE) -> Self {
Self {
process,
stop_event,
stdout: None,
stderr: None,
stdin: None,
stdin_canceller: None,
finished: false,
}
}
fn signal_stop(&self) {
unsafe {
let _ = SetEvent(self.stop_event);
}
}
fn cancel_stdin_read(&self) {
if let Some(canceller) = &self.stdin_canceller {
canceller.close();
}
}
fn join(relay: Option<&OwnedHandle>, timeout_ms: u32) -> bool {
wait_for_relay(relay, timeout_ms).unwrap_or(false)
}
fn join_output(relay: &Option<PipeRelay>, timeout_ms: u32) -> bool {
Self::join(relay.as_ref().map(PipeRelay::thread), timeout_ms)
}
fn output_relays(&self) -> Vec<&PipeRelay> {
[&self.stdout, &self.stderr]
.into_iter()
.filter_map(Option::as_ref)
.collect()
}
fn close_handles(&self) {
let _ = self.process.Close();
}
fn stop_stdin(&mut self) -> Result<bool, IsolationSessionError> {
self.signal_stop();
self.cancel_stdin_read();
let exited = wait_for_relay(self.stdin.as_ref(), Self::JOIN_MS)?;
if exited {
self.stdin = None;
self.stdin_canceller = None;
}
Ok(exited)
}
fn finish(&mut self) -> Result<(), IsolationSessionError> {
self.signal_stop();
self.cancel_stdin_read();
let output_relays = self.output_relays();
let output_drain = drain_output_relays_within(
&output_relays,
Duration::from_millis(Self::IDLE_MS),
Duration::from_millis(Self::ABSOLUTE_CAP_MS),
)
.map_err(|error| lifecycle_err(format!("drain output relays: {error}")))?;
if output_drain == OutputRelayDrain::GaveUp {
Self::join_output(&self.stdout, Self::JOIN_MS);
Self::join_output(&self.stderr, Self::JOIN_MS);
}
Self::join(self.stdin.as_ref(), Self::JOIN_MS);
self.close_handles();
self.finished = true;
Ok(())
}
}
impl Drop for RelayScope<'_> {
fn drop(&mut self) {
if self.finished {
return;
}
self.signal_stop();
self.cancel_stdin_read();
for relay in self.output_relays() {
relay.cancel_read();
}
let _ = self.process.Terminate();
Self::join_output(&self.stdout, Self::JOIN_MS);
Self::join_output(&self.stderr, Self::JOIN_MS);
Self::join(self.stdin.as_ref(), Self::JOIN_MS);
self.close_handles();
}
}
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_for_relay(
relay: Option<&OwnedHandle>,
timeout_ms: u32,
) -> Result<bool, IsolationSessionError> {
let Some(relay) = relay else {
return Ok(true);
};
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()
))),
}
}
fn wait_with_graceful_shutdown(
process: &IsoSessionProcess,
stdin_released: bool,
) -> Result<(i32, Option<i32>), IsolationSessionError> {
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 _ = 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::*;
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 in [true, 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 (relay, canceller) = unsafe {
create_stdin_relay(
source_read.get(),
dest_write.get(),
stop.get(),
interactive,
|_, _| 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());
canceller
.expect("pipe input must have a read canceller")
.close();
assert!(wait_for_relay(Some(&relay), 5000).unwrap());
assert_eq!(received, payload);
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 (relay, canceller) = unsafe {
create_stdin_relay(
HANDLE(input.as_raw_handle()),
dest_write.get(),
stop.get(),
interactive,
|_, _| 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);
}
}
#[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() {
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 (relay, canceller) = unsafe {
create_stdin_relay(
console.get(),
dest_write.get(),
stop.get(),
interactive,
|_, _| {},
)
}
.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());
}
}
#[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 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)
));
}
#[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""#));
}
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"
);
}
#[test]
fn feature_unavailable_returns_clean_error() {
let _ = unsafe {
windows::Win32::System::Com::CoInitializeEx(
None,
windows::Win32::System::Com::COINIT_MULTITHREADED,
)
};
match check_service_available_and_activate() {
Ok(_ops) => {
}
Err(IsolationSessionError::ServiceUnavailable(failure)) => {
assert!(
failure.message.contains("not available")
|| failure.message.contains("activation failed"),
"Expected descriptive error message, got: {}",
failure.message
);
assert_eq!(failure.operation, op::ACTIVATE);
assert!(
failure.code.is_some(),
"activation failure carries no HRESULT"
);
}
Err(other) => {
panic!("expected ServiceUnavailable variant, got: {:?}", other);
}
}
}
#[test]
fn feature_support_requires_a_positive_feature_level() {
assert!(feature_supported_from(Ok(1)));
assert!(feature_supported_from(Ok(7)));
assert!(!feature_supported_from(Ok(0)));
assert!(!feature_supported_from(Ok(-1)));
assert!(!feature_supported_from(Err(
windows_core::Error::from_hresult(
windows_core::HRESULT(0x8007_0057u32 as i32), )
)));
}
}