use super::Secret;
#[skuld::test]
fn secret_debug_is_redacted() {
let s = Secret::new("hunter2");
let dbg = format!("{s:?}");
assert!(!dbg.contains("hunter2"), "Secret Debug must not leak the value: {dbg}");
assert!(dbg.contains("Secret"), "{dbg}");
}
#[skuld::test]
fn secret_exposes_bytes_for_the_effect_layer() {
let s = Secret::new("pw");
assert_eq!(s.expose(), b"pw");
}
use super::{Auth, Backend, ElevatedStdio, ElevatedVia, ElevationReport, Privilege};
pub(crate) fn report(via: ElevatedVia) -> ElevationReport {
ElevationReport {
via,
stripped_env: Vec::new(),
stdio: ElevatedStdio::Passthrough,
}
}
pub(crate) const VIAS_WITHOUT_A_FRONT: [ElevatedVia; 3] = [
ElevatedVia::Wrapped(Backend::Pkexec),
ElevatedVia::AlreadyElevated,
ElevatedVia::WindowsUac,
];
#[skuld::test]
fn backend_defaults_to_auto() {
assert_eq!(Backend::default(), Backend::Auto);
}
#[skuld::test]
fn auth_defaults_to_interactive() {
assert!(matches!(Auth::default(), Auth::Interactive));
}
#[skuld::test]
fn privilege_variants_are_distinct() {
assert_ne!(Privilege::Unprivileged, Privilege::Elevated);
}
#[skuld::test]
fn elevated_via_distinguishes_windows_uac_from_wrapped() {
assert_ne!(ElevatedVia::WindowsUac, ElevatedVia::Wrapped(Backend::Sudo));
assert_ne!(ElevatedVia::WindowsUac, ElevatedVia::AlreadyElevated);
}
#[skuld::test]
fn elevation_report_holds_achieved_state() {
let r = ElevationReport {
stripped_env: vec!["LD_PRELOAD".into()],
..report(ElevatedVia::Wrapped(Backend::Sudo))
};
assert_eq!(r.via, ElevatedVia::Wrapped(Backend::Sudo));
assert_eq!(r.stripped_env, vec![std::ffi::OsString::from("LD_PRELOAD")]);
assert_eq!(r.stdio, ElevatedStdio::Passthrough);
}
#[skuld::test]
fn already_elevated_report_is_single_sourced() {
let r = super::already_elevated_report(ElevatedStdio::Passthrough);
assert_eq!(r.via, ElevatedVia::AlreadyElevated);
assert!(r.stripped_env.is_empty());
assert_eq!(r.stdio, ElevatedStdio::Passthrough);
}
#[skuld::test]
fn remap_backend_missing_is_backend_unavailable_with_cause() {
use crate::error::{ElevationErrorKind, Error};
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "no such file");
let e = super::remap_derived_spawn_error(Error::Io(io), std::path::Path::new("/nonexistent/sudo"));
match e {
Error::Elevation {
kind: ElevationErrorKind::BackendUnavailable,
detail,
source,
} => {
assert!(
detail.contains("/nonexistent/sudo"),
"detail must name the backend path: {detail}"
);
assert!(
!detail.contains("no such file"),
"the cause is the source, not the detail: {detail}"
);
let source = source.expect("the cause is the source");
assert_eq!(crate::error::said(&*source), crate::error::io_said("no such file"));
}
other => panic!("expected BackendUnavailable, got {other:?}"),
}
}
const OS_CODE: i32 = if cfg!(windows) { 5 } else { 13 };
#[skuld::test]
fn an_unkillable_error_has_the_refusal_as_its_cause() {
use crate::error::{ElevationErrorKind, Error};
let refusal = std::io::Error::from_raw_os_error(OS_CODE);
assert_eq!(
refusal.kind(),
std::io::ErrorKind::PermissionDenied,
"the test's code is a refusal"
);
let text = refusal.to_string();
let e = super::map_elevated_kill_error(refusal, true);
assert_eq!(crate::error::first_os_code(&e), Some(OS_CODE), "{e:?}");
match e {
Error::Elevation {
kind: ElevationErrorKind::Unkillable,
detail,
..
} => assert!(!detail.contains(&text), "the cause is in the detail: {detail}"),
other => panic!("expected Unkillable, got {other:?}"),
}
}
#[skuld::test]
fn a_backend_unavailable_error_has_the_failed_exec_as_its_cause() {
use crate::error::Error;
let e = super::remap_derived_spawn_error(
Error::Io(std::io::Error::from_raw_os_error(OS_CODE)),
std::path::Path::new("/nonexistent/sudo"),
);
assert!(matches!(e, Error::Elevation { .. }), "{e:?}");
assert_eq!(crate::error::first_os_code(&e), Some(OS_CODE), "{e:?}");
}
#[skuld::test]
fn remap_preserves_a_non_backend_io_error() {
use crate::error::Error;
let exe = std::env::current_exe().unwrap();
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "cwd gone");
let e = super::remap_derived_spawn_error(Error::Io(io), &exe);
assert!(
matches!(e, Error::Io(_)),
"a non-backend NotFound must not be remapped: {e:?}"
);
}
#[skuld::test]
fn remap_passes_through_unrelated_errors() {
use crate::error::Error;
let e = super::remap_derived_spawn_error(
Error::Unsupported {
op: "x".into(),
platform: "unix",
detail: "y".into(),
source: None,
},
std::path::Path::new("/nonexistent/sudo"),
);
assert!(matches!(e, Error::Unsupported { .. }));
}
#[cfg(unix)]
#[skuld::test]
fn remap_backend_exists_but_not_executable_is_backend_unavailable() {
use crate::error::{ElevationErrorKind, Error};
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let backend_path = dir.path().join("fake-sudo");
std::fs::write(&backend_path, b"#!/bin/sh\n").unwrap();
std::fs::set_permissions(&backend_path, std::fs::Permissions::from_mode(0o644)).unwrap();
let io = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
let e = super::remap_derived_spawn_error(Error::Io(io), &backend_path);
match e {
Error::Elevation {
kind: ElevationErrorKind::BackendUnavailable,
detail,
..
} => {
assert!(
detail.contains(backend_path.to_str().unwrap()),
"detail must name the backend path: {detail}"
);
}
other => panic!("expected BackendUnavailable for an existing-but-non-executable backend, got {other:?}"),
}
}
#[skuld::test]
fn elevated_stdio_stdin_consumed_variant_exists() {
assert_ne!(ElevatedStdio::StdinConsumed, ElevatedStdio::Passthrough);
assert_ne!(ElevatedStdio::StdinConsumed, ElevatedStdio::OwnConsole);
}
#[cfg(unix)]
#[skuld::test]
fn is_elevated_matches_effective_uid_ground_truth() {
let euid0 = unsafe { libc::geteuid() } == 0;
assert_eq!(super::is_elevated(), euid0, "is_elevated disagreed with geteuid()==0");
}
#[cfg(unix)]
#[skuld::test]
fn detect_finds_backends_on_the_path_it_is_given() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let sudo = dir.path().join("sudo");
std::fs::write(&sudo, "#!/bin/sh\n").expect("write the fake sudo");
std::fs::set_permissions(&sudo, std::fs::Permissions::from_mode(0o755)).expect("chmod");
let h = super::plan::Host::detect(
super::Backend::Auto,
&super::Auth::Interactive,
Some(dir.path().as_os_str()),
false,
);
assert_eq!(h.available.sudo.as_deref(), Some(sudo.as_path()));
}
#[cfg(unix)]
#[skuld::test]
fn detect_reports_the_elevation_it_is_given() {
for elevated in [true, false] {
let h = super::plan::Host::detect(super::Backend::Auto, &super::Auth::Interactive, None, elevated);
assert_eq!(h.elevated, elevated);
}
}
#[cfg(unix)]
#[skuld::test]
fn detect_without_a_path_finds_no_backend_on_the_process_path() {
use std::os::unix::fs::PermissionsExt;
const NAME: &str = "elevation::elevation_tests::detect_without_a_path_finds_no_backend_on_the_process_path";
const INNER: &str = "COSCA_TESTCFG_DETECT_NONE_PATH";
if std::env::var_os(INNER).is_none() {
let dir = tempfile::tempdir().expect("tempdir");
for program in ["sudo", "doas", "pkexec"] {
let fake = dir.path().join(program);
std::fs::write(&fake, "#!/bin/sh\n").expect("write a fake backend");
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).expect("chmod");
}
let out = crate::test_spawn::output_captured(
crate::test_reexec::with_json_events(
crate::test_reexec::command(std::env::current_exe().expect("this test binary")).args([
NAME,
"--exact",
crate::test_reexec::NOCAPTURE,
"--test-threads=1",
]),
)
.env(INNER, "1")
.env("PATH", dir.path()),
)
.expect("run the case alone");
if let Err(why) = crate::test_reexec::suite_passed_exactly_one(&out) {
panic!(
"{why}\n{}\n--- stdout ---\n{}\n--- stderr ---\n{}",
out.status,
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
}
return;
}
let process_path = std::env::var_os("PATH").expect("the outer test sets PATH");
for program in ["sudo", "doas", "pkexec"] {
assert!(
super::posix::resolve_in_path_var(&process_path, program).is_some(),
"the process PATH must hold a {program}, or this test proves nothing"
);
}
for backend in [super::Backend::Auto, super::Backend::Pkexec] {
let h = super::plan::Host::detect(backend, &super::Auth::Interactive, None, false);
assert_eq!(h.available.sudo, None, "{backend:?}");
assert_eq!(h.available.doas, None, "{backend:?}");
assert_eq!(h.available.pkexec, None, "{backend:?}");
}
}
#[cfg(target_os = "linux")]
#[skuld::test]
fn detect_reports_linux() {
let h = super::plan::Host::detect(super::Backend::Auto, &super::Auth::Interactive, None, false);
assert_eq!(h.os, super::plan::Os::Linux);
}
#[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))]
#[skuld::test]
fn detect_reports_unix_os() {
let h = super::plan::Host::detect(super::Backend::Auto, &super::Auth::Interactive, None, false);
assert_eq!(h.os, super::plan::Os::Unix);
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn detect_reports_macos() {
let h = super::plan::Host::detect(super::Backend::Auto, &super::Auth::Interactive, None, false);
assert_eq!(h.os, super::plan::Os::MacOs);
assert!(
h.available.osascript.is_some(),
"a macOS host must resolve /usr/bin/osascript"
);
assert!(h.arg_max.is_some(), "kern.argmax must be readable on macOS");
}
#[skuld::test]
fn kill_error_on_an_elevated_wrapper_is_unkillable() {
use crate::error::{ElevationErrorKind, Error};
let eperm = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
let e = super::map_elevated_kill_error(eperm, true);
assert!(
matches!(
e,
Error::Elevation {
kind: ElevationErrorKind::Unkillable,
..
}
),
"{e:?}"
);
}
#[skuld::test]
fn kill_error_on_a_plain_child_stays_io() {
use crate::error::Error;
let eperm = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
assert!(matches!(super::map_elevated_kill_error(eperm, false), Error::Io(_)));
}
#[skuld::test]
fn non_permission_kill_error_stays_io_even_when_elevated() {
use crate::error::Error;
let other = std::io::Error::from(std::io::ErrorKind::NotFound);
assert!(matches!(super::map_elevated_kill_error(other, true), Error::Io(_)));
}
#[skuld::test]
fn the_shared_argv_gate_refuses_each_rule_with_the_backends_words() {
use crate::command::Command;
use crate::error::Error;
use crate::test_child::Console;
const WORDS: super::ArgvRefusals = super::ArgvRefusals {
platform: "test",
op_prefix: "test elevation",
commandline: "no command lines here",
setter: "argv[0] only here",
};
let refusal = |c: &Command| match super::elevation_argv(c, &WORDS) {
Err(Error::Unsupported {
op, platform, detail, ..
}) => {
assert_eq!(platform, "test");
format!("{op} / {detail}")
}
other => panic!("expected Unsupported, got {other:?}"),
};
type Set = fn(&mut Command, &str);
let setters: [(&str, Set); 2] = [
("executable", |c, p| {
c.executable(p);
}),
("raw_executable", |c, p| {
c.raw_executable(p);
}),
];
for (name, set) in setters {
let mut matching = crate::test_child::command(Console::Hidden);
matching.args(["/usr/bin/id", "-u"]);
let mut distinct = crate::test_child::command(Console::Hidden);
distinct.args(["not-id"]);
let mut line = crate::test_child::command(Console::Hidden);
line.commandline("id -u");
let mut empty_argv = crate::test_child::command(Console::Hidden);
empty_argv.args::<[&str; 0], &str>([]);
for (what, mut c) in [
("argv[0] == program", matching),
("argv[0] != program", distinct),
("commandline()", line),
("an empty argv", empty_argv),
("no input", crate::test_child::command(Console::Hidden)),
] {
set(&mut c, "/usr/bin/id");
assert_eq!(
refusal(&c),
format!("test elevation of a program set by {name}() / argv[0] only here"),
"{name}() with {what}"
);
}
}
let mut empty_argv = crate::test_child::command(Console::Hidden);
empty_argv.args::<[&str; 0], &str>([]);
for no_program in [crate::test_child::command(Console::Hidden), empty_argv] {
assert_eq!(
refusal(&no_program),
"test elevation of an empty command / set a program via .args([...]) before .elevate()"
);
}
let mut line = crate::test_child::command(Console::Hidden);
line.commandline("id -u");
assert_eq!(
refusal(&line),
"test elevation of a commandline() command / no command lines here"
);
let mut ok = crate::test_child::command(Console::Hidden);
ok.args(["/usr/bin/id", "-u"]);
assert_eq!(super::elevation_argv(&ok, &WORDS).expect("accepted").len(), 2);
}