use std::ffi::{OsStr, OsString};
use crate::test_child::Console;
use std::path::Path;
use super::{build_rewrite, build_shell_command, reject_structural_gui_config, wrap_do_shell_script};
use crate::command::{Command, CommandInput};
use crate::elevation::{ElevatedStdio, ElevatedVia};
use crate::error::{ElevationErrorKind, Error, QuoteErrorKind};
#[cfg(unix)]
#[path = "macos_tests/shim_script.rs"]
mod shim_script;
fn args(v: &[&str]) -> Vec<OsString> {
v.iter().map(OsString::from).collect()
}
fn shell(program: &str, a: &[&str], cwd: Option<&str>) -> String {
let bytes = build_shell_command(OsStr::new(program), &args(a), cwd.map(Path::new)).unwrap();
String::from_utf8(bytes).unwrap()
}
fn gate(c: &Command) -> Result<(), Error> {
reject_structural_gui_config(c)
}
fn build(c: &mut Command, arg_max: Option<usize>) -> Result<Command, Error> {
let launch = super::program_and_args(c)?;
build_rewrite(
c,
launch,
Path::new("/usr/bin/osascript"),
arg_max,
super::osascript_report(),
)
}
fn gui_cmd() -> Command {
let mut c = crate::test_child::command(Console::Hidden);
c.args(["/usr/bin/id", "-u"])
.elevation_auth(crate::elevation::Auth::Gui);
c
}
fn assert_rejected(c: &Command, needle: &str) {
match gate(c) {
Err(Error::Unsupported { platform, detail, .. }) => {
assert_eq!(platform, "macos");
assert!(detail.contains(needle), "detail {detail:?} must mention {needle:?}");
}
other => panic!("expected a macos Unsupported mentioning {needle:?}, got {other:?}"),
}
}
#[skuld::test]
fn the_shell_command_execs_the_quoted_argv() {
assert_eq!(shell("/usr/bin/id", &["-u"], None), "exec /usr/bin/id -u");
}
#[skuld::test]
fn every_argv_element_is_shell_quoted() {
assert_eq!(
shell("/bin/echo", &["a b", "it's", "$HOME", "`id`"], None),
r#"exec /bin/echo 'a b' 'it'"'"'s' '$HOME' '`id`'"#
);
}
#[skuld::test]
fn a_working_directory_becomes_an_explicit_cd() {
assert_eq!(
shell("/usr/bin/id", &[], Some("/tmp/a dir")),
"cd -P -- '/tmp/a dir' && exec /usr/bin/id"
);
}
#[skuld::test]
fn the_script_is_a_single_do_shell_script_statement() {
let cmd = build_shell_command(OsStr::new("/usr/bin/id"), &args(&["-u"]), None).unwrap();
assert_eq!(
wrap_do_shell_script(&cmd, None).unwrap(),
"do shell script \"exec /usr/bin/id -u\" \
with administrator privileges without altering line endings"
);
}
#[skuld::test]
fn both_quoting_layers_compose() {
let cmd = build_shell_command(OsStr::new("/bin/echo"), &args(&[r#"he said "hi""#]), None).unwrap();
assert_eq!(
wrap_do_shell_script(&cmd, None).unwrap(),
"do shell script \"exec /bin/echo 'he said \\\"hi\\\"'\" \
with administrator privileges without altering line endings"
);
}
#[skuld::test]
fn non_utf8_argv_is_rejected_before_it_can_be_mangled() {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
let bad = OsString::from_vec(vec![b'a', 0xff]);
let cmd = build_shell_command(OsStr::new("/bin/echo"), &[bad], None).unwrap();
let e = wrap_do_shell_script(&cmd, None).unwrap_err();
assert!(
matches!(e, Error::Quote(ref q) if q.kind == QuoteErrorKind::NonUtf8),
"{e}"
);
}
}
#[skuld::test]
fn non_ascii_passes_through_unaltered() {
let cmd = build_shell_command(
OsStr::new("/bin/echo"),
&args(&["\u{4e2d}\u{6587}.txt", "caf\u{e9}", "\u{1f389}"]),
None,
)
.unwrap();
let script = wrap_do_shell_script(&cmd, None).unwrap();
assert!(script.contains("\u{4e2d}\u{6587}.txt"), "{script}");
assert!(script.contains("\u{1f389}"), "{script}");
}
#[cfg(windows)]
#[skuld::test]
fn an_os_string_with_no_byte_form_is_a_typed_error_not_a_panic() {
use std::os::windows::ffi::OsStringExt;
let lone_surrogate = OsString::from_wide(&[0xD800]);
let e = build_shell_command(OsStr::new("/bin/echo"), &[lone_surrogate], None).unwrap_err();
assert!(
matches!(e, Error::Quote(ref q) if q.kind == QuoteErrorKind::NonUtf8),
"{e}"
);
let with_prefix = OsString::from_wide(&[0x006F, 0x006B, 0xD800]);
let e = build_shell_command(OsStr::new("/bin/echo"), &[with_prefix], None).unwrap_err();
match e {
Error::Quote(q) => {
assert_eq!(q.kind, QuoteErrorKind::NonUtf8);
assert_eq!(q.pos, 2, "the offset must point at the first unrepresentable unit");
}
other => panic!("expected a Quote error, got {other:?}"),
}
let multibyte = OsString::from_wide(&[0x00E9, 0xD800]);
let e = build_shell_command(OsStr::new("/bin/echo"), &[multibyte], None).unwrap_err();
match e {
Error::Quote(q) => assert_eq!(q.pos, 2),
other => panic!("expected a Quote error, got {other:?}"),
}
}
fn script_len_for_arg(n: usize) -> usize {
let cmd = build_shell_command(OsStr::new("/bin/echo"), &[OsString::from("x".repeat(n))], None).unwrap();
wrap_do_shell_script(&cmd, None).unwrap().len()
}
#[skuld::test]
fn the_length_guard_accepts_exactly_arg_max_and_rejects_one_more() {
let n = 1000;
let exact = script_len_for_arg(n);
let cmd = build_shell_command(OsStr::new("/bin/echo"), &[OsString::from("x".repeat(n))], None).unwrap();
assert!(
wrap_do_shell_script(&cmd, Some(exact)).is_ok(),
"a script of exactly arg_max bytes must be accepted"
);
match wrap_do_shell_script(&cmd, Some(exact - 1)) {
Err(Error::Elevation { kind, detail, .. }) => {
assert_eq!(kind, ElevationErrorKind::CommandTooLong);
assert!(detail.contains(&exact.to_string()), "{detail}");
assert!(detail.contains(&(exact - 1).to_string()), "{detail}");
}
other => panic!("expected CommandTooLong, got {other:?}"),
}
}
#[skuld::test]
fn an_unknown_arg_max_disables_the_guard_rather_than_guessing() {
let cmd = build_shell_command(OsStr::new("/bin/echo"), &[OsString::from("x".repeat(9_000))], None).unwrap();
assert!(wrap_do_shell_script(&cmd, None).is_ok());
}
#[skuld::test]
fn a_plain_argv_command_is_accepted() {
assert!(gui_cmd().kill_on_drop_flag(), "the builder default is assumed here");
assert!(gate(&gui_cmd()).is_ok());
}
#[skuld::test]
fn a_relative_program_is_rejected_so_roots_path_never_chooses_the_binary() {
let mut c = crate::test_child::command(Console::Hidden);
c.args(["mytool", "--apply"])
.elevation_auth(crate::elevation::Auth::Gui);
assert_rejected(&c, "absolute");
}
#[skuld::test]
fn absoluteness_is_judged_by_posix_rules_not_the_build_hosts() {
let mut ok = crate::test_child::command(Console::Hidden);
ok.args(["/usr/bin/id"]).elevation_auth(crate::elevation::Auth::Gui);
assert!(gate(&ok).is_ok());
let mut windows_style = crate::test_child::command(Console::Hidden);
windows_style
.args([r"C:\tool.exe"])
.elevation_auth(crate::elevation::Auth::Gui);
assert_rejected(&windows_style, "absolute");
}
#[skuld::test]
fn a_relative_working_directory_is_rejected() {
let mut c = gui_cmd();
c.current_dir("subdir");
assert_rejected(&c, "absolute");
}
#[skuld::test]
fn containment_is_rejected_because_the_payload_leaves_our_tree() {
let mut c = gui_cmd();
c.contain();
assert_rejected(&c, "trampoline");
}
#[skuld::test]
fn env_forwarding_is_rejected() {
let mut c = gui_cmd();
c.env("A", "1");
assert_rejected(&c, "environment");
}
#[skuld::test]
fn a_high_fd_is_rejected() {
let mut c = gui_cmd();
c.fd(3, crate::Stdio::null()).unwrap();
assert_rejected(&c, "fd >= 3");
}
#[skuld::test]
fn only_null_and_inherit_are_accepted_on_stdin() {
let mut piped = gui_cmd();
piped.stdin(crate::Stdio::pipe()).unwrap();
assert_rejected(&piped, "stdin");
let f = tempfile::tempfile().expect("tempfile");
let mut filed = gui_cmd();
filed.stdin(crate::Stdio::from_file(f)).unwrap();
assert_rejected(&filed, "stdin");
let mut merged = gui_cmd();
merged.stdout(crate::Stdio::pipe()).unwrap();
merged.stdin(crate::Stdio::merge(crate::Fd::STDOUT)).unwrap();
assert_rejected(&merged, "stdin");
for allowed in [crate::Stdio::null(), crate::Stdio::inherit()] {
let mut ok = gui_cmd();
ok.stdin(allowed).unwrap();
assert!(gate(&ok).is_ok());
}
}
#[skuld::test]
fn stdout_and_stderr_may_be_captured_because_they_carry_the_relay() {
let mut c = gui_cmd();
c.stdout(crate::Stdio::pipe()).unwrap();
c.stderr(crate::Stdio::pipe()).unwrap();
c.stdin(crate::Stdio::null()).unwrap();
assert!(gate(&c).is_ok(), "output()/read() must be usable");
}
#[skuld::test]
fn a_commandline_command_is_rejected() {
let mut c = crate::test_child::command(Console::Hidden);
c.commandline("id -u").elevation_auth(crate::elevation::Auth::Gui);
assert_rejected(&c, "argv");
}
#[skuld::test]
fn an_empty_command_is_rejected() {
let mut fresh = crate::test_child::command(Console::Hidden);
fresh.elevation_auth(crate::elevation::Auth::Gui);
assert_rejected(&fresh, "program");
let mut empty_argv = crate::test_child::command(Console::Hidden);
empty_argv
.args::<[&str; 0], &str>([])
.elevation_auth(crate::elevation::Auth::Gui);
assert!(
matches!(empty_argv.input(), CommandInput::Argv(v) if v.is_empty()),
"this test only means something if .args([]) really yields Argv(vec![])"
);
assert_rejected(&empty_argv, "program");
}
#[cfg(windows)]
#[skuld::test]
fn the_gate_reports_a_byte_formless_program_as_a_quote_error() {
use std::os::windows::ffi::OsStringExt;
let mut c = crate::test_child::command(Console::Hidden);
c.args([OsString::from_wide(&[0xD800])])
.elevation_auth(crate::elevation::Auth::Gui);
let e = gate(&c).unwrap_err();
assert!(
matches!(e, Error::Quote(ref q) if q.kind == QuoteErrorKind::NonUtf8),
"{e}"
);
}
#[skuld::test]
fn argv0_yields_that_program_and_the_remaining_args() {
let mut c = crate::test_child::command(Console::Hidden);
c.args(["/usr/bin/id", "-u", "-r"])
.elevation_auth(crate::elevation::Auth::Gui);
let launch = super::program_and_args(&c).expect("an argv program");
assert_eq!(launch.program, OsString::from("/usr/bin/id"));
assert_eq!(launch.args, args(&["-u", "-r"]));
}
#[skuld::test]
fn the_derived_command_is_osascript_dash_e_with_one_script_argument() {
let mut c = gui_cmd();
let derived = build(&mut c, None).unwrap();
let CommandInput::Argv(argv) = derived.input() else {
panic!("derived command must be an argv");
};
assert_eq!(argv.len(), 3, "exactly osascript, -e, and ONE script argument");
assert_eq!(argv[0], OsString::from("/usr/bin/osascript"));
assert_eq!(argv[1], OsString::from("-e"));
assert_eq!(
argv[2],
OsString::from(
"do shell script \"exec /usr/bin/id -u\" \
with administrator privileges without altering line endings"
)
);
let report = derived
.elevation_report()
.expect("the derived command carries its report");
assert_eq!(report.via, ElevatedVia::MacosOsascript);
assert_eq!(report.stdio, ElevatedStdio::OsascriptRelay);
assert!(report.stripped_env.is_empty(), "no env crosses, so none is stripped");
}
#[skuld::test]
fn the_derived_command_carries_no_elevation_request() {
let mut c = gui_cmd();
let derived = build(&mut c, None).unwrap();
assert!(!derived.elevation_request().enabled);
}
#[skuld::test]
fn kill_on_drop_reaches_the_derived_command() {
for requested in [true, false] {
let mut c = gui_cmd();
c.kill_on_drop(requested);
let derived = build(&mut c, None).unwrap();
assert_eq!(derived.kill_on_drop_flag(), requested);
}
}
#[skuld::test]
fn kill_on_drop_warns_that_it_cannot_reach_the_payload() {
const LOUD: &str = "/usr/bin/cosca-koddrop-probe-loud";
const QUIET: &str = "/usr/bin/cosca-koddrop-probe-quiet";
crate::log_capture::install();
let mark = crate::log_capture::mark();
let mut c = crate::test_child::command(Console::Hidden);
c.args([LOUD]).elevation_auth(crate::elevation::Auth::Gui);
c.kill_on_drop(true);
let _ = build(&mut c, None).unwrap();
assert!(
crate::log_capture::contains_since(mark, LOUD),
"a kill_on_drop child must be warned about, not silently orphaned"
);
let mark = crate::log_capture::mark();
let mut quiet = crate::test_child::command(Console::Hidden);
quiet.args([QUIET]).elevation_auth(crate::elevation::Auth::Gui);
quiet.kill_on_drop(false);
let _ = build(&mut quiet, None).unwrap();
assert!(!crate::log_capture::contains_since(mark, QUIET));
}
#[skuld::test]
fn the_cwd_reaches_both_osascript_and_the_payload() {
let mut c = gui_cmd();
c.current_dir("/tmp");
let derived = build(&mut c, None).unwrap();
assert_eq!(derived.cwd(), Some(Path::new("/tmp")));
let CommandInput::Argv(argv) = derived.input() else {
unreachable!()
};
assert!(
argv[2].to_str().unwrap().contains("cd -P -- /tmp && exec"),
"{:?}",
argv[2]
);
}
#[skuld::test]
fn the_length_guard_is_enforced_through_the_rewrite() {
let mut c = gui_cmd();
let e = build(&mut c, Some(10)).unwrap_err();
assert!(
matches!(
e,
Error::Elevation {
kind: ElevationErrorKind::CommandTooLong,
..
}
),
"{e}"
);
}
#[skuld::test]
fn the_rewrite_preserves_the_callers_argv_and_moves_its_fds() {
let mut c = gui_cmd();
c.stdout(crate::Stdio::pipe()).unwrap();
let before = format!("{:?}", c.input());
let derived = build(&mut c, None).unwrap();
assert_eq!(format!("{:?}", c.input()), before, "argv must survive the rewrite");
assert!(c.env_ops().is_empty());
assert!(c.fds().is_empty(), "the caller's fds are moved, not copied");
assert!(
derived.fds().contains_key(&crate::Fd::STDOUT),
"the moved fds must land on the derived command"
);
}
#[cfg(target_os = "macos")]
fn crate_script_without_the_privilege_clause(program: &OsStr, args: &[OsString]) -> String {
const CLAUSE: &str = " with administrator privileges";
let shell_command = build_shell_command(program, args, None).unwrap();
let script = wrap_do_shell_script(&shell_command, None).unwrap();
assert!(script.contains(CLAUSE), "the privilege clause moved: {script}");
script.replace(CLAUSE, "")
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn both_quoting_layers_survive_a_real_osascript_round_trip() {
let nasty = [
"a b",
"it's",
r#"he said "hi""#,
"$HOME `id` $(id)",
r"back\slash",
"semi;colon & pipe|",
"tab\there",
"line\nbreak",
"carriage\rreturn",
"crlf\r\npair",
"",
"--",
"trailing ",
"\u{1b}[31mred\u{1b}[0m",
"bell\u{7}here",
"vtab\u{b}here",
"ff\u{c}here",
"del\u{7f}here",
"\u{4e2d}\u{6587}\u{6587}\u{4ef6}.txt",
"\u{440}\u{443}\u{441}\u{441}\u{43a}\u{438}\u{439}",
"\u{627}\u{644}\u{639}\u{631}\u{628}\u{64a}\u{629}",
"caf\u{e9}",
"cafe\u{301}",
"\u{1f389}\u{1f680}",
"mixed \u{65e5}\u{672c}\u{8a9e} and \u{3b5}\u{3bb}\u{3bb} and ascii",
];
const DUMP: &str = r#"for a in "$@"; do printf %s "$a" | od -An -tx1 -v | tr -d ' \n'; echo; done"#;
let mut argv: Vec<OsString> = vec![
OsString::from("-c"),
OsString::from(DUMP),
OsString::from("sh"), ];
argv.extend(nasty.iter().map(OsString::from));
let script = crate_script_without_the_privilege_clause(OsStr::new("/bin/sh"), &argv);
let mut c = crate::test_child::command(Console::Hidden);
c.args([
OsString::from("/usr/bin/osascript"),
OsString::from("-e"),
script.into(),
]);
let relayed = c.read().expect("osascript output");
let expected: Vec<String> = nasty
.iter()
.map(|s| s.as_bytes().iter().map(|b| format!("{b:02x}")).collect())
.collect();
let got: Vec<&str> = relayed.trim_end_matches('\n').split('\n').collect();
assert_eq!(got, expected, "argv was mangled crossing the two quoting layers");
let hex = |s: &str| -> String { s.as_bytes().iter().map(|b| format!("{b:02x}")).collect() };
let nfc = hex("caf\u{e9}");
let nfd = hex("cafe\u{301}");
assert_ne!(nfc, nfd, "the NFC/NFD pair must remain byte-distinct");
assert!(got.contains(&nfc.as_str()) && got.contains(&nfd.as_str()));
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn the_administrator_script_compiles() {
let shell_command = build_shell_command(OsStr::new("/usr/bin/id"), &args(&["-u"]), None).unwrap();
let script = wrap_do_shell_script(&shell_command, None).unwrap();
let dir = tempfile::tempdir().expect("tempdir");
let out_path = dir.path().join("script.scpt");
let mut c = crate::test_child::command(Console::Hidden);
c.args([
OsString::from("/usr/bin/osacompile"),
OsString::from("-o"),
out_path.clone().into_os_string(),
OsString::from("-e"),
script.clone().into(),
]);
let out = c.output().expect("osacompile output");
assert!(
out.status.success(),
"the elevated script does not compile: {script}\n{}",
String::from_utf8_lossy(&out.stderr)
);
assert!(out_path.exists(), "osacompile reported success but wrote nothing");
}
#[cfg(target_os = "macos")]
#[skuld::test]
fn a_timeout_clause_does_not_bound_do_shell_script() {
let shell_command = build_shell_command(OsStr::new("/bin/sleep"), &args(&["5"]), None).unwrap();
let body = crate::quote::applescript::escape_literal(&shell_command).unwrap();
let bounded = format!(
"with timeout of 2 seconds
do shell script \"{body}\" without altering line endings
end timeout"
);
let mut c = crate::test_child::command(Console::Hidden);
c.args([
OsString::from("/usr/bin/osascript"),
OsString::from("-e"),
bounded.into(),
]);
let out = c.output().expect("osascript output");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
out.status.success(),
"a 2s `with timeout` must not bound a 5s do-shell-script payload: {stderr}"
);
assert!(
!stderr.contains("-1712"),
"the payload was cut short by the Apple event timeout: {stderr}"
);
}
#[cfg(unix)]
fn sh_exit_code(script: &[u8]) -> Option<i32> {
use std::os::unix::ffi::OsStrExt;
crate::test_spawn::status(
std::process::Command::new("/bin/sh")
.arg("-c")
.arg(OsStr::from_bytes(script))
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null()),
)
.expect("run /bin/sh")
.code()
}
#[cfg(unix)]
fn exit_tool(path: &Path, code: i32) {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
let _guard = crate::child::spawn::spawn_lock();
std::fs::write(path, format!("#!/bin/sh\nexit {code}\n")).expect("write tool");
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).expect("chmod tool");
}
#[cfg(unix)]
#[skuld::test]
fn the_script_enters_a_symlink_dotdot_directory_as_the_kernel_does() {
let root = tempfile::tempdir().expect("tempdir");
std::fs::create_dir_all(root.path().join("real").join("inner")).expect("mkdir");
std::fs::create_dir_all(root.path().join("a")).expect("mkdir");
std::os::unix::fs::symlink("../real/inner", root.path().join("a").join("link")).expect("symlink");
exit_tool(&root.path().join("real").join("tool"), 11);
exit_tool(&root.path().join("a").join("tool"), 22);
let dir = root.path().join("a").join("link").join("..");
let script = build_shell_command(OsStr::new("/bin/sh"), &args(&["-c", "exec ./tool"]), Some(&dir)).unwrap();
assert_eq!(sh_exit_code(&script), Some(11), "{}", String::from_utf8_lossy(&script));
}