use super::*;
use crate::command::Command;
use crate::error::Error;
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
fn nul_between(prefix: &str, suffix: &str) -> OsString {
OsString::from_wide(
&prefix
.encode_utf16()
.chain([0])
.chain(suffix.encode_utf16())
.collect::<Vec<u16>>(),
)
}
fn invalid_input_message(via: &str, r: Result<(), Error>) -> String {
match r {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => e.to_string(),
other => panic!("{via}: expected Io(InvalidInput), got {other:?}"),
}
}
fn commands_with_token(token: &OsString) -> Vec<(&'static str, Command)> {
let mut by_argv = Command::new();
by_argv.args([token.clone()]);
let mut by_executable = Command::new();
by_executable.executable(token).args(["ordinary.exe"]);
let mut by_commandline = Command::new();
by_commandline.commandline(token.clone());
vec![
("argv[0]", by_argv),
("executable()", by_executable),
("commandline()", by_commandline),
]
}
#[skuld::test]
fn a_nul_before_a_batch_extension_is_diagnosed_as_a_nul_not_a_batch_refusal() {
let token = nul_between(r"C:\tools\setup", ".bat");
invalid_input_message(
"the shared gate",
crate::child::spawn::reject_batch_path(std::path::Path::new(&token)),
);
for (via, c) in commands_with_token(&token) {
let msg = invalid_input_message(via, reject_batch_program(&c));
assert!(
!msg.contains('\0'),
"{via}: the refusal must not carry a raw NUL into logs: {msg:?}"
);
}
}
#[skuld::test]
fn a_clean_batch_token_is_still_refused_as_a_batch() {
for (via, c) in commands_with_token(&OsString::from(r"C:\tools\setup.bat")) {
assert!(
matches!(reject_batch_program(&c), Err(Error::Unsupported { .. })),
"{via}: a clean .bat must still be refused by the batch gate"
);
}
}
#[skuld::test]
fn a_nul_in_the_program_token_is_not_blamed_on_the_environment() {
let token = nul_between("setup.bat", "junk");
invalid_input_message(
"the shared gate",
crate::child::spawn::reject_batch_path(std::path::Path::new(&token)),
);
for (via, c) in commands_with_token(&token) {
let msg = invalid_input_message(via, reject_batch_program(&c));
assert!(
msg.contains("program token"),
"{via}: must name the program token, got {msg}"
);
assert!(
!msg.contains("environment"),
"{via}: a program token is not the environment, got {msg}"
);
}
}
#[skuld::test]
fn a_nul_in_an_argument_is_blamed_on_its_index() {
let mut c = Command::new();
c.args([OsString::from("a"), nul_between("b", "c"), OsString::from("d")]);
let msg = invalid_input_message("argv", super::raw_program_and_line(&c).map(|_| ()));
assert!(msg.contains("argument 1"), "must name the offending element, got {msg}");
}
#[skuld::test]
fn raw_program_and_line_rejects_an_empty_command_line_with_no_executable_set() {
let mut cmd = Command::new();
cmd.commandline("");
let err = raw_program_and_line(&cmd).unwrap_err();
assert!(matches!(err, Error::Io(_)), "{err:?}");
}
#[skuld::test]
fn raw_program_and_line_rejects_a_whitespace_only_command_line_with_no_executable_set() {
let mut cmd = Command::new();
cmd.commandline(" ");
let err = raw_program_and_line(&cmd).unwrap_err();
assert!(matches!(err, Error::Io(_)), "{err:?}");
}
#[skuld::test]
fn raw_program_and_line_allows_an_empty_command_line_when_executable_is_set() {
let mut cmd = Command::new();
cmd.executable(std::path::PathBuf::from(r"C:\some\app.exe"));
cmd.commandline("");
assert!(raw_program_and_line(&cmd).is_ok());
}
#[skuld::test]
fn raw_program_and_line_allows_a_non_empty_command_line_with_no_executable_set() {
let mut cmd = Command::new();
cmd.commandline("tool --flag");
assert!(raw_program_and_line(&cmd).is_ok());
}
#[skuld::test]
fn the_containment_marker_is_named_as_std_names_it() {
let removed = "__cosca_group_root";
let mut std_cmd = std::process::Command::new("unused");
std_cmd.env_remove(removed).env(crate::containment::NESTED_ENV, "1");
let std_name: Vec<_> = std_cmd.get_envs().map(|(k, _)| k.to_os_string()).collect();
assert_eq!(std_name, [OsString::from(removed)], "std control");
let snapshot = env_snapshot::EnvSnapshot::from_block("A=1\0\0".encode_utf16().collect());
let user_ops = [EnvOp::Remove(removed.into())];
let ops = child_ops(&user_ops, true);
let block = resolve::ChildEnv::capture(&snapshot, &ops).into_block().unwrap();
assert_eq!(String::from_utf16(&block).unwrap(), "A=1\0__cosca_group_root=1\0\0");
}
fn image(cmd: &Command) -> Result<Option<PathBuf>, Error> {
Ok(target(cmd, &spawn_env(cmd)?)?.image)
}
fn image_on(cmd: &Command) -> Result<Option<PathBuf>, Error> {
Ok(target_with(cmd, &spawn_env(cmd)?, || Ok(PathBuf::from(EXACT_CWD)))?.image)
}
const EXACT_CWD: &str = r"C:\cosca-process-cwd";
#[skuld::test]
fn target_completes_an_exact_program_without_searching_it() {
let mut cmd = Command::new();
cmd.raw_executable("tool").args(["tool"]);
let image = image_on(&cmd).expect("an exact program is never searched, so it cannot miss");
assert_eq!(image.as_deref(), Some(Path::new(r"C:\cosca-process-cwd\tool")));
}
const PROBE: &str = "cosca_exact_cwd_probe.exe";
const FIXTURE_LOAD_EXACT_PROBE_TEST: &str = "child::spawn::windows_raw::windows_raw_tests::fixture_load_exact_probe";
const FIXTURE_LOAD_EXACT_PROBE_ENV: &str = "COSCA_FIXTURE_LOAD_EXACT_PROBE_CURRENT_DIR";
const LOADED: i32 = 0;
const FILE_NOT_FOUND: i32 = 20;
const OTHER_FAILURE: i32 = 21;
#[skuld::test]
fn fixture_load_exact_probe() {
let Some(current_dir) = std::env::var_os(FIXTURE_LOAD_EXACT_PROBE_ENV) else {
return;
};
let mut c = Command::new();
c.raw_executable(PROBE)
.args([PROBE, "--exact", "__cosca_no_such_test__"])
.current_dir(current_dir);
crate::test_reexec::scrub_env(|var| _ = c.env_remove(var));
c.stdout(crate::stdio::Stdio::null()).expect("stdout null");
c.stderr(crate::stdio::Stdio::null()).expect("stderr null");
let image = image(&c).expect("target").unwrap();
assert!(image.is_absolute() && image.ends_with(PROBE), "{image:?}");
let not_found = windows::Win32::Foundation::ERROR_FILE_NOT_FOUND;
let code = match c.spawn() {
Ok(child) if child.wait().expect("wait").success() => LOADED,
Err(Error::Io(e))
if e.raw_os_error() == Some(not_found.0 as i32)
|| e.raw_os_error() == Some(windows::core::HRESULT::from_win32(not_found.0).0) =>
{
FILE_NOT_FOUND
}
_ => OTHER_FAILURE,
};
std::process::exit(code);
}
fn load_exact_probe(process_cwd: &Path, current_dir: &Path) -> Option<i32> {
let mut c = Command::new();
c.executable(std::env::current_exe().expect("current_exe"))
.args(crate::test_child::fixture_argv(FIXTURE_LOAD_EXACT_PROBE_TEST))
.env(FIXTURE_LOAD_EXACT_PROBE_ENV, current_dir)
.current_dir(process_cwd);
crate::test_reexec::scrub_env(|var| _ = c.env_remove(var));
c.stdout(crate::stdio::Stdio::null()).expect("stdout null");
c.stderr(crate::stdio::Stdio::null()).expect("stderr null");
c.spawn().expect("spawn the fixture").wait().expect("wait").code()
}
#[skuld::test]
fn an_exact_image_is_loaded_from_the_process_cwd_not_current_dir() {
let (with, without) = (
tempfile::tempdir().expect("tempdir"),
tempfile::tempdir().expect("tempdir"),
);
std::fs::copy(std::env::current_exe().expect("current_exe"), with.path().join(PROBE)).expect("copy");
assert_eq!(load_exact_probe(with.path(), without.path()), Some(LOADED));
assert_eq!(
load_exact_probe(without.path(), with.path()),
Some(FILE_NOT_FOUND),
"current_dir() holds the image but the process cwd does not"
);
}
#[skuld::test]
fn target_resolves_a_search_program_to_an_absolute_path() {
let mut cmd = Command::new();
cmd.executable("cmd").args(["cmd"]);
let image = image(&cmd).expect("cmd resolves on any Windows host").unwrap();
assert!(
image.is_absolute(),
"a Search program must be absolute by the time the backend sees it, got {image:?}"
);
assert_ne!(image, Path::new("cmd"), "it must actually have been resolved");
}
#[skuld::test]
fn target_rejects_an_empty_exact_program() {
let mut cmd = Command::new();
cmd.raw_executable("").args(["tool"]);
match image(&cmd) {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!("an empty exact program must be Io(InvalidInput), got {other:?}"),
}
}
#[skuld::test]
fn a_spawn_of_a_program_that_names_no_file_is_invalid_input() {
for n in [r"C:\t\dir\", ".", "..", "C:", r"x\.."] {
let mut exact = Command::new();
exact.raw_executable(n).args(["tool"]);
let mut search = Command::new();
search.executable(n).args(["tool"]);
for (via, mut c) in [("raw_executable", exact), ("executable", search)] {
match c.spawn() {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!(
"{via}({n:?}) names no file and must be Io(InvalidInput), got {:?}",
other.map(|_| "a child")
),
}
}
}
}
#[skuld::test]
fn target_rejects_an_exact_program_that_names_no_file() {
for n in [r"C:\t\dir\", r"C:\t\.", ".", "..", "C:", r"C:\t\...", r"C:\t\. "] {
let mut cmd = Command::new();
cmd.raw_executable(n).args(["tool"]);
match image(&cmd) {
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::InvalidInput => {}
other => panic!("{n:?} names no file and must be Io(InvalidInput), got {other:?}"),
}
}
}
#[skuld::test]
fn target_completes_an_exact_program_as_the_loader_does() {
let mut cmd = Command::new();
cmd.raw_executable(r"t\tool.").args(["tool"]);
assert_eq!(
image_on(&cmd).unwrap().as_deref(),
Some(Path::new(r"C:\cosca-process-cwd\t\tool"))
);
}
#[skuld::test]
fn the_token_gate_refuses_an_exact_batch_reached_through_win32_normalisation() {
for n in ["setup.bat.", "setup.bat ", r"C:\t\.bat"] {
let mut cmd = Command::new();
cmd.raw_executable(n).args(["tool"]);
match reject_batch_program(&cmd) {
Err(Error::Unsupported { platform, detail, .. }) => {
assert_eq!(platform, "windows");
assert!(detail.contains("CVE-2024-24576"), "{n:?}: {detail}");
}
other => panic!("{n:?} reaches a batch file and must be refused, got {other:?}"),
}
}
}
#[skuld::test]
fn target_completes_an_exact_program_that_is_not_a_batch_file() {
for n in ["setup.exe", "setup.bat.exe"] {
let mut cmd = Command::new();
cmd.raw_executable(n).args(["tool"]);
assert_eq!(image_on(&cmd).unwrap(), Some(Path::new(EXACT_CWD).join(n)));
}
}
#[skuld::test]
fn target_falls_back_to_the_program_token_when_no_executable_is_set() {
let mut cmd = Command::new();
cmd.args(["cmd", "/C", "exit 0"]);
let image = image(&cmd).expect("argv[0] resolves").unwrap();
assert!(image.is_absolute(), "the fallback must resolve too, got {image:?}");
}
fn high_fd_command() -> Command {
let mut c = Command::new();
c.fd(3, crate::stdio::Stdio::pipe_out()).expect("fd 3");
c
}
#[skuld::test]
fn program_token_reads_the_first_argv_element() {
let mut refused = high_fd_command();
refused.args(["x.bat", "ordinary.exe", "tail.exe"]);
assert!(crate::child::spawn::routes_to_raw_backend(&refused));
assert_eq!(program_token(&refused), Some(PathBuf::from("x.bat")));
assert!(
matches!(reject_batch_program(&refused), Err(Error::Unsupported { .. })),
"argv[0] is a batch file"
);
let mut allowed = high_fd_command();
allowed.args(["ordinary.exe", "x.bat", "y.cmd"]);
assert_eq!(program_token(&allowed), Some(PathBuf::from("ordinary.exe")));
reject_batch_program(&allowed).expect("only argv[0] is the program");
}
#[skuld::test]
fn program_token_reads_the_first_command_line_token() {
for (line, token) in [
("x.bat --flag", "x.bat"),
(r#""C:\dir with space\x.bat" --flag"#, r"C:\dir with space\x.bat"),
(r"\\srv\x.bat\.. & calc", r"\\srv\x.bat\.."),
] {
let mut c = high_fd_command();
c.commandline(line);
assert!(crate::child::spawn::routes_to_raw_backend(&c));
assert_eq!(program_token(&c), Some(PathBuf::from(token)), "{line:?}");
assert!(
matches!(reject_batch_program(&c), Err(Error::Unsupported { .. })),
"{line:?}: the first token is a batch file"
);
}
let mut allowed = high_fd_command();
allowed.commandline(r#"ordinary.exe x.bat "y.cmd""#);
assert_eq!(program_token(&allowed), Some(PathBuf::from("ordinary.exe")));
reject_batch_program(&allowed).expect("only the first token is the program");
}
#[skuld::test]
fn a_high_fd_spawn_without_an_executable_is_gated_on_its_program_token() {
let mut by_argv = high_fd_command();
by_argv.args(["x.bat", "--flag"]);
let mut by_line = high_fd_command();
by_line.commandline("x.bat --flag");
for (via, mut c) in [("argv", by_argv), ("commandline", by_line)] {
let err = crate::child::spawn::failure::expect_not_started(
c.spawn().expect_err("a batch program token must be refused"),
);
assert!(matches!(err, Error::Unsupported { .. }), "{via}: got {err:?}");
}
}
#[skuld::test]
fn target_pins_the_resolved_directory_as_the_childs() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("sub")).unwrap();
std::fs::write(dir.path().join("sub").join("tool.exe"), b"x").unwrap();
for (cmd_cwd, want_dir) in [(Some("sub"), dir.path().join("sub")), (None, dir.path().to_path_buf())] {
let token = if cmd_cwd.is_some() {
r".\tool.exe"
} else {
r"sub\tool.exe"
};
let mut cmd = Command::new();
cmd.executable(token).args([token]);
if let Some(c) = cmd_cwd {
cmd.current_dir(c);
}
let reads = std::cell::Cell::new(0);
let got = target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
reads.set(reads.get() + 1);
Ok(dir.path().to_path_buf())
})
.unwrap();
assert_eq!(reads.get(), 1, "{cmd_cwd:?}");
assert_eq!(got.cwd, want_dir, "{cmd_cwd:?}");
let image = got.image.unwrap();
assert!(image.starts_with(&want_dir), "{cmd_cwd:?}: {image:?}");
}
}
#[skuld::test]
fn target_refuses_a_share_less_unc_current_dir() {
let mut cmd = Command::new();
cmd.executable(r".\tool.exe")
.args([r".\tool.exe"])
.current_dir(r"\\server");
match target(&cmd, &spawn_env(&cmd).unwrap()) {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e}"),
Err(other) => panic!("expected Io(InvalidInput), got {other:?}"),
Ok(_) => panic!("a share-less UNC directory must be refused"),
}
}
#[skuld::test]
fn target_completes_an_exact_program_and_its_current_dir_from_one_read() {
let mut cmd = Command::new();
cmd.raw_executable("tool.exe").args(["tool.exe"]).current_dir("sub");
let reads = std::cell::Cell::new(0);
let got = target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
reads.set(reads.get() + 1);
Ok(PathBuf::from(EXACT_CWD))
})
.unwrap();
assert_eq!(reads.get(), 1);
assert_eq!(got.cwd, Path::new(EXACT_CWD).join("sub"));
assert_eq!(got.image, Some(Path::new(EXACT_CWD).join("tool.exe")));
}
#[skuld::test]
fn an_empty_current_dir_is_refused_on_both_arms() {
let mut search = Command::new();
search.executable("tool").args(["tool"]).current_dir("");
let mut exact = Command::new();
exact.raw_executable(r"C:\t\tool.exe").args(["tool"]).current_dir("");
for (arm, cmd) in [("Search", search), ("Exact", exact)] {
match target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
panic!("{arm}: must not read the cwd")
}) {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "{arm}: {e}"),
Err(other) => panic!("{arm}: expected Io(NotFound), got {other:?}"),
Ok(_) => panic!("{arm}: an empty current_dir must be refused"),
}
}
}
#[skuld::test]
fn target_pins_the_process_cwd_for_every_program() {
let mut cmd = Command::new();
cmd.executable("cmd").args(["cmd"]);
let reads = std::cell::Cell::new(0);
let got = target_with(&cmd, &spawn_env(&cmd).unwrap(), || {
reads.set(reads.get() + 1);
Ok(PathBuf::from(EXACT_CWD))
})
.unwrap();
assert_eq!(reads.get(), 1);
assert_eq!(got.cwd, PathBuf::from(EXACT_CWD));
}
fn raw_blocker() -> Command {
let mut c = Command::new();
c.executable("findstr")
.args(["findstr", "/c:needle"])
.stdin(crate::stdio::Stdio::pipe())
.expect("stdin pipe");
c
}
#[skuld::test]
fn a_raw_spawn_reads_the_identity_before_it_attaches() {
use crate::child::spawn::fault;
let mut c = raw_blocker();
fault::set_force_identity_vanished(true);
fault::set_force_attach_failure(true);
let result = c.spawn();
fault::set_force_attach_failure(false);
fault::set_force_identity_vanished(false);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
result.expect_err("a forced failure fails the spawn"),
);
assert!(
matches!(&err, Error::Io(e) if e.to_string().contains("reaped by another party")),
"the identity check comes first: {err:?}"
);
assert_eq!(
fate,
crate::error::ChildFate::Reaped,
"the raw teardown kills and reaps the child"
);
fault::assert_child_reaped(fault::take_captured().expect("the seam captured the child"));
}
#[skuld::test]
fn a_raw_spawn_whose_attach_fails_tears_its_child_down() {
use crate::child::spawn::fault;
let mut c = raw_blocker();
fault::set_force_attach_failure(true);
let result = c.spawn();
fault::set_force_attach_failure(false);
let (err, fate) = crate::child::spawn::failure::expect_may_have_started_with(
result.expect_err("the forced attach failure fails the spawn"),
);
assert!(matches!(err, Error::Containment { .. }), "{err:?}");
assert_eq!(fate, crate::error::ChildFate::Reaped, "terminated and waited for");
fault::assert_child_reaped(fault::take_captured().expect("the seam captured the child"));
}
#[skuld::test]
fn a_raw_spawn_whose_create_process_fails_did_not_start() {
let dir = tempfile::tempdir().expect("tempdir");
let image = dir.path().join("not-a-program.exe");
std::fs::write(&image, b"not a PE image").expect("write the image");
let mut c = Command::new();
c.executable(&image).args(["not-a-program"]);
let err = crate::child::spawn::failure::expect_not_started(c.spawn().expect_err("a non-PE image fails"));
assert!(matches!(err, Error::Io(ref e) if e.raw_os_error().is_some()), "{err:?}");
}
#[skuld::test]
fn raw_refusals_before_create_process_did_not_start() {
use crate::child::spawn::failure::{invalid_input, unsupported};
use crate::stdio::Stdio;
let dir = tempfile::tempdir().expect("tempdir");
let bat = dir.path().join("x.bat");
std::fs::write(&bat, b"@echo off\n").expect("write the batch file");
let mut batch = Command::new();
batch.executable(&bat).args(["x.bat"]);
let mut cwd_nul = Command::new();
cwd_nul
.executable("findstr")
.args(["findstr", "x"])
.current_dir(std::path::PathBuf::from("a\u{0}b"));
let mut line_nul = Command::new();
line_nul.executable("findstr").args(["findstr", "a\u{0}b"]);
let mut oversized = Command::new();
oversized.executable("findstr").args(["findstr", "x"]);
oversized.fd(70_000, Stdio::null()).expect("fd 70000");
let mut inherit_fd3 = Command::new();
inherit_fd3.executable("findstr").args(["findstr", "x"]);
inherit_fd3.fd(3, Stdio::inherit()).expect("fd 3");
for (what, mut cmd, variant) in [
("batch", batch, unsupported as fn(&Error) -> bool),
("cwd NUL", cwd_nul, invalid_input),
("command-line NUL", line_nul, invalid_input),
("oversized fd table", oversized, unsupported),
("inherit on fd 3", inherit_fd3, unsupported),
] {
let err = crate::child::spawn::failure::expect_not_started(cmd.spawn().expect_err(what));
assert!(variant(&err), "{what}: not the refusal's own error: {err:?}");
}
}