cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! The PURE elevation planner: plain-data [`Host`] + a syscall-free
//! [`Host::plan`]. A Linux test constructs a Windows-shaped `Host` and asserts
//! the Windows decision — the `Containment` host-testing pattern.

use std::path::{Path, PathBuf};

use super::{Auth, Backend, Privilege};
use crate::error::{ElevationErrorKind, Error};

/// Which OS the effect layer will use. Data, not `cfg!`, so `plan` is cross-tested.
// The planner models EVERY platform's decision on ANY host (that is the whole point — a
// Windows-shaped `Host` is planned on Linux and vice versa), so in a non-test single-platform
// build the other platform's variant is never constructed. That is by design, not dead logic.
#[allow(
    dead_code,
    reason = "the other platform's Os variant is never constructed in a single-platform non-test build"
)]
// The enum is named `Os` and `MacOs` names an OS, so the variant unavoidably ends
// with the enum's name. Renaming either to satisfy the lint would make both worse.
#[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 {
    /// Every POSIX host except macOS and Linux — the BSDs, illumos. Planned as Linux is, except
    /// for what needs Linux itself.
    Unix,
    /// Linux: a Unix whose `/proc` cosca launches pkexec through ([`Backend::Pkexec`]).
    Linux,
    MacOs,
    Windows,
}

/// Is this request the macOS graphical path? Deliberately privilege-free: it is a
/// property of the REQUEST, so the same answer holds for a root and a non-root
/// caller. Every site that needs "is this osascript?" calls THIS — the structural
/// matrix, [`Host::plan`]'s resolution arm, and the effect layer's gate selection.
/// Deriving it inline in three places is how they drift apart.
pub(crate) fn is_macos_gui_auto(os: Os, backend: Backend, auth: &Auth) -> bool {
    os == Os::MacOs && matches!(auth, Auth::Gui) && backend == Backend::Auto
}

/// The resolved absolute path of each CLI backend on PATH (`None` = absent),
/// filled by `detect` (checking the exec bit, skipping empty PATH elements) and
/// faked in tests. Carrying the ABSOLUTE path is what closes the CWD-hijack hole:
/// the validated path is exactly the one argv[0] emits.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BackendSet {
    pub sudo: Option<PathBuf>,
    pub doas: Option<PathBuf>,
    pub pkexec: Option<PathBuf>,
    /// macOS only: the absolute path of `/usr/bin/osascript`, the graphical
    /// elevation front-end. Not a [`Backend`]: it does not wrap the child, it asks
    /// Authorization Services to run the command as root.
    pub osascript: Option<PathBuf>,
}

impl BackendSet {
    /// The resolved absolute path for `backend`; `Auto` maps to sudo-then-doas.
    pub(crate) fn path(&self, backend: Backend) -> Option<&Path> {
        match backend {
            Backend::Sudo => self.sudo.as_deref(),
            Backend::Doas => self.doas.as_deref(),
            Backend::Pkexec => self.pkexec.as_deref(),
            Backend::Auto => self.sudo.as_deref().or(self.doas.as_deref()),
        }
    }
}

/// Ambient privilege facts, resolved once by [`Host::detect`].
#[derive(Debug, Clone)]
pub struct Host {
    pub elevated: bool,
    pub has_tty: bool,
    pub available: BackendSet,
    pub os: Os,
    /// `sysctl kern.argmax` — the exec argument budget, read at detect time
    /// because it has changed across macOS releases and must never be guessed.
    /// `None` when the query failed or the platform has no equivalent; the macOS
    /// length guard is then skipped rather than run against an invented number.
    /// Only the macOS graphical path reads it; it lives here because the planner
    /// is plain data.
    pub arg_max: Option<usize>,
    /// What [`BackendSet::pkexec`]'s `--version` said, or why a pkexec on `PATH` was not stored
    /// ([`super::pkexec::PkexecVersion::Unresolved`]); asked only for a request that launches pkexec
    /// — `Backend::Pkexec` with `Auth::Gui`, from a non-root caller, on Linux.
    pub pkexec_version: super::pkexec::PkexecVersion,
    /// [`BackendSet::pkexec`], opened by detection: the version probe and the launch both exec this
    /// descriptor's file (`/proc/self/fd/N`), so a file renamed over the path between them is
    /// never run. `Some` exactly for a request that launches pkexec, when its file was opened.
    // Read only by the POSIX rewrite.
    #[cfg_attr(not(unix), allow(dead_code, reason = "read only by the POSIX rewrite"))]
    pub pkexec_pin: Option<std::sync::Arc<std::fs::File>>,
}

/// The planner's decision. Not `PartialEq` — `Reject` wraps a non-comparable
/// [`Error`]; tests use `matches!` and inspect fields.
// Cross-platform like [`Os`]: the effect arm for the other platform (and its fields) is never
// constructed in a single-platform non-test build, but is exercised by the cross-OS planner tests.
#[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 {
        /// The absolute path of `/usr/bin/osascript`, carried for the same reason
        /// the POSIX backends carry theirs: the validated path is exactly the one
        /// argv[0] emits, so nothing on PATH can be substituted for it.
        osascript: PathBuf,
        /// The detected `kern.argmax`, carried so the effect layer stays pure.
        arg_max: Option<usize>,
    },
    Reject {
        error: Error,
    },
}

impl Host {
    /// The facts for a request naming `backend` and `auth`, which decide whether `pkexec` is asked
    /// its version. `elevated` is the caller's privilege. Unix looks for `sudo`, `doas` and `pkexec`
    /// on `path_var` (`None` finds none); macOS also finds the fixed `/usr/bin/osascript`. Windows
    /// ignores `path_var`.
    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;
        }
        // Structural matrix — privilege-independent, BEFORE the already-elevated
        // short-circuit, so an impossible combo never passes under root.
        let structural = match self.os {
            Os::Windows => structural_windows(backend, &auth),
            os => structural_posix(os, backend, &auth, &self.available),
        };
        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.as_deref() {
                    Some(p) => Transition::ElevateMacosGui {
                        osascript: p.to_path_buf(),
                        arg_max: self.arg_max,
                    },
                    // Honest here, unlike the pkexec verdict: /usr/bin/osascript
                    // can genuinely be missing or non-executable.
                    None => reject_backend_unavailable(
                        "/usr/bin/osascript is missing or not executable; \
                         macOS graphical elevation needs it",
                    ),
                }
            }
            Os::MacOs | Os::Unix | Os::Linux => self.resolve_posix(backend, auth),
        }
    }

    fn resolve_posix(&self, backend: Backend, auth: Auth) -> Transition {
        let (resolved, path) = match backend {
            Backend::Auto => {
                if let Some(p) = self.available.sudo.as_deref() {
                    (Backend::Sudo, p.to_path_buf())
                } else if let Some(p) = self.available.doas.as_deref() {
                    (Backend::Doas, p.to_path_buf())
                } else {
                    return reject_backend_unavailable("no sudo/doas on PATH for Backend::Auto");
                }
            }
            explicit => match self.available.path(explicit) {
                Some(p) => (explicit, p.to_path_buf()),
                None => {
                    let unresolved = (explicit == Backend::Pkexec)
                        .then(|| self.pkexec_version.unresolved())
                        .flatten();
                    return reject_backend_unavailable(
                        &unresolved.unwrap_or_else(|| format!("forced backend {explicit:?} is not on PATH")),
                    );
                }
            },
        };
        // Environmental, not structural: whether a TTY is attached is a fact about
        // this run, not the (backend, auth) config, so it stays here rather than in
        // `structural_posix` — it legitimately differs by invocation.
        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(),
                },
            };
        }
        Transition::ElevatePosix {
            backend: resolved,
            path,
            auth,
        }
    }
}

/// Whether a request launches pkexec: whether [`Host::plan`], on `os` with a pkexec on `PATH`,
/// yields `ElevatePosix` for it. Detection opens and probes pkexec only then, and asks the planner
/// itself rather than restating its rules.
// Only the POSIX detection calls it.
#[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: Some(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 reject_backend_unavailable(detail: &str) -> Transition {
    Transition::Reject {
        error: Error::Elevation {
            kind: ElevationErrorKind::BackendUnavailable,
            detail: detail.into(),
        },
    }
}

/// The full POSIX (backend, auth) matrix, privilege-independent: called BEFORE the
/// already-elevated short-circuit so an impossible combo never passes under root.
///
/// The Askpass/Stdin-needs-sudo check is evaluated against the backend `Auto` WOULD
/// resolve to (via `available`), not against ambient privilege — otherwise
/// `Backend::Auto` + `Auth::Stdin` on a doas-only host would return `Unsupported`
/// unprivileged but `RunAsIs` once already root, a verdict that flips on ambient
/// privilege instead of staying a property of the request.
fn structural_posix(os: Os, backend: Backend, auth: &Auth, available: &BackendSet) -> 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(),
        })
    };
    // polkit is a Linux stack. Saying "not on PATH" on macOS reads as a
    // fixable environment problem on a platform where it will never exist.
    // sudo and doas are NOT in this list: both are portable and do run on macOS.
    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(_)) {
        // `Auto` with neither sudo nor doas on PATH is left to resolution's
        // `BackendUnavailable`, not reported as a config mismatch here.
        let effective = match backend {
            Backend::Auto => {
                if available.sudo.is_some() {
                    Some(Backend::Sudo)
                } else if available.doas.is_some() {
                    Some(Backend::Doas)
                } else {
                    None
                }
            }
            explicit => Some(explicit),
        };
        if let Some(eff) = effective.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
}

/// The full Windows (backend, auth) matrix, privilege-independent for the same reason
/// as [`structural_posix`].
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(),
        });
    }
    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(),
        });
    }
    None
}

#[cfg(test)]
#[path = "plan_tests.rs"]
mod plan_tests;