use std::ffi::{OsStr, OsString};
use std::path::Path;
use super::{ElevatedStdio, ElevatedVia, ElevationReport};
use crate::command::{Command, CommandInput};
use crate::error::Error;
use crate::stdio::{Fd, ResolvedStdio};
fn unsupported(op: &str, detail: String) -> Error {
Error::Unsupported {
op: op.into(),
platform: "macos",
detail,
}
}
fn os_bytes(s: &OsStr) -> Result<&[u8], Error> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
Ok(s.as_bytes())
}
#[cfg(not(unix))]
{
if let Some(valid) = s.to_str() {
return Ok(valid.as_bytes());
}
use std::os::windows::ffi::OsStrExt;
let pos = char::decode_utf16(s.encode_wide())
.take_while(|c| c.is_ok())
.map(|c| c.expect("take_while kept only Ok").len_utf8())
.sum();
Err(Error::Quote(crate::error::QuoteError::new(
pos,
crate::error::QuoteErrorKind::NonUtf8,
)))
}
}
fn is_posix_absolute(s: &OsStr) -> Result<bool, Error> {
Ok(os_bytes(s)?.first() == Some(&b'/'))
}
pub(crate) fn build_shell_command(program: &OsStr, args: &[OsString], cwd: Option<&Path>) -> Result<Vec<u8>, Error> {
debug_assert!(
matches!(is_posix_absolute(program), Ok(true)),
"the structural gate must reject a non-absolute program before composition"
);
debug_assert!(
cwd.is_none_or(|d| matches!(is_posix_absolute(d.as_os_str()), Ok(true))),
"the structural gate must reject a non-absolute cwd before composition"
);
let mut words: Vec<&[u8]> = Vec::with_capacity(args.len() + 2);
words.push(b"exec".as_slice());
words.push(os_bytes(program)?);
let arg_bytes: Vec<&[u8]> = args.iter().map(|a| os_bytes(a)).collect::<Result<_, _>>()?;
words.extend(arg_bytes.iter().copied());
let mut out = Vec::new();
if let Some(dir) = cwd {
out.extend_from_slice(b"cd -- ");
out.extend_from_slice(&crate::quote::posix::quote(os_bytes(dir.as_os_str())?));
out.extend_from_slice(b" && ");
}
out.extend_from_slice(&crate::quote::posix::join(&words));
Ok(out)
}
pub(crate) fn wrap_do_shell_script(shell_command: &[u8], arg_max: Option<usize>) -> Result<String, Error> {
let body = crate::quote::applescript::escape_literal(shell_command).map_err(Error::Quote)?;
let script = format!("do shell script \"{body}\" with administrator privileges without altering line endings");
if let Some(max) = arg_max {
if script.len() > max {
return Err(Error::Elevation {
kind: crate::error::ElevationErrorKind::CommandTooLong,
detail: format!(
"the composed AppleScript is {} bytes; this system's kern.argmax is {max}. \
Shorten the command, or write the arguments to a file the elevated program reads",
script.len()
),
});
}
}
Ok(script)
}
pub(crate) fn program_and_args(cmd: &Command) -> Result<(OsString, Vec<OsString>), Error> {
let argv = match cmd.input() {
CommandInput::Argv(argv) => argv,
CommandInput::Empty => {
return Err(unsupported(
"macOS graphical elevation of an empty command",
"set a program via .args([...]) before .elevate()".into(),
))
}
CommandInput::CommandLine(_) => {
return Err(unsupported(
"macOS graphical elevation of a commandline() command",
"the command must be an argv (set .args([...])); a raw command line cannot be \
re-quoted for /bin/sh without guessing its word boundaries"
.into(),
))
}
};
let Some(first) = argv.first() else {
return Err(unsupported(
"macOS graphical elevation of an empty command",
"set a program via .args([...]) before .elevate()".into(),
));
};
match cmd.executable_path() {
Some(exe) => {
if first.as_os_str() != exe.as_os_str() {
return Err(unsupported(
"macOS graphical elevation with an argv[0] distinct from executable()",
"`do shell script` execs the program, which sets argv[0] to its own path; \
a separate argv[0] cannot survive elevation"
.into(),
));
}
Ok((exe.as_os_str().to_os_string(), argv[1..].to_vec()))
}
None => Ok((first.clone(), argv[1..].to_vec())),
}
}
pub(crate) fn reject_structural_gui_config(cmd: &Command) -> Result<(), Error> {
let (program, _) = program_and_args(cmd)?;
if !is_posix_absolute(&program)? {
return Err(unsupported(
"macOS graphical elevation of a non-absolute program",
format!(
"{program:?} would be resolved by the elevated shell's own PATH, not the caller's, \
so the binary that runs as root is not the one you selected; pass an absolute path"
),
));
}
if let Some(dir) = cmd.cwd() {
if !is_posix_absolute(dir.as_os_str())? {
return Err(unsupported(
"macOS graphical elevation with a relative current_dir()",
format!(
"{dir:?} would resolve against this process's directory for osascript but \
against whatever the authorization trampoline hands the elevated shell for \
the command itself; pass an absolute path"
),
));
}
}
for (&slot, resolved) in cmd.fds() {
if slot.raw() >= 3 {
return Err(unsupported(
"fd >= 3 on a macOS graphically-elevated child",
"the authorization trampoline passes no descriptors, so fd >= 3 cannot reach the \
elevated program"
.into(),
));
}
if slot == Fd::STDIN && !matches!(resolved, ResolvedStdio::Inherit | ResolvedStdio::Null) {
return Err(unsupported(
"a pipe or file on stdin for a macOS graphically-elevated child",
"the elevated program's stdin comes from Authorization Services; osascript never \
reads fd0, so anything written there would be silently discarded. Use null() or \
inherit()"
.into(),
));
}
}
if !cmd.env_ops().is_empty() {
return Err(unsupported(
"env forwarding to a macOS graphically-elevated child",
"the authorization trampoline builds the root environment; the only way to pass a \
variable would be an assignment in the command text, which is visible to anyone \
inspecting the running processes"
.into(),
));
}
if cmd.contain_request().mode.is_some() {
return Err(unsupported(
".contain() + macOS graphical elevation",
"the elevated program runs under the authorization trampoline, parented to launchd \
and outside this process's tree; containment cannot span it"
.into(),
));
}
Ok(())
}
pub(crate) fn build_rewrite(
cmd: &mut Command,
osascript: &Path,
arg_max: Option<usize>,
) -> Result<(Command, ElevationReport), Error> {
debug_assert!(
cmd.env_ops().is_empty(),
"reject_structural_gui_config must reject env ops before build_rewrite"
);
debug_assert!(
cmd.contain_request().mode.is_none(),
"reject_structural_gui_config must reject containment before build_rewrite"
);
debug_assert!(
cmd.fds().keys().all(|s| s.raw() < 3),
"reject_structural_gui_config must reject fd >= 3 before build_rewrite"
);
let (program, args) = program_and_args(cmd)?;
let shell_command = build_shell_command(&program, &args, cmd.cwd())?;
let script = wrap_do_shell_script(&shell_command, arg_max)?;
let mut derived = Command::new();
derived.set_input_argv(vec![
osascript.as_os_str().to_os_string(),
OsString::from("-e"),
OsString::from(script),
]);
if let Some(d) = cmd.cwd() {
derived.current_dir(d);
}
derived.kill_on_drop(cmd.kill_on_drop_flag());
if cmd.kill_on_drop_flag() {
log::warn!(
"kill_on_drop is set on a macOS graphically-elevated child ({program:?}): killing or \
dropping it reaches only the osascript front-end, and the root program keeps running \
with its exit status unobservable. Call .kill_on_drop(false) and wait() if that matters."
);
}
for (slot, resolved) in std::mem::take(cmd.fds_mut()) {
derived.fds_mut().insert(slot, resolved);
}
let report = ElevationReport {
via: ElevatedVia::MacosOsascript,
stripped_env: Vec::new(),
stdio: ElevatedStdio::OsascriptRelay,
};
Ok((derived, report))
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;