use super::*;
#[cfg(unix)]
use crate::test_groups::{root, Group};
skuld::default_labels!(crate::test_harness::ROOT);
#[skuld::test]
fn absolute_names_by_grammar() {
for (name, windows, want) in [
(r"C:\t\tool", true, true),
("C:/t/tool", true, true),
(r"\\srv\shr\tool", true, true),
(r"\\?\C:\t\tool", true, true),
(r"\\.\dev\tool", true, true),
(r"\\?\UNC\srv\shr\tool", true, true),
(r"\\?\UNC\srv\shr", true, true),
(r"\\?\UNC\srv", true, false),
(r"\\?\Unc\srv", true, false),
(r"\\?\unc\srv\shr\tool", true, true),
(r"\\?\UNC\srv\", true, false),
(r"\\?\UNC\", true, false),
(r"\\?\UNC\\shr", true, false),
(r"\\?\UNC\srv/shr", true, false),
(r"\\?\UNC/srv", true, true),
(r"\\?\UNC/srv\tool.exe", true, true),
(r"\\srv", true, false),
(r"\t\tool", true, false),
("C:tool", true, false),
(r"t\tool", true, false),
("tool", true, false),
("/t/tool", false, true),
("t/tool", false, false),
(r"C:\t\tool", false, false),
] {
assert_eq!(
is_absolute_name(OsStr::new(name), windows),
want,
"{name:?} (windows: {windows})"
);
}
}
#[skuld::test]
fn an_absolute_name_needs_no_base() {
let dir = tempfile::tempdir().unwrap();
let tool = dir.path().join("tool");
std::fs::write(&tool, b"x").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let got = resolve(ResolveInput {
program: &tool,
cwd: None,
system_dirs: &no_system_dirs,
path_var: None,
windows: cfg!(windows),
loadable_only: false,
normalise: &as_written,
});
assert_eq!(got.unwrap(), tool);
}
#[skuld::test]
fn a_bare_name_needs_no_base() {
let dir = tempfile::tempdir().unwrap();
let name = if cfg!(windows) { "tool.exe" } else { "tool" };
let tool = dir.path().join(name);
std::fs::write(&tool, b"x").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let got = resolve(ResolveInput {
program: Path::new("tool"),
cwd: None,
system_dirs: &no_system_dirs,
path_var: Some(dir.path().as_os_str()),
windows: cfg!(windows),
loadable_only: false,
normalise: &as_written,
});
assert_eq!(got.unwrap(), tool);
}
#[skuld::test]
fn a_unc_shaped_name_with_no_share_is_refused() {
for name in [
r"\\tool.exe",
"//tool.exe",
r"\/tool.exe",
r"/\tool.exe",
r"\\srv\\x.exe",
] {
let got = resolve(ResolveInput {
program: Path::new(name),
cwd: None,
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &as_written,
});
match got {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{name:?}: {e}"),
other => panic!("{name:?} must be refused, got {other:?}"),
}
}
}
#[skuld::test]
fn which_names_need_a_base() {
for (name, want) in [
(r"sub\tool.exe", true),
(r".\tool.exe", true),
(r"\tool.exe", true),
("tool.exe", false),
(r"C:\t\tool.exe", false),
(r"\\srv\shr\tool.exe", false),
("C:tool.exe", false),
(r"\\tool.exe", false),
] {
assert_eq!(needs_base(OsStr::new(name), true), want, "{name:?}");
}
assert!(needs_base(OsStr::new("sub/tool"), false));
assert!(!needs_base(OsStr::new("/t/tool"), false));
}
#[skuld::test]
fn path_types_as_win32_reads_them() {
use PathType::*;
for (name, want) in [
(r"\\srv\shr\x", Unc),
("//x", Unc),
(r"\/x", Unc),
(r"\\?\C:\x", Unc),
(r"C:\x", DriveAbsolute),
("C:/x", DriveAbsolute),
("C:x", DriveRelative),
("1:tool.exe", DriveRelative),
("\u{e9}:x", DriveRelative),
(r"C:D:\x", DriveRelative),
("::x", DriveRelative),
(r"\x", Rooted),
(r"\:x.exe", Rooted),
("/:x.exe", Rooted),
(r"\:\x.exe", Rooted),
("x", Relative),
(r"sub\x", Relative),
("\u{1f600}:x", Relative),
] {
assert_eq!(path_type(OsStr::new(name)), want, "{name:?}");
}
}
#[skuld::test]
fn a_lone_surrogate_is_a_drive() {
for (rest, want) in [
(&b":x"[..], PathType::DriveRelative),
(br":\x", PathType::DriveAbsolute),
] {
let bytes = [&[0xED, 0xA0, 0x80][..], rest].concat();
assert_eq!(drive_len(&bytes), Some(4), "{bytes:?}");
let name = unsafe { OsStr::from_encoded_bytes_unchecked(&bytes) };
assert_eq!(path_type(name), want, "{bytes:?}");
}
}
#[skuld::test]
fn a_digit_drive_is_drive_relative_everywhere() {
let name = OsStr::new("1:tool.exe");
assert_eq!(classify(name, true), Shape::Located);
assert!(is_drive_relative(name, true));
assert!(!is_absolute_name(name, true));
assert!(!needs_base(name, true));
let got = resolve(ResolveInput {
program: Path::new(name),
cwd: None,
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &as_written,
});
match got {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{e}"),
other => panic!("expected InvalidInput, got {other:?}"),
}
}
#[skuld::test]
fn a_leading_separator_is_never_a_drive_prefix() {
assert_eq!(windows_prefix_len(br"\:x"), 0);
assert_eq!(windows_prefix_len(b"1:x"), 2);
assert_eq!(windows_prefix_len("\u{e9}:x".as_bytes()), 3);
}
#[skuld::test]
#[should_panic(expected = "needs a base")]
fn a_located_name_without_a_base_is_a_contract_violation() {
_ = resolve(ResolveInput {
program: Path::new("sub/tool"),
cwd: None,
system_dirs: &no_system_dirs,
path_var: None,
windows: false,
loadable_only: false,
normalise: &as_written,
});
}
#[skuld::test]
fn candidates_join_by_the_one_classifier() {
let sep = std::path::MAIN_SEPARATOR_STR;
for (dir, candidate, want) in [
(r"1:\work", r"\tool.exe", r"1:\tool.exe".to_owned()),
(r"1:\work", "tool.exe", format!(r"1:\work{sep}tool.exe")),
(r"1:\work\", "tool.exe", r"1:\work\tool.exe".to_owned()),
(r"\\srv\shr\d", r"\t.exe", r"\\srv\shr\t.exe".to_owned()),
("C:", "tool.exe", "C:tool.exe".to_owned()),
("", r"C:\t.exe", r"C:\t.exe".to_owned()),
(r"\\?\C:\work", "./t.exe", r"\\?\C:\work\t.exe".to_owned()),
(r"\\?\C:\work", "sub/../t.exe", r"\\?\C:\work\t.exe".to_owned()),
(r"\\?\C:\work", "/t.exe", r"\\?\C:\t.exe".to_owned()),
] {
assert_eq!(
join_candidate(Path::new(dir), OsStr::new(candidate), true),
PathBuf::from(&want),
"{dir:?} + {candidate:?}"
);
}
}
#[skuld::test]
fn a_candidate_is_accepted_when_fully_qualified() {
for (joined, want) in [
(r"1:\tool.exe", true),
(r"C:\tool.exe", true),
(r"\\srv\shr\tool.exe", true),
("C:tool.exe", false),
(r"\tool.exe", false),
("tool.exe", false),
] {
assert_eq!(accepted(Path::new(joined), true), want, "{joined:?}");
}
}
#[cfg(unix)]
fn windows_path_var(first: &Path, second: &Path) -> std::ffi::OsString {
use std::os::unix::ffi::OsStrExt;
for dir in [first, second] {
assert!(
!dir.as_os_str().as_bytes().contains(&b'"'),
"precondition: {dir:?} must not contain a `\"` — NTFS forbids it, and the Windows \
PATH grammar cannot express one"
);
}
let mut path = std::ffi::OsString::from("\"");
path.push(first);
path.push("\";\"");
path.push(second);
path.push("\"");
path
}
#[cfg(unix)]
#[skuld::test]
fn windows_path_var_resolves_two_ordinary_directories() {
let first = tempfile::tempdir().unwrap();
let second = tempfile::tempdir().unwrap();
std::fs::write(second.path().join("tool.exe"), b"x").unwrap();
let path = windows_path_var(first.path(), second.path());
assert_eq!(search_tool(&path, false).unwrap(), second.path().join("tool.exe"));
}
#[cfg(unix)]
#[skuld::test]
fn windows_path_var_resolves_a_directory_whose_name_contains_the_separator() {
let first = tempfile::tempdir().unwrap();
let second = tempfile::Builder::new().prefix("has;semicolon").tempdir().unwrap();
std::fs::write(second.path().join("tool.exe"), b"x").unwrap();
let path = windows_path_var(first.path(), second.path());
assert_eq!(search_tool(&path, false).unwrap(), second.path().join("tool.exe"));
}
#[cfg(unix)]
#[skuld::test]
#[should_panic(expected = "must not contain a `\"`")]
fn windows_path_var_refuses_a_component_holding_a_quote() {
windows_path_var(Path::new("/tmp/has\"quote"), Path::new("/tmp/b"));
}
#[cfg(unix)]
fn loop_then_open() -> (tempfile::TempDir, PathBuf, std::ffi::OsString) {
let root = tempfile::tempdir().unwrap();
let looping = root.path().join("loop");
std::os::unix::fs::symlink("loop", &looping).unwrap();
let open = root.path().join("open");
std::fs::create_dir(&open).unwrap();
std::fs::write(open.join("tool.exe"), b"x").unwrap();
let candidate = looping.join("tool.exe");
let e = std::fs::metadata(&candidate).unwrap_err();
assert!(
!is_absence(&e),
"precondition: {candidate:?} must be undeterminable, not a definite absence: {e}"
);
let path = windows_path_var(&looping, &open);
(root, open, path)
}
#[cfg(unix)]
struct Locked(PathBuf, crate::test_child::RestoreMode);
#[cfg(unix)]
impl Locked {
fn new(dir: PathBuf) -> Self {
use std::os::unix::fs::PermissionsExt;
let restore = crate::test_child::RestoreMode::new(&dir, 0o755);
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o000)).unwrap();
Locked(dir, restore)
}
}
#[cfg(unix)]
fn locked_then_open() -> (tempfile::TempDir, Locked, PathBuf, std::ffi::OsString) {
let root = crate::test_child::fixture_scratch_tempdir();
let locked = root.path().join("locked");
let open = root.path().join("open");
std::fs::create_dir(&locked).unwrap();
std::fs::create_dir(&open).unwrap();
std::fs::write(open.join("tool.exe"), b"x").unwrap();
let locked = Locked::new(locked);
let candidate = locked.0.join("tool.exe");
let e = std::fs::metadata(&candidate).unwrap_err();
assert_eq!(
e.raw_os_error(),
Some(libc::EACCES),
"precondition: {candidate:?} must be denied to this caller, not {e} — did the caller \
forget run_fixture?"
);
let path = windows_path_var(&locked.0, &open);
(root, locked, open, path)
}
#[cfg(unix)]
fn search_tool(path_var: &OsStr, loadable_only: bool) -> Result<PathBuf, Error> {
resolve(ResolveInput {
program: Path::new("tool"),
cwd: None,
system_dirs: &no_system_dirs,
path_var: Some(path_var),
windows: true,
loadable_only,
normalise: &as_written,
})
}
#[cfg(unix)]
const FIXTURE_STAT_TARGET_ENV: &str = "COSCA_FIXTURE_STAT_TARGET";
#[cfg(unix)]
const STAT_ERRNO_PREFIX: &str = "COSCA_FIXTURE_STAT_ERRNO=";
#[cfg(unix)]
#[skuld::test]
fn fixture_stat_errno_probe() {
use std::io::Write as _;
let Some(target) = std::env::var_os(FIXTURE_STAT_TARGET_ENV) else {
return; };
if !crate::test_child::is_fixture_reexec() {
return;
}
let errno = std::fs::metadata(&target)
.err()
.map_or(0, |e| e.raw_os_error().unwrap_or(-1));
writeln!(std::io::stderr(), "{STAT_ERRNO_PREFIX}{errno}").expect("report the errno");
}
#[cfg(unix)]
fn stat_errno_via_grandchild(target: &Path) -> Option<i32> {
let child = crate::test_spawn::spawn(
crate::test_child::fixture_command(crate::test_child::fixture_path!(fixture_stat_errno_probe))
.env(FIXTURE_STAT_TARGET_ENV, target),
)
.expect("spawn the stat probe");
let output = child.wait_with_output().expect("wait for the stat probe");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
output.status.success() && stderr.contains(crate::test_child::FIXTURE_GATE_PASSED_LINE),
"the stat probe did not run: {output:?}"
);
let errno: i32 = stderr
.lines()
.find_map(|l| l.strip_prefix(STAT_ERRNO_PREFIX))
.unwrap_or_else(|| panic!("the stat probe reported no errno: {stderr}"))
.parse()
.expect("the reported errno is a number");
(errno != 0).then_some(errno)
}
#[cfg(unix)]
#[skuld::test]
fn an_undeterminable_candidate_fails_a_loadable_only_search_closed() {
let (_root, _open, path) = loop_then_open();
match search_tool(&path, true) {
Err(e @ Error::Io(_)) => assert_eq!(crate::error::first_os_code(&e), Some(libc::ELOOP), "{e}"),
other => panic!("a loadable_only search must not skip an undeterminable candidate: {other:?}"),
}
}
#[cfg(unix)]
#[skuld::test]
fn a_denied_candidate_fails_a_loadable_only_search_closed() {
crate::test_child::run_fixture(crate::test_child::fixture_path!(
fixture_a_denied_candidate_fails_a_loadable_only_search_closed
));
}
#[cfg(unix)]
#[skuld::test]
fn fixture_a_denied_candidate_fails_a_loadable_only_search_closed() {
if !crate::test_child::is_fixture_reexec() {
return; }
let (_root, _locked, _open, path) = locked_then_open();
match search_tool(&path, true) {
Err(e @ Error::Io(_)) => assert_eq!(crate::error::first_os_code(&e), Some(libc::EACCES), "{e}"),
other => panic!("a loadable_only search must not skip an undeterminable candidate: {other:?}"),
}
}
#[cfg(unix)]
#[skuld::test]
fn an_undeterminable_candidate_is_skipped_by_an_ordinary_search() {
let (_root, open, path) = loop_then_open();
assert_eq!(search_tool(&path, false).unwrap(), open.join("tool.exe"));
}
#[cfg(unix)]
#[skuld::test]
fn a_denied_candidate_is_skipped_by_an_ordinary_search() {
crate::test_child::run_fixture(crate::test_child::fixture_path!(
fixture_a_denied_candidate_is_skipped_by_an_ordinary_search
));
}
#[cfg(unix)]
#[skuld::test]
fn fixture_a_denied_candidate_is_skipped_by_an_ordinary_search() {
if !crate::test_child::is_fixture_reexec() {
return; }
let (_root, _locked, open, path) = locked_then_open();
assert_eq!(search_tool(&path, false).unwrap(), open.join("tool.exe"));
}
#[cfg(unix)]
#[skuld::test(labels = [])]
fn a_denied_candidate_is_denied_by_an_exec_child(#[fixture(root)] _group: &Group) {
crate::test_privilege::assert_holds_dac_bypass();
crate::test_child::run_fixture(crate::test_child::fixture_path!(
fixture_a_denied_candidate_is_denied_by_an_exec_child
));
}
#[cfg(unix)]
#[skuld::test]
fn fixture_a_denied_candidate_is_denied_by_an_exec_child() {
if !crate::test_child::is_fixture_reexec() {
return; }
let (_root, locked, open, _path) = locked_then_open();
assert_eq!(
stat_errno_via_grandchild(&open.join("tool.exe")),
None,
"positive control: an exec'd child must reach the unlocked directory, or a denial below \
proves nothing"
);
let errno = stat_errno_via_grandchild(&locked.0.join("tool.exe"));
assert_eq!(
errno,
Some(libc::EACCES),
"an exec'd child must not regain access this process was denied"
);
}
#[skuld::test]
fn only_definite_misses_count_as_absent() {
#[cfg(windows)]
let cases = [
(2, true),
(3, true),
(15, true),
(123, true),
(161, true),
(267, true),
(5, false),
(21, false),
(53, false),
(67, false),
];
#[cfg(unix)]
let cases = [
(libc::ENOENT, true),
(libc::ENOTDIR, true),
(libc::EACCES, false),
(libc::EIO, false),
];
for (code, want) in cases {
let e = std::io::Error::from_raw_os_error(code);
assert_eq!(is_absence(&e), want, "{e}");
}
}
#[cfg(unix)]
#[skuld::test]
fn only_a_denied_or_absent_execute_check_is_a_no() {
assert!(execute_permission(0, 0).unwrap());
for errno in [libc::EACCES, libc::ENOENT, libc::ENOTDIR] {
assert!(!execute_permission(-1, errno).unwrap(), "errno {errno}");
}
for errno in [libc::EIO, libc::ELOOP, libc::ENOMEM] {
let e = execute_permission(-1, errno).unwrap_err();
assert_eq!(e.raw_os_error(), Some(errno));
}
}
#[skuld::test]
#[should_panic(expected = "must be fully qualified")]
fn a_relative_windows_base_is_a_contract_violation() {
_ = resolve(ResolveInput {
program: Path::new(r"sub\tool.exe"),
cwd: Some(Path::new("rel")),
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &as_written,
});
}
#[cfg(debug_assertions)] #[skuld::test]
#[should_panic(expected = "loadable_only is a Windows rule")]
fn loadable_only_on_the_posix_grammar_is_a_contract_violation() {
_ = resolve(ResolveInput {
program: Path::new("tool"),
cwd: None,
system_dirs: &no_system_dirs,
path_var: None,
windows: false,
loadable_only: true,
normalise: &as_written,
});
}
#[skuld::test]
fn a_candidate_made_verbatim_by_its_base_is_normalised() {
let dir = tempfile::tempdir().unwrap();
let tool = dir.path().join("tool.exe");
std::fs::write(&tool, b"x").unwrap();
let seen = std::cell::RefCell::new(Vec::new());
let normalise = |p: &Path| {
seen.borrow_mut().push(p.to_path_buf());
Ok(tool.clone())
};
let got = resolve(ResolveInput {
program: Path::new(r"sub.\tool.exe"),
cwd: Some(Path::new(r"\\?\C:\d")),
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &normalise,
});
assert_eq!(got.unwrap(), tool);
assert_eq!(*seen.borrow(), [PathBuf::from(r"\\?\C:\d\sub.\tool.exe")]);
}
#[skuld::test]
fn a_candidate_made_verbatim_by_its_base_is_joined_as_written() {
let seen = std::cell::RefCell::new(Vec::new());
let normalise = |p: &Path| {
seen.borrow_mut().push(p.to_path_buf());
Ok(p.to_path_buf())
};
_ = resolve(ResolveInput {
program: Path::new(r"..\..\..\t.exe"),
cwd: Some(Path::new(r"\\?\UNC\srv\shr\d")),
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &normalise,
});
assert_eq!(*seen.borrow(), [PathBuf::from(r"\\?\UNC\srv\shr\d\..\..\..\t.exe")]);
}
#[skuld::test]
fn a_rooted_name_on_a_verbatim_base_is_refused() {
let never = |p: &Path| -> std::io::Result<PathBuf> { panic!("{p:?} must not be probed") };
for cwd in [r"\\?\UNC\srv\shr\d", r"\\?\C:\d"] {
let got = resolve(ResolveInput {
program: Path::new(r"\t.exe"),
cwd: Some(Path::new(cwd)),
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &never,
});
match got {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{cwd:?}: {e}"),
other => panic!("{cwd:?}: must be refused, got {other:?}"),
}
}
}
#[skuld::test]
fn only_a_verbatim_base_makes_a_candidate_normalised() {
let never = |p: &Path| -> std::io::Result<PathBuf> { panic!("{p:?} must not be normalised") };
for (program, cwd) in [
(r"\\?\C:\d\sub.\tool.exe", None),
(r"sub.\tool.exe", Some(Path::new(r"C:\d"))),
] {
let got = resolve(ResolveInput {
program: Path::new(program),
cwd,
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &never,
});
match got {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "{program:?}: {e}"),
other => panic!("{program:?} must miss, got {other:?}"),
}
}
}
#[skuld::test]
fn a_verbatim_search_directory_is_taken_as_written() {
let never = |p: &Path| -> std::io::Result<PathBuf> { panic!("{p:?} must not be normalised") };
let system = [PathBuf::from(r"\\?\C:\a\..\b")];
let system_fn = || -> Result<Vec<PathBuf>, Error> { Ok(system.to_vec()) };
let got = resolve(ResolveInput {
program: Path::new("tool"),
cwd: None,
system_dirs: &system_fn,
path_var: Some(OsStr::new(r"\\?\C:\x\bin.")),
windows: true,
loadable_only: false,
normalise: &never,
});
match got {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "{e}"),
other => panic!("nothing is on disk there, got {other:?}"),
}
}
#[skuld::test]
fn a_verbatim_unc_marker_needs_a_backslash() {
assert_eq!(
windows_prefix_len(br"\\?\UNC\srv\shr\tool.exe"),
r"\\?\UNC\srv\shr".len()
);
assert_eq!(windows_prefix_len(br"\\?\UNC/srv\tool.exe"), r"\\?\UNC".len());
assert_eq!(windows_prefix_len(br"\\?\UNC/srv"), r"\\?\UNC".len());
}
#[skuld::test]
fn a_normalised_candidate_that_names_no_file_is_refused() {
for completed in [r"\\?\UNC\srv\t.exe", r"\\?\UNC\t.exe", r"\\?\t.exe"] {
let normalise = |_: &Path| Ok(PathBuf::from(completed));
let got = resolve(ResolveInput {
program: Path::new(r"..\..\t.exe"),
cwd: Some(Path::new(r"\\?\UNC\srv\shr\d")),
system_dirs: &no_system_dirs,
path_var: None,
windows: true,
loadable_only: false,
normalise: &normalise,
});
match got {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{completed:?}: {e}"),
other => panic!("{completed:?} must be refused, got {other:?}"),
}
}
}