use std::path::Path;
use crate::learning_mode_windows::LearningModeError;
use crate::mxc_common::models::{ExecutionRequest, ScriptResponse};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LaunchDiagnostic {
pub kind: &'static str,
pub message: String,
}
pub const REQUIRED_CHILD_ENV_VARS: [&str; 2] = ["SYSTEMROOT", "LOCALAPPDATA"];
fn missing_required_child_env_vars(supplied_env: &[String]) -> Vec<&'static str> {
REQUIRED_CHILD_ENV_VARS
.iter()
.copied()
.filter(|required| {
!supplied_env.iter().any(|entry| {
entry
.split_once('=')
.is_some_and(|(key, _)| key.eq_ignore_ascii_case(required))
})
})
.collect()
}
fn missing_required_env_diagnostic(supplied_env: &[String]) -> Option<LaunchDiagnostic> {
let missing = missing_required_child_env_vars(supplied_env);
if missing.is_empty() {
return None;
}
let described = if supplied_env.is_empty() {
"an empty environment".to_string()
} else {
format!("an environment of {} variable(s)", supplied_env.len())
};
Some(LaunchDiagnostic {
kind: "missing_required_env",
message: format!(
"The supplied `process.env` cannot launch a Windows process container because it is \
missing the required variable(s): {}. MXC uses your `process.env` ({described}) \
verbatim when `process.inheritDefaultEnv` is false. Set \
`process.inheritDefaultEnv` to true to layer these entries on the default user \
environment. Alternatively, add the missing variable(s) to `process.env` — any \
value will do because the Windows requirement is presence-only — or omit \
`process.env` entirely to use the default user environment.",
missing.join(", ")
),
})
}
pub fn validate_required_child_env(request: &ExecutionRequest) -> Result<(), ScriptResponse> {
if request.inherit_default_env {
return Ok(());
}
let Some(supplied_env) = request.env.as_deref() else {
return Ok(());
};
let Some(diagnostic) = missing_required_env_diagnostic(supplied_env) else {
return Ok(());
};
Err(ScriptResponse::rejected(&diagnostic.message))
}
pub fn diagnose_missing_required_env(
win32_error: u32,
supplied_env: Option<&[String]>,
) -> Option<LaunchDiagnostic> {
if win32_error != ERROR_ENVVAR_NOT_FOUND.0 {
return None;
}
let supplied = supplied_env?;
missing_required_env_diagnostic(supplied)
}
pub fn diagnose_create_process_failure(win32_error: u32, command_line: &str) -> LaunchDiagnostic {
if win32_error == ERROR_ACCESS_DISABLED_BY_POLICY.0 {
return LaunchDiagnostic {
kind: "launch_blocked_by_policy",
message:
"Windows blocked the sandboxed process launch because of an IT-managed policy rule \
(ERROR_ACCESS_DISABLED_BY_POLICY, 1260). Contact your system administrator \
to allow the target executable to run in an MXC sandbox."
.to_string(),
};
}
if win32_error == ERROR_CALL_NOT_IMPLEMENTED.0 || win32_error == E_NOTIMPL.0 as u32 {
return diagnose_api_not_implemented();
}
let bare_exe = Path::new(extract_exe_from_command_line(command_line));
let resolved_exe = resolve_exe_on_path(bare_exe);
if let Some(diag) = check_exe_heuristics(&resolved_exe, None) {
return diag;
}
LaunchDiagnostic {
kind: "create_process_failed",
message: format!(
"CreateProcessW failed with error code {win32_error} (0x{win32_error:08X})."
),
}
}
pub(crate) fn security_environment_failure_message(
error: &LearningModeError,
capture: bool,
) -> String {
let prefix = if capture {
"captureDenials: failed to start learning-mode capture"
} else {
"failed to create the process security environment"
};
let mut message = format!("{prefix}: {error}");
if matches!(
error,
LearningModeError::HResultCall {
function: "CreateProcessSecurityEnvironment",
code,
} if *code == ERROR_ACCESS_DISABLED_BY_POLICY.to_hresult().0
) {
message.push_str(
". Windows blocked creation of the requested sandbox because of an IT-managed \
policy rule (ERROR_ACCESS_DISABLED_BY_POLICY, 1260). Review the requested sandbox \
permissions or contact your system administrator.",
);
}
message
}
pub fn diagnose_process_exit(command_line: &str, exit_code: u32) -> Option<LaunchDiagnostic> {
let bare_exe = Path::new(extract_exe_from_command_line(command_line));
let resolved_exe = resolve_exe_on_path(bare_exe);
check_exe_heuristics(&resolved_exe, Some(exit_code))
}
const REQUIRED_VELOCITY_KEYS: &[(u32, &str)] = &[
(61389575, "BaseContainer core"),
(61155944, "BaseContainer sandbox spec"),
];
use windows::Win32::Foundation::{
ERROR_ACCESS_DISABLED_BY_POLICY, ERROR_CALL_NOT_IMPLEMENTED, ERROR_ENVVAR_NOT_FOUND, E_NOTIMPL,
STATUS_DLL_INIT_FAILED,
};
fn check_exe_heuristics(exe_path: &Path, exit_code: Option<u32>) -> Option<LaunchDiagnostic> {
if is_packaged_app(exe_path) {
return Some(LaunchDiagnostic {
kind: "packaged_app",
message: format!(
"The target executable '{}' appears to be a packaged (MSIX) app. \
Packaged apps cannot be launched inside a sandboxed container. \
Uninstall the packaged version and install an unpackaged build.",
exe_path.display()
),
});
}
if exit_code == Some(STATUS_DLL_INIT_FAILED.0 as u32) {
return Some(LaunchDiagnostic {
kind: "dll_init_failed_ui_required",
message: "The target executable exited with STATUS_DLL_INIT_FAILED (0xC0000142). \
This often means the sandbox is blocking Win32k system calls \
(UI subsystem access), which is often required to initialize. \
Enable UI access in your sandbox policy: set `ui.disable: false` \
in the JSON config, or `ui.allowWindows: true` if you are using \
the SDK's SandboxPolicy."
.to_string(),
});
}
None
}
fn diagnose_api_not_implemented() -> LaunchDiagnostic {
diagnose_api_not_implemented_with(&check_velocity_keys())
}
fn diagnose_api_not_implemented_with(key_status: &[(u32, bool)]) -> LaunchDiagnostic {
let mut message = "The native PSEC process-launch API returned E_NOTIMPL or \
ERROR_CALL_NOT_IMPLEMENTED. The process security environment feature is not enabled \
on this OS build. Windows ProcessContainer requires native PSEC support and cannot \
run this request. Use a host with PSEC enabled."
.to_string();
let disabled: Vec<String> = key_status
.iter()
.filter(|(_, enabled)| !enabled)
.map(|(id, _)| id.to_string())
.collect();
if !disabled.is_empty() {
message.push_str(&format!(
" Disabled feature flags: {}.",
disabled.join(", ")
));
}
LaunchDiagnostic {
kind: "feature_not_enabled",
message,
}
}
fn check_velocity_keys() -> Vec<(u32, bool)> {
#[cfg(target_os = "windows")]
{
use winreg::enums::HKEY_LOCAL_MACHINE;
use winreg::RegKey;
let mut results = Vec::new();
for &(key_id, _label) in REQUIRED_VELOCITY_KEYS {
let enabled = [4u32, 8].iter().any(|priority| {
let path = format!(
r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\FeatureManagement\Overrides\{}\{}",
priority, key_id
);
if let Ok(reg_key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(&path) {
if let Ok(state) = reg_key.get_value::<u32, _>("EnabledState") {
return state == 2;
}
}
false
});
results.push((key_id, enabled));
}
results
}
#[cfg(not(target_os = "windows"))]
{
Vec::new()
}
}
pub fn resolve_exe_on_path(exe: &Path) -> std::path::PathBuf {
if exe.is_absolute() {
return exe.to_path_buf();
}
if let Some(path_var) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&path_var) {
let candidate = dir.join(exe);
if candidate.exists() {
return candidate;
}
}
}
exe.to_path_buf()
}
pub fn extract_exe_from_command_line(command_line: &str) -> &str {
let trimmed = command_line.trim();
if let Some(after_quote) = trimmed.strip_prefix('"') {
match after_quote.find('"') {
Some(end) => &after_quote[..end],
None => trimmed.split_whitespace().next().unwrap_or(""),
}
} else {
trimmed.split_whitespace().next().unwrap_or("")
}
}
fn is_packaged_app(exe_path: &Path) -> bool {
let normalized = exe_path.to_string_lossy().to_lowercase();
normalized.contains("\\windowsapps\\") || normalized.contains("/windowsapps/")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mxc_common::models::FailurePhase;
fn env(entries: &[&str]) -> Vec<String> {
entries.iter().map(|s| s.to_string()).collect()
}
#[test]
fn missing_required_env_names_the_absent_variables() {
let supplied = env(&["PATH=C:\\Windows"]);
let diag = diagnose_missing_required_env(ERROR_ENVVAR_NOT_FOUND.0, Some(&supplied))
.expect("203 with a sparse caller env must produce a diagnostic");
assert_eq!(diag.kind, "missing_required_env");
assert!(diag.message.contains("SYSTEMROOT"));
assert!(diag.message.contains("LOCALAPPDATA"));
assert!(diag.message.contains("supplied `process.env`"));
assert!(diag.message.contains("verbatim"));
assert!(diag.message.contains("1 variable(s)"));
assert!(diag
.message
.contains("Set `process.inheritDefaultEnv` to true"));
}
#[test]
fn missing_required_env_reports_only_what_is_absent() {
let supplied = env(&["SystemRoot=C:\\Windows"]);
let diag =
diagnose_missing_required_env(ERROR_ENVVAR_NOT_FOUND.0, Some(&supplied)).unwrap();
assert!(!diag.message.contains("SYSTEMROOT"));
assert!(diag.message.contains("LOCALAPPDATA"));
}
#[test]
fn missing_required_env_describes_an_explicitly_empty_environment() {
let diag = diagnose_missing_required_env(ERROR_ENVVAR_NOT_FOUND.0, Some(&[])).unwrap();
assert!(diag.message.contains("an empty environment"));
}
#[test]
fn missing_required_env_ignores_other_error_codes() {
let supplied = env(&["PATH=C:\\Windows"]);
assert!(diagnose_missing_required_env(5, Some(&supplied)).is_none());
}
#[test]
fn missing_required_env_ignores_a_caller_supplied_complete_environment() {
let supplied = env(&[
"SYSTEMROOT=C:\\Windows",
"LOCALAPPDATA=C:\\Users\\u\\AppData\\Local",
]);
assert!(diagnose_missing_required_env(ERROR_ENVVAR_NOT_FOUND.0, Some(&supplied)).is_none());
}
#[test]
fn missing_required_env_ignores_a_block_mxc_built_itself() {
assert!(diagnose_missing_required_env(ERROR_ENVVAR_NOT_FOUND.0, None).is_none());
}
#[test]
fn validation_rejects_a_sparse_verbatim_environment() {
let request = ExecutionRequest {
env: Some(env(&["PATH=C:\\Windows"])),
..Default::default()
};
let error = validate_required_child_env(&request)
.expect_err("a sparse verbatim environment must be rejected");
assert_eq!(error.failure_phase, FailurePhase::Rejected);
assert!(error.error_message.contains("SYSTEMROOT"));
assert!(error.error_message.contains("LOCALAPPDATA"));
}
#[test]
fn validation_accepts_a_complete_verbatim_environment_case_insensitively() {
let request = ExecutionRequest {
env: Some(env(&[
"systemroot=C:\\Windows",
"LocalAppData=C:\\Users\\u\\AppData\\Local",
])),
..Default::default()
};
assert!(validate_required_child_env(&request).is_ok());
}
#[test]
fn validation_accepts_an_inherited_sparse_environment() {
let request = ExecutionRequest {
env: Some(env(&["MYVAR=hello"])),
inherit_default_env: true,
..Default::default()
};
assert!(validate_required_child_env(&request).is_ok());
}
#[test]
fn validation_accepts_an_omitted_environment() {
assert!(validate_required_child_env(&ExecutionRequest::default()).is_ok());
}
#[test]
fn validation_rejects_an_empty_caller_environment() {
let request = ExecutionRequest {
env: Some(Vec::new()),
..Default::default()
};
assert!(
validate_required_child_env(&request).is_err(),
"an empty caller-owned block omits the required variables"
);
}
#[test]
fn api_not_implemented_triggers_feature_diagnostic() {
let diag = diagnose_create_process_failure(ERROR_CALL_NOT_IMPLEMENTED.0, "pwsh.exe");
assert_eq!(diag.kind, "feature_not_enabled");
assert!(diag
.message
.contains("process security environment feature is not enabled"));
}
#[test]
fn e_notimpl_triggers_feature_diagnostic() {
let diag = diagnose_create_process_failure(E_NOTIMPL.0 as u32, "pwsh.exe");
assert_eq!(diag.kind, "feature_not_enabled");
}
#[test]
fn native_feature_guidance_requires_psec_and_lists_disabled_flags() {
for key_status in [
&[][..],
&[(61389575, true), (61155944, true)],
&[(61389575, false), (61155944, true)],
] {
let diag = diagnose_api_not_implemented_with(key_status);
assert_eq!(diag.kind, "feature_not_enabled");
assert!(diag.message.contains("requires native PSEC support"));
assert!(diag.message.contains("cannot run this request"));
assert_eq!(
diag.message.contains("Disabled feature flags: 61389575"),
key_status.iter().any(|(_, enabled)| !enabled)
);
}
}
#[test]
fn policy_block_takes_priority_over_executable_heuristics() {
let diag = diagnose_create_process_failure(
ERROR_ACCESS_DISABLED_BY_POLICY.0,
r#""C:\Program Files\PowerShell\7\pwsh.exe" -NoProfile"#,
);
assert_eq!(diag.kind, "launch_blocked_by_policy");
assert!(diag.message.contains("IT-managed"));
assert!(diag.message.contains("1260"));
assert!(diag.message.contains("system administrator"));
assert!(!diag.message.contains("readonlyPaths"));
}
#[test]
fn policy_block_at_environment_creation_has_automatic_guidance() {
let function = "CreateProcessSecurityEnvironment";
for capture in [false, true] {
let error = LearningModeError::HResultCall {
function,
code: ERROR_ACCESS_DISABLED_BY_POLICY.to_hresult().0,
};
let message = security_environment_failure_message(&error, capture);
assert!(message.contains("IT-managed policy rule"));
assert!(message.contains("requested sandbox permissions"));
assert!(message.contains("system administrator"));
assert!(message.contains(&ERROR_ACCESS_DISABLED_BY_POLICY.0.to_string()));
assert!(message.contains(&format!(
"0x{:08X}",
ERROR_ACCESS_DISABLED_BY_POLICY.to_hresult().0 as u32
)));
assert!(message.contains(function));
assert_eq!(message.starts_with("captureDenials:"), capture);
assert!(!message.contains("target executable"));
}
}
#[test]
fn unrelated_environment_and_trace_errors_keep_their_message() {
for (function, code) in [
(
"CreateProcessSecurityEnvironment",
windows::Win32::Foundation::E_ACCESSDENIED.0,
),
("CreateProcessSecurityEnvironment", E_NOTIMPL.0),
(
"CreateProcessSecurityEnvironment",
ERROR_ACCESS_DISABLED_BY_POLICY.0 as i32,
),
(
"GetLastProcessSecurityEnvironmentPolicyResult",
ERROR_ACCESS_DISABLED_BY_POLICY.to_hresult().0,
),
(
"StartLearningModeTrace",
ERROR_ACCESS_DISABLED_BY_POLICY.to_hresult().0,
),
] {
let error = LearningModeError::HResultCall { function, code };
for capture in [false, true] {
let prefix = if capture {
"captureDenials: failed to start learning-mode capture"
} else {
"failed to create the process security environment"
};
assert_eq!(
security_environment_failure_message(&error, capture),
format!("{prefix}: {error}")
);
}
}
}
#[test]
fn packaged_app_detected_from_command_line() {
let cmd =
r#""C:\Program Files\WindowsApps\Microsoft.PowerShell_7.4.0\pwsh.exe" -NoProfile"#;
let diag = diagnose_create_process_failure(87, cmd);
assert_eq!(diag.kind, "packaged_app");
assert!(diag.message.contains("packaged"));
}
#[test]
fn generic_fallback_for_unknown_error() {
let diag = diagnose_create_process_failure(5, "cmd.exe");
assert_eq!(diag.kind, "create_process_failed");
assert!(diag.message.contains("5"));
}
#[test]
fn pwsh_creation_failure_preserves_win32_error() {
for error in [2, 267] {
let diag = diagnose_create_process_failure(
error,
r#""C:\Program Files\PowerShell\7\pwsh.exe" -NoProfile"#,
);
assert_eq!(diag.kind, "create_process_failed");
assert!(diag.message.contains(&format!("error code {error} ")));
}
}
#[test]
fn dll_init_failed_pwsh_triggers_ui_diagnostic() {
let diag = diagnose_process_exit(
r#""C:\Program Files\PowerShell\7\pwsh.exe" -NoProfile"#,
STATUS_DLL_INIT_FAILED.0 as u32,
);
assert!(diag.is_some());
let d = diag.unwrap();
assert_eq!(d.kind, "dll_init_failed_ui_required");
assert!(d.message.contains("STATUS_DLL_INIT_FAILED"));
assert!(d.message.contains("UI access"));
}
#[test]
fn dll_init_failed_powershell_exe_triggers_ui_diagnostic() {
let diag = diagnose_process_exit(
r#""C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe""#,
STATUS_DLL_INIT_FAILED.0 as u32,
);
assert!(diag.is_some());
assert_eq!(diag.unwrap().kind, "dll_init_failed_ui_required");
}
#[test]
fn pwsh_nonzero_exit_has_no_filesystem_diagnostic() {
let diag = diagnose_process_exit(r#""C:\Program Files\PowerShell\7\pwsh.exe""#, 1);
assert!(diag.is_none());
}
#[test]
fn packaged_app_exit_has_packaged_app_diagnostic() {
let cmd = r#""C:\Program Files\WindowsApps\Microsoft.PowerShell_7.4.0\pwsh.exe""#;
let diag = diagnose_process_exit(cmd, 1);
assert!(diag.is_some());
assert_eq!(diag.unwrap().kind, "packaged_app");
}
#[test]
fn extract_exe_quoted_path_with_spaces() {
let cmd = r#""C:\Program Files\WindowsApps\Microsoft.PowerShell_7.6.1.0_x64__8wekyb3d8bbwe\pwsh.exe" -NoProfile -NoLogo"#;
let exe = extract_exe_from_command_line(cmd);
assert_eq!(
exe,
r"C:\Program Files\WindowsApps\Microsoft.PowerShell_7.6.1.0_x64__8wekyb3d8bbwe\pwsh.exe"
);
}
#[test]
fn extract_exe_unquoted() {
assert_eq!(
extract_exe_from_command_line("pwsh.exe -NoProfile"),
"pwsh.exe"
);
}
#[test]
fn extract_exe_quoted_no_args() {
let cmd = r#""C:\Program Files\PowerShell\7\pwsh.exe""#;
assert_eq!(
extract_exe_from_command_line(cmd),
r"C:\Program Files\PowerShell\7\pwsh.exe"
);
}
#[test]
fn extract_exe_empty() {
assert_eq!(extract_exe_from_command_line(""), "");
}
}