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;
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"),
})
}
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> {
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)));
}
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 {}
pub(super) fn feature_supported_from(level: windows_core::Result<i32>) -> bool {
matches!(level, Ok(level) if level > 0)
}
pub(super) struct ProvisionedUser {
pub agent_user_name: String,
pub agent_user_sid: String,
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);
};
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));
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));
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() {
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));
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() {
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), )
)));
}
}