#[skuld::test]
fn detect_reports_windows_os() {
let h = crate::elevation::plan::Host::detect(
crate::elevation::Backend::Auto,
&crate::elevation::Auth::Interactive,
None,
false,
);
assert_eq!(h.os, crate::elevation::plan::Os::Windows);
}
#[skuld::test]
fn detect_reports_the_elevation_it_is_given() {
for elevated in [true, false] {
let h = crate::elevation::plan::Host::detect(
crate::elevation::Backend::Auto,
&crate::elevation::Auth::Interactive,
None,
elevated,
);
assert_eq!(h.elevated, elevated);
}
}
#[skuld::test]
fn detect_ignores_the_path_it_is_given() {
let h = crate::elevation::plan::Host::detect(
crate::elevation::Backend::Auto,
&crate::elevation::Auth::Interactive,
Some(std::ffi::OsStr::new(r"C:\Windows\System32")),
false,
);
assert_eq!(h.available, crate::elevation::plan::BackendSet::default());
}
#[skuld::test]
fn integrity_level_is_always_answerable() {
assert!(
super::integrity_level().is_some(),
"integrity_level() must resolve on any Windows runner"
);
}
#[skuld::test]
fn is_elevated_agrees_with_integrity_level() {
use windows::Win32::System::SystemServices::SECURITY_MANDATORY_HIGH_RID;
let elevated = super::is_elevated();
let rid = super::integrity_level().expect("integrity level must be readable");
let high = rid >= SECURITY_MANDATORY_HIGH_RID as u32;
assert_eq!(
elevated, high,
"TokenElevation ({elevated}) disagrees with integrity RID {rid:#x} vs High"
);
}
use crate::command::Command;
use crate::error::Error;
use crate::stdio::Stdio;
use crate::test_child::Console;
fn is_unsupported<T>(r: Result<T, Error>) -> bool {
matches!(r, Err(Error::Unsupported { .. }))
}
fn is_pathext_refusal<T>(r: Result<T, Error>) -> bool {
matches!(r, Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput && e.to_string().contains("PATHEXT"))
}
fn unsupported_detail<T: std::fmt::Debug>(r: Result<T, Error>) -> String {
match r {
Err(Error::Unsupported { detail, .. }) => detail,
other => panic!("expected Unsupported, got {other:?}"),
}
}
#[skuld::test]
fn piped_stdio_is_unsupported() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
c.stdout(Stdio::pipe()).unwrap();
assert!(is_unsupported(super::reject_unsupported_config(&c)));
}
#[skuld::test]
fn null_and_merge_stdio_are_unsupported() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
c.stdin(Stdio::null()).unwrap();
assert!(is_unsupported(super::reject_unsupported_config(&c)));
let mut c2 = crate::test_child::command(Console::Hidden);
c2.args([r"C:\Windows\System32\whoami.exe"]).elevate();
c2.stderr(Stdio::merge(crate::stdio::Fd::STDOUT)).unwrap();
assert!(is_unsupported(super::reject_unsupported_config(&c2)));
}
#[skuld::test]
fn high_fd_is_unsupported() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
c.fd(3, Stdio::pipe_out()).unwrap();
assert!(is_unsupported(super::reject_unsupported_config(&c)));
}
#[skuld::test]
fn env_and_contain_are_unsupported() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate().env("FOO", "bar");
assert!(is_unsupported(super::reject_unsupported_config(&c)));
let mut c2 = crate::test_child::command(Console::Hidden);
c2.args([r"C:\Windows\System32\whoami.exe"]).elevate().contain();
assert!(is_unsupported(super::reject_unsupported_config(&c2)));
}
#[skuld::test]
fn inherit_only_is_accepted() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
c.stdout(Stdio::inherit()).unwrap();
assert!(super::reject_unsupported_config(&c).is_ok());
}
fn win_host(elevated: bool) -> crate::elevation::plan::Host {
crate::elevation::plan::Host {
elevated,
has_tty: false,
available: crate::elevation::plan::BackendSet::default(),
os: crate::elevation::plan::Os::Windows,
arg_max: None,
pkexec_version: crate::elevation::pkexec::PkexecVersion::NotProbed,
pkexec_pin: None,
}
}
fn nul_between(prefix: &str, suffix: &str) -> std::ffi::OsString {
use std::os::windows::ffi::OsStringExt;
std::ffi::OsString::from_wide(
&prefix
.encode_utf16()
.chain([0])
.chain(suffix.encode_utf16())
.collect::<Vec<u16>>(),
)
}
#[skuld::test]
fn launch_runas_rejects_bad_config_before_the_short_circuit_regardless_of_privilege() {
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
c.stdout(Stdio::pipe()).unwrap();
assert!(
is_unsupported(super::plan_runas(&c, &win_host(elevated))),
"piped elevated config must reject with elevated={elevated}"
);
}
}
#[skuld::test]
fn commandline_elevated_is_unsupported_on_windows_regardless_of_privilege() {
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.commandline("whoami").elevate();
assert!(is_unsupported(super::plan_runas(&c, &win_host(elevated))));
}
}
#[skuld::test]
fn an_argv_less_command_is_not_reported_as_a_commandline_command() {
let mut by_executable = crate::test_child::command(Console::Hidden);
by_executable.executable("x.exe").elevate();
assert_eq!(
unsupported_detail(super::plan_runas(&by_executable, &win_host(false)).map(|_| ())),
super::ARGV_REFUSALS.setter,
"executable() only"
);
let mut bare = crate::test_child::command(Console::Hidden);
bare.elevate();
match super::plan_runas(&bare, &win_host(false)) {
Err(e @ Error::Unsupported { .. }) => {
let msg = e.to_string();
assert!(!msg.contains("commandline"), "none was set, got {msg}");
assert!(
msg.contains("empty command"),
"the refusal must name the missing program, got {msg}"
);
}
other => panic!("an argv-less elevate() must be refused, got {:?}", other.map(|_| "Ok")),
}
}
#[skuld::test]
fn a_clean_unelevated_request_plans_a_launch() {
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
let mut c = crate::test_child::command(Console::Asked);
c.args([r"C:\Windows\System32\whoami.exe", "/all"]).elevate();
let launch = match super::plan_runas(&c, &win_host(false)) {
Ok(super::RunasStep::Launch(launch)) => launch,
Ok(super::RunasStep::AlreadyElevated) => panic!("an unelevated host must not short-circuit"),
Err(e) => panic!("a clean inherit-only request must not be refused: {e:?}"),
};
assert_eq!(
launch.class_w,
"exefile\0".encode_utf16().collect::<Vec<u16>>(),
"the launch skips shell32's lookup by class"
);
for (field, w) in [
("lpVerb", &launch.verb_w),
("lpFile", &launch.file_w),
("lpParameters", &launch.params_w),
] {
assert_eq!(w.last(), Some(&0), "{field} must be NUL-terminated: {w:?}");
assert!(w.len() > 1, "{field} must carry the value, not just its terminator");
}
assert_eq!(
launch.dir_w, None,
"no current_dir() was set, so lpDirectory stays null"
);
assert_eq!(launch.show, SW_SHOWNORMAL);
}
#[skuld::test]
fn a_percent_in_current_dir_is_refused() {
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"])
.current_dir(r"C:\work\%TEMP%")
.elevate();
match super::plan_runas(&c, &win_host(elevated)) {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!(
"elevated={elevated}: expected Io(InvalidInput), got {:?}",
other.map(|_| "Ok")
),
}
}
}
#[skuld::test]
fn a_clean_request_with_a_current_dir_plans_a_launch_in_it() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"])
.current_dir(r"C:\Windows\Temp")
.elevate();
let launch = match super::plan_runas(&c, &win_host(false)) {
Ok(super::RunasStep::Launch(launch)) => launch,
Ok(super::RunasStep::AlreadyElevated) => panic!("an unelevated host must not short-circuit"),
Err(e) => panic!("a clean request with a current_dir() must not be refused: {e:?}"),
};
assert_eq!(
launch.dir_w,
Some(r"C:\Windows\Temp".encode_utf16().chain([0]).collect::<Vec<u16>>()),
"lpDirectory is current_dir(), wide and NUL-terminated"
);
}
#[skuld::test]
fn already_elevated_inherit_only_is_run_as_is() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate();
assert!(matches!(
super::plan_runas(&c, &win_host(true)),
Ok(super::RunasStep::AlreadyElevated)
));
}
fn assert_setter_refused(setter: &str, set: fn(&mut Command, &str), programs: &[&str]) {
let words = &super::ARGV_REFUSALS;
for elevated in [false, true] {
for &program in programs {
let mut plain = crate::test_child::command(Console::Hidden);
plain.args([program, "/all"]);
let mut line = crate::test_child::command(Console::Hidden);
line.commandline("whoami /all");
let mut nul_arg = crate::test_child::command(Console::Hidden);
nul_arg.args([std::ffi::OsString::from(program), nul_between("a", "b")]);
let mut nul_cwd = crate::test_child::command(Console::Hidden);
nul_cwd.args([program]).current_dir(nul_between(r"C:\w", "x"));
for (what, mut c) in [
("a plain argv", plain),
("commandline()", line),
("no input", crate::test_child::command(Console::Hidden)),
("a NUL in an argument", nul_arg),
("a NUL in current_dir()", nul_cwd),
] {
set(&mut c, program);
c.elevate();
let at = format!("elevated={elevated}, {setter}({program:?}), {what}");
match super::plan_runas(&c, &win_host(elevated)) {
Err(Error::Unsupported {
op, platform, detail, ..
}) => {
assert_eq!(platform, "windows", "{at}");
assert_eq!(op, format!("elevation of a program set by {setter}()"), "{at}");
assert_eq!(detail, words.setter, "{at}");
}
other => panic!("{at}: expected the setter refusal, got {:?}", other.map(|_| "Ok")),
}
}
let mut env = crate::test_child::command(Console::Hidden);
env.args([program]).env("A", "1");
set(&mut env, program);
env.elevate();
let detail = unsupported_detail(super::plan_runas(&env, &win_host(elevated)).map(|_| ()));
assert!(
detail.contains("environment"),
"elevated={elevated}, {setter}({program:?}): {detail}"
);
}
}
}
#[skuld::test]
fn an_elevated_executable_is_refused() {
assert_setter_refused(
"executable",
|c, p| {
c.executable(p);
},
&[r"C:\Windows\System32\whoami.exe", "whoami", r"C:\t\setup.bat"],
);
}
#[skuld::test]
fn an_elevated_raw_executable_is_refused() {
assert_setter_refused(
"raw_executable",
|c, p| {
c.raw_executable(p);
},
&[r"C:\Windows\System32\whoami.exe", "tool.exe", r"C:\t\setup.bat"],
);
}
#[skuld::test]
fn an_extensionless_absolute_argv0_program_is_refused_on_the_consent_path() {
for n in [r"C:\tools\setup", r"C:\tools\setup.bat.exe.lnk"] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([n]).elevate();
match super::plan_runas(&c, &win_host(false)) {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {
assert!(
e.to_string().contains("PATHEXT"),
"{n:?}: the reason must be named: {e}"
);
}
other => panic!("{n:?}: expected Io(InvalidInput), got {:?}", other.map(|_| "Ok")),
}
}
}
#[skuld::test]
fn an_extensionless_absolute_argv0_program_is_refused_when_already_elevated_too() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\tools\setup"]).elevate();
assert!(is_pathext_refusal(super::plan_runas(&c, &win_host(true)).map(|_| ())));
}
#[skuld::test]
fn an_absolute_argv0_exe_or_com_program_plans_a_launch() {
for n in [r"C:\tools\setup.exe", r"C:\tools\SETUP.COM"] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([n]).elevate();
assert!(
matches!(super::plan_runas(&c, &win_host(false)), Ok(super::RunasStep::Launch(_))),
"{n:?} must plan a launch"
);
}
}
#[skuld::test]
fn an_extensionless_search_program_is_refused_on_the_consent_path() {
for (via, c) in search_commands(&[r"C:\tools\setup", "whoami"]) {
match super::plan_runas(&c, &win_host(false)) {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {
assert!(
e.to_string().contains("PATHEXT"),
"{via}: the reason must be named: {e}"
);
}
other => panic!("{via}: expected Io(InvalidInput), got {:?}", other.map(|_| "Ok")),
}
}
}
#[skuld::test]
fn a_search_exe_or_com_program_plans_a_launch() {
for (via, c) in search_commands(&[r"C:\tools\setup.exe", r"C:\Windows\System32\WHOAMI.COM"]) {
assert!(
matches!(super::plan_runas(&c, &win_host(false)), Ok(super::RunasStep::Launch(_))),
"{via} must plan a launch"
);
}
}
#[skuld::test]
fn a_search_batch_reached_through_normalisation_is_refused_regardless_of_privilege() {
let probes = [
r"C:\t\setup.bat.",
r"C:\t\setup.bat ",
r"C:\t\.bat",
r"C:\t\setup.bat:.exe",
];
for elevated in [false, true] {
for (via, c) in search_commands(&probes) {
let detail = unsupported_detail(super::plan_runas(&c, &win_host(elevated)).map(|_| ()));
assert!(
detail.contains("CVE-2024-24576"),
"elevated={elevated}, {via}: {detail}"
);
}
}
}
fn search_commands(names: &[&str]) -> Vec<(String, Command)> {
let mut out = Vec::new();
for &n in names {
let mut argv = crate::test_child::command(Console::Hidden);
argv.args([n]).elevate();
out.push((format!("args([{n:?}])"), argv));
}
out
}
#[skuld::test]
fn runas_hides_the_window_when_no_window_is_requested() {
use crate::command::flags::FlagsRequest;
use windows::Win32::UI::WindowsAndMessaging::SW_HIDE;
let flags = FlagsRequest {
no_window: true,
..Default::default()
};
assert_eq!(super::runas_show_command(&flags), SW_HIDE);
}
#[skuld::test]
fn runas_shows_the_window_by_default() {
use crate::command::flags::FlagsRequest;
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
assert_eq!(super::runas_show_command(&FlagsRequest::default()), SW_SHOWNORMAL);
}
#[skuld::test]
fn elevation_rejects_raw_creation_flags() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"])
.elevate()
.creation_flags(0x0000_0040);
let detail = unsupported_detail(super::reject_unsupported_config(&c));
crate::error::assert_detail_is_not_hard_wrapped(&detail);
}
#[skuld::test]
fn elevation_accepts_a_zero_creation_flags_word() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate().creation_flags(0);
assert!(super::reject_unsupported_config(&c).is_ok());
}
#[skuld::test]
fn elevation_rejects_detached() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate().detached();
let detail = unsupported_detail(super::reject_unsupported_config(&c));
crate::error::assert_detail_is_not_hard_wrapped(&detail);
}
#[skuld::test]
fn elevation_rejects_breakaway() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"])
.elevate()
.breakaway_from_job();
let detail = unsupported_detail(super::reject_unsupported_config(&c));
crate::error::assert_detail_is_not_hard_wrapped(&detail);
}
#[skuld::test]
fn elevation_accepts_no_window() {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r"C:\Windows\System32\whoami.exe"]).elevate().no_window();
assert!(super::reject_unsupported_config(&c).is_ok());
}
#[skuld::test]
fn wide_nul_refuses_an_interior_nul_in_any_value() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
for units in [
vec![0u16],
"C:\\a\\b.exe\0junk".encode_utf16().collect::<Vec<u16>>(),
"D:\\work\0junk".encode_utf16().collect::<Vec<u16>>(),
] {
let value = OsString::from_wide(&units);
let got = super::wide_nul("probe field", &value);
assert!(
got.is_err(),
"an interior NUL must be refused, not truncated to {:?}",
value.to_string_lossy().split('\0').next().unwrap()
);
match got.unwrap_err() {
Error::Io(e) => {
assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e:?}");
assert!(
e.to_string().contains("probe field"),
"refusal must name the field: {e}"
);
}
other => panic!("expected Io(InvalidInput), got {other:?}"),
}
}
}
#[skuld::test]
fn wide_nul_accepts_an_ordinary_value_and_terminates_it() {
let w = super::wide_nul("program path", std::ffi::OsStr::new("C:\\tools\\app.exe")).unwrap();
assert_eq!(w.last(), Some(&0), "the buffer must be NUL-terminated: {w:?}");
assert!(!w[..w.len() - 1].contains(&0), "no interior NUL in a clean value");
}
#[skuld::test]
fn launch_runas_refuses_a_truncating_nul_regardless_of_privilege() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let nul_path = OsString::from_wide(
&r"Z:\cosca-nonexistent\x.exe"
.encode_utf16()
.chain([0])
.chain("junk".encode_utf16())
.collect::<Vec<u16>>(),
);
let clean = OsString::from(r"Z:\cosca-nonexistent\x.exe");
for elevated in [false, true] {
let mut by_program = crate::test_child::command(Console::Hidden);
by_program.args([nul_path.clone()]).elevate();
let mut by_argument = crate::test_child::command(Console::Hidden);
by_argument.args([clean.clone(), nul_path.clone()]).elevate();
let mut by_cwd = crate::test_child::command(Console::Hidden);
by_cwd.args([clean.clone()]).current_dir(&nul_path).elevate();
for (field, needle, c) in [
("lpFile", "program path", &by_program),
("lpParameters", "argument 1", &by_argument),
("lpDirectory", "working directory", &by_cwd),
] {
match super::plan_runas(c, &win_host(elevated)) {
Err(Error::Io(e)) => {
assert_eq!(
e.kind(),
std::io::ErrorKind::InvalidInput,
"elevated={elevated} {field}: expected the NUL refusal, got {e:?}"
);
assert!(
e.to_string().contains(needle),
"elevated={elevated} {field}: refusal must name the field ({needle:?}), got {e}"
);
}
other => panic!(
"elevated={elevated} {field}: a truncating NUL must be refused at the call \
site, got {:?}",
other.map(|_| "Ok")
),
}
}
}
}
#[skuld::test]
fn the_elevated_and_raw_paths_word_the_nul_refusal_identically() {
let token = nul_between(r"C:\tools\x.exe", "junk");
let mut c = crate::test_child::command(Console::Hidden);
c.args([token.clone()]).elevate();
let elevated = match super::plan_runas(&c, &win_host(false)) {
Err(Error::Io(e)) => e.to_string(),
other => panic!(
"a truncating program path must be refused, got {:?}",
other.map(|_| "Ok")
),
};
let raw = match crate::child::spawn::windows_raw::resolve::ensure_no_nul_wide("program path", &token) {
Err(Error::Io(e)) => e.to_string(),
other => panic!("the raw backend refuses the same token as an Io error, got {other:?}"),
};
assert_eq!(elevated, raw, "one defect, described two ways");
}
#[skuld::test]
fn launch_runas_refuses_a_batch_program_regardless_of_privilege() {
for elevated in [false, true] {
for probe in ["setup.bat", "setup.cmd", "SETUP.BAT"] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([probe, "a&calc"]).elevate();
assert!(
is_unsupported(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
"elevated={elevated}: {probe:?} must be refused before ShellExecuteEx hands it to cmd.exe"
);
}
}
}
#[skuld::test]
fn launch_runas_refuses_an_absolute_argv0_batch_reached_through_normalisation_regardless_of_privilege() {
for elevated in [false, true] {
for probe in [r"C:\t\setup.bat.", r"C:\t\setup.bat ", r"C:\t\.bat"] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([probe, "a&calc"]).elevate();
let detail = unsupported_detail(super::plan_runas(&c, &win_host(elevated)).map(|_| ()));
assert!(
detail.contains("CVE-2024-24576"),
"elevated={elevated}, {probe:?}: {detail}"
);
}
}
}
#[skuld::test]
fn launch_runas_refuses_a_program_not_ending_in_exe_or_com() {
for elevated in [false, true] {
for probe in [
r"C:\tools\setup",
"setup",
"setup.lnk",
"setup.msc",
r"C:\tools\setup.exe.",
] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([probe, "a&calc"]).elevate();
assert!(
is_pathext_refusal(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
"elevated={elevated}: {probe:?} may be completed or dispatched by ShellExecuteEx"
);
}
}
}
#[skuld::test]
fn launch_runas_refuses_a_program_that_is_not_fully_qualified() {
for elevated in [false, true] {
for probe in ["whoami.exe", r"tools\setup.exe", r"\tools\setup.exe", "C:setup.exe"] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([probe]).elevate();
assert!(
is_unsupported(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
"elevated={elevated}: {probe:?} is not fully qualified"
);
}
}
}
#[skuld::test]
fn launch_runas_refuses_a_token_shell_execute_rewrites() {
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([r#""C:\tools\setup.bat""#, "a&calc"]).elevate();
assert!(
is_unsupported(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
"elevated={elevated}: a quote is refused"
);
for probe in ["file:///C:/tools/setup%2Ebat", "shell:startup", r"C:\tools\%X%"] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([probe, "a&calc"]).elevate();
assert!(
is_pathext_refusal(super::plan_runas(&c, &win_host(elevated)).map(|_| ())),
"elevated={elevated}: {probe:?} is not a fully qualified image path without a quote"
);
}
}
}
#[skuld::test]
fn nul_bearing_batch_looking_path_is_diagnosed_as_a_nul_not_a_batch_refusal() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let nul_bat = OsString::from_wide(
&r"C:\tools\setup"
.encode_utf16()
.chain([0])
.chain(".bat".encode_utf16())
.collect::<Vec<u16>>(),
);
assert_eq!(
std::path::Path::new(&nul_bat).extension().map(|e| e.to_string_lossy()),
Some("bat".into()),
"premise: the token's extension is misleading"
);
assert!(
matches!(
crate::child::spawn::reject_batch_path(std::path::Path::new(&nul_bat)),
Err(Error::Io(ref e)) if e.kind() == std::io::ErrorKind::InvalidInput
),
"premise: the shared gate refuses this as a NUL too, never as a batch file"
);
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([nul_bat.clone()]).elevate();
match super::plan_runas(&c, &win_host(elevated)) {
Err(Error::Io(e)) => {
assert_eq!(
e.kind(),
std::io::ErrorKind::InvalidInput,
"elevated={elevated}: expected the NUL refusal, got {e:?}"
);
assert!(
e.to_string().contains("program path"),
"elevated={elevated}: the refusal must blame the program path, got {e}"
);
}
other => panic!(
"elevated={elevated}: a NUL-bearing batch-looking path must be diagnosed as a NUL, \
got {:?}",
other.map(|_| "Ok")
),
}
}
}
#[skuld::test]
fn a_nul_after_a_batch_extension_is_blamed_on_the_nul_not_the_batch_gate() {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let bat_nul = OsString::from_wide(
&r"C:\tools\setup.bat"
.encode_utf16()
.chain([0])
.chain("junk".encode_utf16())
.collect::<Vec<u16>>(),
);
assert!(
matches!(
crate::child::spawn::reject_batch_path(std::path::Path::new(&bat_nul)),
Err(Error::Io(ref e)) if e.kind() == std::io::ErrorKind::InvalidInput
),
"premise: the shared gate refuses this as a NUL"
);
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([bat_nul.clone(), OsString::from("a&calc")]).elevate();
match super::plan_runas(&c, &win_host(elevated)) {
Err(Error::Io(e)) => {
assert_eq!(
e.kind(),
std::io::ErrorKind::InvalidInput,
"elevated={elevated}: expected the NUL refusal, got {e:?}"
);
assert!(
e.to_string().contains("program path"),
"elevated={elevated}: the refusal must blame the program path, got {e}"
);
}
other => panic!(
"elevated={elevated}: a NUL that truncates back to a real batch file must be \
blamed on the NUL, got {:?}",
other.map(|_| "Ok")
),
}
}
}
#[skuld::test]
fn a_poisoned_program_path_is_named_before_a_poisoned_argument_or_cwd() {
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([nul_between(r"C:\tools\setup.bat", "junk"), nul_between("x", "y")])
.current_dir(nul_between(r"C:\work", "junk"))
.elevate();
match super::plan_runas(&c, &win_host(elevated)) {
Err(Error::Io(e)) => {
assert_eq!(
e.kind(),
std::io::ErrorKind::InvalidInput,
"elevated={elevated}: expected the NUL refusal, got {e:?}"
);
assert!(
e.to_string().contains("program path"),
"elevated={elevated}: the program path outranks the other poisoned fields, got {e}"
);
}
other => panic!(
"elevated={elevated}: a truncating NUL must be refused, got {:?}",
other.map(|_| "Ok")
),
}
}
}
#[skuld::test]
fn a_poisoned_working_directory_is_named_before_the_batch_gate() {
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([std::ffi::OsString::from(r"C:\tools\setup.bat")])
.current_dir(nul_between(r"C:\work", "junk"))
.elevate();
match super::plan_runas(&c, &win_host(elevated)) {
Err(Error::Io(e)) => {
assert_eq!(
e.kind(),
std::io::ErrorKind::InvalidInput,
"elevated={elevated}: expected the NUL refusal, got {e:?}"
);
assert!(
e.to_string().contains("working directory"),
"elevated={elevated}: the refusal must name the working directory, got {e}"
);
}
other => panic!(
"elevated={elevated}: the cwd's NUL must be refused before the batch gate, got {:?}",
other.map(|_| "Ok")
),
}
}
}
#[skuld::test]
fn a_poisoned_argument_is_named_before_the_batch_gate() {
for elevated in [false, true] {
let mut c = crate::test_child::command(Console::Hidden);
c.args([std::ffi::OsString::from(r"C:\tools\setup.bat"), nul_between("x", "y")])
.elevate();
match super::plan_runas(&c, &win_host(elevated)) {
Err(Error::Io(e)) => assert!(
e.to_string().contains("argument 1"),
"elevated={elevated}: the refusal must name the poisoned argument, got {e}"
),
other => panic!(
"elevated={elevated}: the argument's NUL must be refused before the batch gate, got {:?}",
other.map(|_| "Ok")
),
}
}
}
#[skuld::test]
fn a_failed_token_close_is_logged() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let outcome = std::panic::catch_unwind(|| drop(super::OwnedToken(windows::Win32::Foundation::HANDLE(0x3 as _))));
assert_eq!(
outcome.is_err(),
cfg!(debug_assertions),
"the debug_assert fires in exactly the builds that keep it"
);
assert!(
crate::log_capture::contains_since(mark, "CloseHandle of an owned token failed"),
"a failed token close must be logged"
);
}
#[skuld::test]
fn a_shell_execute_failure_takes_its_answer_from_the_classification() {
use windows::core::HRESULT;
use windows::Win32::Foundation::{ERROR_CANCELLED, ERROR_DDE_FAIL, ERROR_FILE_NOT_FOUND};
use crate::child::spawn::SpawnFailure;
use crate::error::{ChildFate, ElevationErrorKind, Error};
assert!(matches!(
super::shell_execute_failure(HRESULT::from_win32(ERROR_CANCELLED.0), 0),
SpawnFailure::NotStarted(Error::Elevation {
kind: ElevationErrorKind::AuthDeclined,
..
})
));
assert!(matches!(
super::shell_execute_failure(HRESULT::from_win32(ERROR_FILE_NOT_FOUND.0), 2),
SpawnFailure::NotStarted(Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
..
})
));
assert!(matches!(
super::shell_execute_failure(HRESULT::from_win32(ERROR_DDE_FAIL.0), 0),
SpawnFailure::MayHaveStarted {
ref cause,
fate: ChildFate::Unknown,
wrapper_elevated: false,
..
} if matches!(
**cause,
Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
..
}
)
));
}
#[skuld::test]
fn a_failed_shell_execute_has_the_windows_error_as_its_cause() {
use windows::core::HRESULT;
use windows::Win32::Foundation::{ERROR_DDE_FAIL, ERROR_FILE_NOT_FOUND};
use crate::child::spawn::SpawnFailure;
use crate::error::{ElevationErrorKind, Error};
for (code, inst_app) in [(ERROR_FILE_NOT_FOUND.0, 2), (ERROR_DDE_FAIL.0, 0)] {
let error = match super::shell_execute_failure(HRESULT::from_win32(code), inst_app) {
SpawnFailure::NotStarted(error) => error,
SpawnFailure::MayHaveStarted { cause, .. } => *cause,
};
assert_eq!(crate::error::first_os_code(&error), Some(code as i32), "{error:?}");
match error {
Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail,
..
} => assert_eq!(detail, "ShellExecuteEx(runas) failed"),
other => panic!("expected AuthFailed, got {other:?}"),
}
}
}
#[skuld::test]
fn an_hresult_cause_keeps_its_hex_unless_it_is_a_win32_code() {
use windows::core::HRESULT;
let win32 = super::hresult_cause(HRESULT(0x8007_0005_u32 as i32));
assert_eq!(crate::error::first_os_code(&*win32), Some(5));
assert!(!crate::error::said(&*win32).contains("HRESULT"), "{win32}");
let other = super::hresult_cause(HRESULT(0x8000_4005_u32 as i32));
let text = crate::error::said(&*other);
assert!(text.contains("HRESULT 0x80004005"), "{text}");
}
#[skuld::test]
fn an_untracked_child_fate_follows_how_its_termination_ended() {
use super::untracked_outcome;
use crate::error::ChildFate;
use crate::identity::Termination;
use windows::core::{Error as WinError, HRESULT};
let win = |code| WinError::from_hresult(HRESULT::from_win32(code));
let unresolved = || Ok((4242, win(1)));
let (detail, source, cleanup, fate) = untracked_outcome(unresolved(), Termination::Terminated);
assert_eq!(fate, ChildFate::Killed);
assert!(cleanup.is_none(), "{cleanup:?}");
assert!(detail.ends_with("it was terminated"), "{detail}");
assert_eq!(
crate::error::first_os_code(&*source.expect("the identity read's failure is the cause")),
Some(1)
);
let (detail, _, cleanup, fate) = untracked_outcome(unresolved(), Termination::Exited);
assert_eq!(fate, ChildFate::Killed);
assert!(cleanup.is_none(), "{cleanup:?}");
assert!(
detail.ends_with("it exited or is exiting, and its exit was not waited for"),
"{detail}"
);
let (detail, source, cleanup, fate) = untracked_outcome(unresolved(), Termination::Failed(win(5)));
assert_eq!(fate, ChildFate::Running { id: None });
assert!(detail.contains("pid 4242"), "{detail}");
assert!(detail.contains("identity could not be resolved"), "{detail}");
assert!(
detail.ends_with("and could not be terminated; it may still be running"),
"{detail}"
);
assert_eq!(
crate::error::first_os_code(&*source.expect("the identity read's failure is the cause")),
Some(1)
);
let cleanup = cleanup.expect("the refused termination is the cleanup");
assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
assert_eq!(crate::error::first_os_code(&**cleanup.first()), Some(5), "{cleanup:?}");
assert!(
crate::error::said(&**cleanup.first()).starts_with(&crate::error::io_said("terminating the elevated child: ")),
"the refusal names its step: {cleanup:?}"
);
let no_pid = || Err(win(6));
let (detail, source, cleanup, fate) = untracked_outcome(no_pid(), Termination::Failed(win(5)));
assert_eq!(fate, ChildFate::Running { id: None });
assert!(!detail.contains("pid 0"), "{detail}");
assert!(detail.contains("pid could not be read (GetProcessId)"), "{detail}");
assert!(!detail.contains("identity could not be resolved"), "{detail}");
assert!(
detail.ends_with("and could not be terminated; it may still be running"),
"{detail}"
);
assert!(
!detail.contains(&win(6).message()) && !detail.contains(&win(5).message()),
"a failure's text is in the detail: {detail}"
);
assert_eq!(
crate::error::first_os_code(&*source.expect("the failed read is the cause")),
Some(6)
);
let cleanup = cleanup.expect("the refused termination is the cleanup");
assert_eq!(crate::error::first_os_code(&**cleanup.first()), Some(5), "{cleanup:?}");
let (detail, source, cleanup, fate) = untracked_outcome(no_pid(), Termination::Terminated);
assert_eq!(fate, ChildFate::Killed);
assert!(cleanup.is_none(), "{cleanup:?}");
assert!(detail.contains("pid could not be read (GetProcessId)"), "{detail}");
assert!(detail.ends_with("it was terminated"), "{detail}");
assert_eq!(
crate::error::first_os_code(&*source.expect("the failed read is the cause")),
Some(6)
);
}
#[skuld::test]
fn an_already_elevated_spawn_leaves_the_callers_command_without_a_report() {
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
cmd.args(["cmd", "/c", "exit", "0"]);
let child = super::spawn_already_elevated(&mut cmd, true, crate::child::spawn::policy::SpawnPolicy::SYNC)
.expect("an ordinary spawn");
assert!(cmd.elevation_report().is_none(), "{:?}", cmd.elevation_report());
assert_eq!(
child.elevation().map(|report| report.via),
Some(super::ElevatedVia::AlreadyElevated)
);
assert!(child.wait().expect("the child exits").success());
}