cosca 0.8.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
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};

/// The report of a child launched as `via`: nothing stripped, stdio passed through.
pub(crate) fn report(via: ElevatedVia) -> ElevationReport {
    ElevationReport {
        via,
        stripped_env: Vec::new(),
        stdio: ElevatedStdio::Passthrough,
    }
}

/// The launches that leave no front: pkexec execs the program, and UAC and an already-elevated
/// parent track it. A child reported as one fails or hands back as a plain child, never as a front.
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:?}"),
    }
}

/// A permission refusal (`ERROR_ACCESS_DENIED`, `EACCES`), the kind both mappers act on.
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;
    // The backend path exists (this test binary), so a NotFound is NOT the backend —
    // it is attributable elsewhere (e.g. a bad current_dir()). The original Io survives.
    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();

    // A real exec attempt on a non-executable file yields PermissionDenied.
    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() {
    // POSIX Auth::Stdin binds fd0 to the elevation password channel; reporting
    // Passthrough would be a lie. This variant must exist and be distinct.
    assert_ne!(ElevatedStdio::StdinConsumed, ElevatedStdio::Passthrough);
    assert_ne!(ElevatedStdio::StdinConsumed, ElevatedStdio::OwnConsole);
}

#[cfg(unix)]
#[skuld::test]
fn is_elevated_matches_effective_uid_ground_truth() {
    // Never assume ambient privilege; compare against an independent syscall.
    // SAFETY: geteuid has no preconditions and never fails.
    let euid0 = unsafe { libc::geteuid() } == 0;
    assert_eq!(super::is_elevated(), euid0, "is_elevated disagreed with geteuid()==0");
}

/// Detection looks for the backends on the `PATH` it is handed, not on this process's.
#[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()));
}

/// Detection reports the privilege it is handed, not this process's.
#[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);
    }
}

/// `path_var: None` finds no backend, even when this process's own `PATH` holds all three.
///
/// Runs in a copy of this test binary whose `PATH` is a directory of fake `sudo`, `doas` and `pkexec`,
/// so no `set_var` races a sibling test.
#[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);
}

/// macOS must NOT report `Os::Unix`: the whole point of the split is that the
/// planner can tell it apart, and detection is the only place that decision is made.
#[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, /* elevated_wrapper */ 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(_)));
}

/// Every backend's argv gate is this one function; only the words differ. A program set by
/// `executable()` or `raw_executable()` is its first rule, so it is refused whatever else is wrong.
///
/// Mutant: the setter rule moved below the empty-command or `commandline()` rule.
#[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);
}