use std::path::PathBuf;
use super::{Auth, Backend, Privilege};
use crate::error::{ElevationErrorKind, Error};
#[allow(
dead_code,
reason = "the other platform's Os variant is never constructed in a single-platform non-test build"
)]
#[allow(
clippy::enum_variant_names,
reason = "MacOs necessarily ends with the enum's own name Os; renaming either would make both worse"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Unix,
Linux,
MacOs,
Windows,
}
pub(crate) fn is_macos_gui_auto(os: Os, backend: Backend, auth: &Auth) -> bool {
os == Os::MacOs && matches!(auth, Auth::Gui) && backend == Backend::Auto
}
#[derive(Debug, Clone, Default)]
pub enum FrontState {
#[default]
Absent,
Found(PathBuf),
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only the POSIX detection finds a front it cannot examine")
)]
Unexamined(std::sync::Arc<Error>),
}
#[derive(Debug, Clone, Default)]
pub struct BackendSet {
pub sudo: FrontState,
pub doas: FrontState,
pub pkexec: FrontState,
pub osascript: FrontState,
}
impl BackendSet {
pub(crate) fn resolve(&self, backend: Backend) -> Option<(Backend, &'static str, &FrontState)> {
match backend {
Backend::Sudo => Some((Backend::Sudo, "sudo", &self.sudo)),
Backend::Doas => Some((Backend::Doas, "doas", &self.doas)),
Backend::Pkexec => Some((Backend::Pkexec, "pkexec", &self.pkexec)),
Backend::Auto => [Backend::Sudo, Backend::Doas]
.into_iter()
.filter_map(|front| self.resolve(front))
.find(|(_, _, state)| !matches!(state, FrontState::Absent)),
}
}
}
#[derive(Debug, Clone)]
pub struct Host {
pub elevated: bool,
pub has_tty: bool,
pub available: BackendSet,
pub os: Os,
pub arg_max: Option<usize>,
#[cfg_attr(not(unix), allow(dead_code, reason = "read only by the POSIX rewrite"))]
pub pkexec_version: super::pkexec::PkexecVersion,
#[cfg_attr(not(unix), allow(dead_code, reason = "read only by the POSIX rewrite"))]
pub pkexec_pin: Option<std::sync::Arc<std::fs::File>>,
}
#[allow(
dead_code,
reason = "the other platform's effect arm is never constructed in a single-platform non-test build"
)]
#[derive(Debug)]
pub enum Transition {
RunAsIs,
ElevatePosix {
backend: Backend,
path: PathBuf,
auth: Auth,
},
ElevateWindows {
auth: Auth,
},
ElevateMacosGui {
osascript: PathBuf,
arg_max: Option<usize>,
},
Reject {
error: Error,
},
}
impl Host {
pub fn detect(backend: Backend, auth: &Auth, path_var: Option<&std::ffi::OsStr>, elevated: bool) -> Host {
#[cfg(unix)]
{
super::posix::detect_with(
path_var,
super::posix::host_os(),
elevated,
backend,
auth,
|p| std::fs::canonicalize(p),
super::posix::run_version_probe,
)
}
#[cfg(windows)]
{
let _ = (backend, auth, path_var);
super::windows::detect(elevated)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (backend, auth, path_var);
Host {
elevated,
has_tty: false,
available: BackendSet::default(),
os: Os::Unix,
arg_max: None,
pkexec_version: crate::elevation::pkexec::PkexecVersion::NotProbed,
pkexec_pin: None,
}
}
}
pub fn plan(&self, target: Privilege, backend: Backend, auth: Auth) -> Transition {
if target != Privilege::Elevated {
return Transition::RunAsIs;
}
let structural = match self.os {
Os::Windows => structural_windows(backend, &auth),
os => structural_posix(os, backend, &auth, self),
};
if let Some(error) = structural {
return Transition::Reject { error };
}
if self.elevated {
return Transition::RunAsIs;
}
match self.os {
Os::Windows => Transition::ElevateWindows { auth },
Os::MacOs if is_macos_gui_auto(self.os, backend, &auth) => {
match &self.available.osascript {
FrontState::Found(p) => Transition::ElevateMacosGui {
osascript: p.to_path_buf(),
arg_max: self.arg_max,
},
FrontState::Unexamined(error) => Transition::Reject {
error: unexamined("/usr/bin/osascript", error),
},
FrontState::Absent => reject_backend_unavailable(
"/usr/bin/osascript is missing; macOS graphical elevation needs it",
None,
),
}
}
Os::MacOs | Os::Unix | Os::Linux => self.resolve_posix(backend, auth),
}
}
fn resolve_posix(&self, backend: Backend, auth: Auth) -> Transition {
let Some((resolved, program, state)) = self.available.resolve(backend) else {
return reject_backend_unavailable("no sudo/doas on PATH for Backend::Auto", None);
};
let path = match state {
FrontState::Found(p) => p.to_path_buf(),
FrontState::Unexamined(error) => {
return Transition::Reject {
error: unexamined(program, error),
}
}
FrontState::Absent => {
return reject_backend_unavailable(&format!("forced backend {resolved:?} is not on PATH"), None)
}
};
if matches!(auth, Auth::Interactive) && !self.has_tty {
return Transition::Reject {
error: Error::Elevation {
kind: ElevationErrorKind::NoTty,
detail: "Auth::Interactive requires a controlling terminal; use \
Auth::NonInteractive / Askpass / Stdin, or run from a TTY"
.into(),
source: None,
},
};
}
Transition::ElevatePosix {
backend: resolved,
path,
auth,
}
}
}
#[cfg_attr(not(unix), allow(dead_code, reason = "only the POSIX detection calls it"))]
pub(crate) fn launches_pkexec(os: Os, backend: Backend, auth: &Auth, elevated: bool) -> bool {
let host = Host {
elevated,
has_tty: true,
available: BackendSet {
pkexec: FrontState::Found(PathBuf::from("pkexec")),
..BackendSet::default()
},
os,
arg_max: None,
pkexec_version: super::pkexec::PkexecVersion::NotProbed,
pkexec_pin: None,
};
matches!(
host.plan(Privilege::Elevated, backend, auth.clone()),
Transition::ElevatePosix {
backend: Backend::Pkexec,
..
}
)
}
fn unexamined(program: &str, error: &std::sync::Arc<Error>) -> Error {
backend_unavailable(
&format!("{program} could not be found or opened"),
Some(std::sync::Arc::clone(error)),
)
}
fn backend_unavailable(detail: &str, source: Option<std::sync::Arc<Error>>) -> Error {
Error::Elevation {
kind: ElevationErrorKind::BackendUnavailable,
detail: detail.into(),
source,
}
}
fn reject_backend_unavailable(detail: &str, source: Option<std::sync::Arc<Error>>) -> Transition {
Transition::Reject {
error: backend_unavailable(detail, source),
}
}
fn structural_posix(os: Os, backend: Backend, auth: &Auth, host: &Host) -> Option<Error> {
let platform = if os == Os::MacOs { "macos" } else { "unix" };
let unsupported = |op: String, detail: &str| {
Some(Error::Unsupported {
op,
platform,
detail: detail.into(),
source: None,
})
};
if os == Os::MacOs {
let impossible = match backend {
Backend::Pkexec => Some(
"pkexec is a polkit (Linux) program and does not exist on macOS; \
use Backend::Auto with Auth::Gui for the macOS authentication dialog",
),
_ => None,
};
if let Some(detail) = impossible {
return unsupported(format!("Backend::{backend:?}"), detail);
}
}
if os == Os::Unix && backend == Backend::Pkexec {
return unsupported(
"Backend::Pkexec".into(),
"cosca launches pkexec through Linux's /proc/self/fd, so that the pkexec it checked is the one \
it runs; pkexec elevation needs Linux, so use sudo or doas here",
);
}
if matches!(auth, Auth::Gui) {
if os == Os::MacOs {
if !is_macos_gui_auto(os, backend, auth) {
return unsupported(
format!("{backend:?} + Auth::Gui"),
"macOS graphical elevation goes through Authorization Services, not a \
CLI wrapper; pair Auth::Gui with Backend::Auto",
);
}
} else if backend != Backend::Pkexec {
return unsupported(
format!("{backend:?} + Auth::Gui"),
"graphical (Gui) auth is only available through Backend::Pkexec",
);
}
}
if backend == Backend::Pkexec && !matches!(auth, Auth::Gui) {
return unsupported(
"pkexec + non-Gui auth".into(),
"pkexec is the graphical backend; pair it with Auth::Gui",
);
}
if matches!(auth, Auth::Askpass(_) | Auth::Stdin(_)) {
let effective = host.available.resolve(backend);
if let (Backend::Auto, Some((_, program, FrontState::Unexamined(error)))) = (backend, effective) {
return Some(unexamined(program, error));
}
if let Some(eff) = effective.map(|(eff, ..)| eff).filter(|eff| *eff != Backend::Sudo) {
let (kind, detail) = if matches!(auth, Auth::Askpass(_)) {
(
"Askpass",
"askpass auth is sudo-only; doas/pkexec have no askpass mechanism",
)
} else {
(
"Stdin",
"Stdin (sudo -S) auth is sudo-only; doas has no -S and non-sudo targets would leak the password",
)
};
let op = if backend == Backend::Auto {
format!("Auto (resolves to {eff:?}) + {kind}")
} else {
format!("{backend:?} + {kind}")
};
return unsupported(op, detail);
}
}
None
}
fn structural_windows(backend: Backend, auth: &Auth) -> Option<Error> {
if backend != Backend::Auto {
return Some(Error::Unsupported {
op: format!("elevation backend {backend:?}"),
platform: "windows",
detail: "POSIX elevation backends do not exist on Windows; use Backend::Auto (ShellExecuteEx runas)".into(),
source: None,
});
}
if matches!(auth, Auth::NonInteractive | Auth::Askpass(_) | Auth::Stdin(_)) {
return Some(Error::Unsupported {
op: "runas + non-interactive/askpass/stdin auth".into(),
platform: "windows",
detail: "ShellExecuteEx(runas) has no non-interactive, askpass, or stdin-credential mechanism; \
use Auth::Interactive or Auth::Gui (both map to the UAC consent gate)"
.into(),
source: None,
});
}
None
}
#[cfg(test)]
#[path = "plan_tests.rs"]
mod plan_tests;