use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainmentBackend, ExecutionRequest, ScriptResponse};
use crate::mxc_common::mxc_error::MxcError;
use crate::mxc_common::sandbox_process::{PtySize, SandboxProcess, StdioMode};
fn ensure_host_supported() -> Result<(), MxcError> {
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
{
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
{
Err(MxcError::unsupported_containment(
"the mxc engine has no sandbox backend for this host OS \
(supported: Windows, Linux, macOS)",
))
}
}
pub fn spawn_runner(
request: &ExecutionRequest,
logger: &mut Logger,
wslc_stdin: bool,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
crate::mxc_engine::experimental::require_experimental_optin(
&request.containment,
request.experimental_enabled,
)?;
ensure_host_supported()?;
if request.dry_run {
return Err(MxcError::malformed_request(
"dry_run is not supported for streaming spawns",
));
}
crate::mxc_engine::run::log_policy_hash(request, logger);
match &request.containment {
ContainmentBackend::Seatbelt => spawn_seatbelt(request, logger),
ContainmentBackend::Bubblewrap => spawn_bubblewrap(request, logger),
ContainmentBackend::Lxc => spawn_lxc(request, logger),
ContainmentBackend::ProcessContainer => spawn_process_container(request, logger),
ContainmentBackend::Wslc => spawn_wslc(request, logger, wslc_stdin),
ContainmentBackend::IsolationSession => spawn_isolation_session(request, logger),
ContainmentBackend::MicroVm => spawn_microvm(request, logger),
ContainmentBackend::W365Agents => {
use crate::mxc_common::sandbox_process::SandboxBackend;
crate::backend_modules::W365AgentsRunner
.spawn(request, logger, StdioMode::Pipes)
.map_err(map_spawn_error)
}
other => Err(MxcError::unsupported_containment(format!(
"the mxc engine does not yet support streaming for the '{}' backend",
other.wire_name()
))),
}
}
#[cfg(all(target_os = "windows", target_arch = "x86_64", feature = "microvm"))]
fn spawn_microvm(
request: &ExecutionRequest,
logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
crate::nvx_runner::spawn_streaming(request, logger, false)
}
#[cfg(not(all(target_os = "windows", target_arch = "x86_64", feature = "microvm")))]
fn spawn_microvm(
_request: &ExecutionRequest,
_logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"the mxc engine does not yet support streaming for the 'microvm' backend",
))
}
pub fn spawn_pty_runner(
request: &ExecutionRequest,
logger: &mut Logger,
size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
size.validate()?;
ensure_host_supported()?;
if request.dry_run {
return Err(MxcError::malformed_request(
"dry_run is not supported for PTY spawns",
));
}
crate::mxc_engine::run::log_policy_hash(request, logger);
match &request.containment {
ContainmentBackend::IsolationSession => spawn_isolation_session_pty(request, logger, size),
ContainmentBackend::Bubblewrap => {
spawn_bubblewrap_with_stdio(request, logger, StdioMode::Pty(size))
}
ContainmentBackend::Seatbelt => {
spawn_seatbelt_with_stdio(request, logger, StdioMode::Pty(size))
}
ContainmentBackend::Lxc => spawn_lxc_with_stdio(request, logger, StdioMode::Pty(size)),
other => Err(MxcError::unsupported_containment(format!(
"the mxc engine does not yet support PTY spawning for the '{}' backend",
other.wire_name()
))),
}
}
pub fn spawn_with_stdio_runner(
request: &ExecutionRequest,
logger: &mut Logger,
stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
let mode = match stdio {
StdioMode::Pipes => return spawn_runner(request, logger, true),
StdioMode::Pty(size) => return spawn_pty_runner(request, logger, size),
StdioMode::Inherit => "inherited-stdio",
StdioMode::MergedPipes => {
crate::mxc_engine::experimental::require_experimental_optin(
&request.containment,
request.experimental_enabled,
)?;
"merged-stdio"
}
};
ensure_host_supported()?;
if request.dry_run {
return Err(MxcError::malformed_request(format!(
"dry_run is not supported for {mode} spawns"
)));
}
crate::mxc_engine::run::log_policy_hash(request, logger);
match &request.containment {
ContainmentBackend::ProcessContainer => {
spawn_process_container_with_stdio(request, logger, stdio)
}
ContainmentBackend::Bubblewrap if stdio == StdioMode::Inherit => {
spawn_bubblewrap_with_stdio(request, logger, stdio)
}
ContainmentBackend::Seatbelt if stdio == StdioMode::Inherit => {
spawn_seatbelt_with_stdio(request, logger, stdio)
}
other => Err(MxcError::unsupported_containment(format!(
"the mxc engine does not support {mode} spawning for the '{}' backend",
other.wire_name()
))),
}
}
fn map_spawn_error(resp: ScriptResponse) -> MxcError {
resp.into_mxc_error()
}
#[cfg(target_os = "linux")]
fn spawn_bubblewrap(
request: &ExecutionRequest,
logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
spawn_bubblewrap_with_stdio(request, logger, StdioMode::Pipes)
}
#[cfg(target_os = "linux")]
fn spawn_bubblewrap_with_stdio(
request: &ExecutionRequest,
logger: &mut Logger,
stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
use crate::mxc_common::sandbox_process::SandboxBackend;
let mut runner = crate::bwrap_common::bwrap_runner::BubblewrapScriptRunner::new();
runner
.spawn(request, logger, stdio)
.map_err(map_spawn_error)
}
#[cfg(not(target_os = "linux"))]
fn spawn_bubblewrap(
_request: &ExecutionRequest,
_logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"Bubblewrap is only available on Linux",
))
}
#[cfg(not(target_os = "linux"))]
fn spawn_bubblewrap_with_stdio(
_request: &ExecutionRequest,
_logger: &mut Logger,
_stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"Bubblewrap is only available on Linux",
))
}
#[cfg(target_os = "linux")]
fn spawn_lxc(
request: &ExecutionRequest,
logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
spawn_lxc_with_stdio(request, logger, StdioMode::Pipes)
}
#[cfg(target_os = "linux")]
fn spawn_lxc_with_stdio(
request: &ExecutionRequest,
logger: &mut Logger,
stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
use crate::mxc_common::sandbox_process::SandboxBackend;
let mut runner = crate::lxc_common::lxc_runner::LxcScriptRunner::new(
&request.lxc_config,
&request.container_id,
&request.lifecycle,
);
runner
.spawn(request, logger, stdio)
.map_err(map_spawn_error)
}
#[cfg(not(target_os = "linux"))]
fn spawn_lxc(
_request: &ExecutionRequest,
_logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"LXC is only available on Linux",
))
}
#[cfg(not(target_os = "linux"))]
fn spawn_lxc_with_stdio(
_request: &ExecutionRequest,
_logger: &mut Logger,
_stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"LXC is only available on Linux",
))
}
#[cfg(target_os = "macos")]
fn spawn_seatbelt(
request: &ExecutionRequest,
logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
spawn_seatbelt_with_stdio(request, logger, StdioMode::Pipes)
}
#[cfg(target_os = "macos")]
fn spawn_seatbelt_with_stdio(
request: &ExecutionRequest,
logger: &mut Logger,
stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
use crate::mxc_common::sandbox_process::SandboxBackend;
let mut runner = crate::seatbelt_common::seatbelt_runner::SeatbeltScriptRunner::new();
runner
.spawn(request, logger, stdio)
.map_err(map_spawn_error)
}
#[cfg(not(target_os = "macos"))]
fn spawn_seatbelt(
_request: &ExecutionRequest,
_logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"Seatbelt is only available on macOS",
))
}
#[cfg(not(target_os = "macos"))]
fn spawn_seatbelt_with_stdio(
_request: &ExecutionRequest,
_logger: &mut Logger,
_stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"Seatbelt is only available on macOS",
))
}
fn spawn_process_container(
request: &ExecutionRequest,
logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
spawn_process_container_with_stdio(request, logger, StdioMode::Pipes)
}
#[cfg(target_os = "windows")]
fn spawn_process_container_with_stdio(
request: &ExecutionRequest,
logger: &mut Logger,
stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
use crate::mxc_common::sandbox_process::SandboxBackend;
use crate::process_container_common::base_container_runner::BaseContainerRunner;
let mut backend = BaseContainerRunner::for_request(request)?;
backend
.spawn(request, logger, stdio)
.map_err(map_spawn_error)
}
#[cfg(not(target_os = "windows"))]
fn spawn_process_container_with_stdio(
_request: &ExecutionRequest,
_logger: &mut Logger,
_stdio: StdioMode,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
Err(MxcError::unsupported_containment(
"ProcessContainer (PSEC) is only available on Windows",
))
}
#[cfg(all(target_os = "windows", feature = "wslc"))]
fn spawn_wslc(
request: &ExecutionRequest,
logger: &mut Logger,
stdin: bool,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
use crate::mxc_common::sandbox_process::{SandboxBackend, StdioMode};
let config = request.wslc.clone().unwrap_or_default();
let mut runner = if stdin {
crate::wslc_common::WSLContainerRunner::with_piped_stdin(&config)
} else {
crate::wslc_common::WSLContainerRunner::new(&config)
};
runner
.spawn(request, logger, StdioMode::Pipes)
.map_err(map_spawn_error)
}
#[cfg(not(all(target_os = "windows", feature = "wslc")))]
fn spawn_wslc(
_request: &ExecutionRequest,
_logger: &mut Logger,
_stdin: bool,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
#[cfg(target_os = "windows")]
{
Err(MxcError::unsupported_containment(
"WSLC backend not compiled. Rebuild with --features wslc.",
))
}
#[cfg(not(target_os = "windows"))]
{
Err(MxcError::unsupported_containment(
"WSLC (WSL Container) is only available on Windows",
))
}
}
#[cfg(all(target_os = "windows", feature = "isolation_session"))]
fn spawn_isolation_session(
request: &ExecutionRequest,
logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
use crate::isolation_session_common::OneShotSpawnFailure;
crate::isolation_session_common::spawn_one_shot(request, logger).map_err(|e| match e {
OneShotSpawnFailure::Refused(resp) => map_spawn_error(resp),
OneShotSpawnFailure::Launch(err) => err,
})
}
#[cfg(all(target_os = "windows", feature = "isolation_session"))]
fn spawn_isolation_session_pty(
request: &ExecutionRequest,
logger: &mut Logger,
size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
use crate::isolation_session_common::OneShotSpawnFailure;
crate::isolation_session_common::spawn_one_shot_pty(request, logger, size).map_err(
|e| match e {
OneShotSpawnFailure::Refused(resp) => map_spawn_error(resp),
OneShotSpawnFailure::Launch(err) => err,
},
)
}
#[cfg(not(all(target_os = "windows", feature = "isolation_session")))]
fn spawn_isolation_session(
_request: &ExecutionRequest,
_logger: &mut Logger,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
#[cfg(target_os = "windows")]
{
Err(MxcError::unsupported_containment(
"IsolationSession backend not compiled. Rebuild with --features isolation_session.",
))
}
#[cfg(not(target_os = "windows"))]
{
Err(MxcError::unsupported_containment(
"IsolationSession is only available on Windows",
))
}
}
#[cfg(not(all(target_os = "windows", feature = "isolation_session")))]
fn spawn_isolation_session_pty(
_request: &ExecutionRequest,
_logger: &mut Logger,
_size: PtySize,
) -> Result<Box<dyn SandboxProcess>, MxcError> {
#[cfg(target_os = "windows")]
{
Err(MxcError::unsupported_containment(
"IsolationSession backend not compiled. Rebuild with --features isolation_session.",
))
}
#[cfg(not(target_os = "windows"))]
{
Err(MxcError::unsupported_containment(
"IsolationSession is only available on Windows",
))
}
}
#[cfg(test)]
mod tests {
use super::{
ensure_host_supported, map_spawn_error, spawn_pty_runner, spawn_runner,
spawn_with_stdio_runner,
};
use crate::mxc_common::logger::{Logger, Mode};
use crate::mxc_common::models::{ContainmentBackend, ExecutionRequest};
use crate::mxc_common::mxc_error::MxcErrorCode;
use crate::mxc_common::sandbox_process::{PtySize, StdioMode};
fn minimal_request() -> ExecutionRequest {
ExecutionRequest {
script_code: "echo hello".to_string(),
..ExecutionRequest::default()
}
}
fn spawn_failure(
phase: crate::mxc_common::models::FailurePhase,
) -> crate::mxc_common::models::ScriptResponse {
crate::mxc_common::models::ScriptResponse {
error_message: "wslc rejected the request".to_string(),
failure_phase: phase,
..Default::default()
}
}
#[test]
fn rejected_phase_maps_to_policy_validation() {
use crate::mxc_common::models::FailurePhase;
let err = map_spawn_error(spawn_failure(FailurePhase::Rejected));
assert_eq!(err.code, MxcErrorCode::PolicyValidation);
assert_eq!(err.message, "wslc rejected the request");
}
#[test]
fn unavailable_and_unset_phases_keep_their_codes() {
use crate::mxc_common::models::FailurePhase;
assert_eq!(
map_spawn_error(spawn_failure(FailurePhase::BackendUnavailable)).code,
MxcErrorCode::BackendUnavailable
);
assert_eq!(
map_spawn_error(spawn_failure(FailurePhase::None)).code,
MxcErrorCode::BackendError
);
assert_eq!(
map_spawn_error(spawn_failure(FailurePhase::LaunchFailed)).code,
MxcErrorCode::BackendError
);
}
#[test]
fn streaming_rejects_dry_run() {
let mut request = minimal_request();
request.dry_run = true;
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("dry_run must be rejected"),
Err(e) => e,
};
assert_eq!(err.code, MxcErrorCode::MalformedRequest);
}
#[test]
fn streaming_rejects_unsupported_containment() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Vm;
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("Vm must be rejected"),
Err(e) => e,
};
assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
assert!(err.message.contains("vm"), "got: {}", err.message);
}
#[test]
fn pty_spawn_rejects_unsupported_containment_before_launch() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Vm;
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_pty_runner(
&request,
&mut logger,
PtySize {
rows: 24,
cols: 80,
pixel_width: 0,
pixel_height: 0,
},
) {
Ok(_) => panic!("VM PTY spawn must be rejected"),
Err(error) => error,
};
assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
assert!(err.message.contains("vm"), "got: {}", err.message);
}
#[test]
fn inherited_stdio_spawn_rejects_backends_without_inherited_stdio() {
for containment in [
ContainmentBackend::Lxc,
ContainmentBackend::Wslc,
ContainmentBackend::IsolationSession,
ContainmentBackend::Vm,
] {
let mut request = minimal_request();
request.containment = containment.clone();
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_with_stdio_runner(&request, &mut logger, StdioMode::Inherit) {
Ok(_) => panic!("{} must be rejected", containment.wire_name()),
Err(error) => error,
};
assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
assert!(
err.message.contains(containment.wire_name()),
"got: {}",
err.message
);
}
}
#[test]
fn extended_stdio_spawn_rejects_dry_run() {
let mut request = minimal_request();
request.dry_run = true;
for stdio in [StdioMode::Inherit, StdioMode::MergedPipes] {
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_with_stdio_runner(&request, &mut logger, stdio) {
Ok(_) => panic!("dry_run must be rejected"),
Err(error) => error,
};
assert_eq!(err.code, MxcErrorCode::MalformedRequest);
}
}
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
#[test]
fn host_support_ok_on_supported_platforms() {
assert!(ensure_host_supported().is_ok());
}
#[cfg(target_os = "macos")]
#[test]
fn streaming_rejects_gui_access() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Seatbelt;
request.seatbelt = Some(crate::mxc_common::models::SeatbeltConfig {
gui_access: true,
..Default::default()
});
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("guiAccess must be rejected"),
Err(e) => e,
};
assert!(err.message.contains("guiAccess"), "got: {}", err.message);
}
#[cfg(not(target_os = "windows"))]
#[test]
fn streaming_rejects_wslc_off_windows() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Wslc;
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("WSLC must be rejected off Windows"),
Err(e) => e,
};
assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
assert!(err.message.contains("Windows"), "got: {}", err.message);
}
#[cfg(all(target_os = "windows", not(feature = "wslc")))]
#[test]
fn streaming_matches_run_to_completion_for_a_backend_this_build_omits() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Wslc;
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("a backend this build omits must not spawn"),
Err(e) => e,
};
assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
}
#[cfg(not(target_os = "linux"))]
#[test]
fn streaming_rejects_lxc_off_linux() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Lxc;
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("LXC must be rejected off Linux"),
Err(e) => e,
};
assert_eq!(err.code, MxcErrorCode::UnsupportedContainment);
assert!(err.message.contains("Linux"), "got: {}", err.message);
}
#[cfg(target_os = "linux")]
#[test]
fn streaming_lxc_reaches_the_backend_on_linux() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Lxc;
request.lxc_config.distribution = String::new();
request.lxc_config.release = String::new();
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("an LXC request the backend refuses must not spawn"),
Err(e) => e,
};
assert_ne!(err.code, MxcErrorCode::UnsupportedContainment);
assert!(err.message.starts_with("LXC"), "got: {}", err.message);
}
#[cfg(all(target_os = "windows", feature = "wslc"))]
#[test]
fn streaming_wslc_without_optin_reaches_policy_validation() {
let mut request = minimal_request();
request.containment = ContainmentBackend::Wslc;
request.policy.ui_specified = true;
let mut logger = Logger::new(Mode::Buffer);
let err = match spawn_runner(&request, &mut logger, false) {
Ok(_) => panic!("WSLC must reject an unsupported UI policy"),
Err(e) => e,
};
assert_eq!(err.code, MxcErrorCode::PolicyValidation);
assert!(err.message.contains("ui section"), "got: {}", err.message);
assert!(
!err.message.contains("experimental"),
"got: {}",
err.message
);
}
}