Skip to main content

sysknife_daemon/
executor.rs

1use crate::actions::{
2    apparmor, apt, apt_preferences, auditd, certbot, cloudinit, containers, deployment, distrobox,
3    fail2ban, filesystem, flatpak, grub, identity, journald, layering, livepatch, logging, lvm,
4    mounts, multipass, netplan, network, package_repos, pam, ppa, processes, reboot,
5    release_upgrade, resolvectl, services, snap, ssh, sudoers, sysctl, system_info, toolbox,
6    ubuntu_pro, ufw, users,
7    validate::{
8        validated_activatable_unit, validated_apparmor_profile, validated_apt_package,
9        validated_apt_pin_expr, validated_apt_pin_name, validated_audit_path,
10        validated_audit_perms, validated_cpu_quota, validated_domain, validated_email,
11        validated_fstype, validated_group, validated_group_not_critical, validated_hostname,
12        validated_install_package, validated_journal_grep, validated_journal_priority,
13        validated_journal_time, validated_locale, validated_log_path, validated_lvm_name,
14        validated_lvm_size, validated_memory_limit, validated_mount_device,
15        validated_mount_options, validated_mount_point, validated_port_or_service,
16        validated_ppa_name, validated_pro_service, validated_safe_arg, validated_sudo_commands,
17        validated_sudoers_name, validated_swap_path, validated_sysctl_key, validated_sysctl_value,
18        validated_syslog_host, validated_tasks_max, validated_timezone, validated_unit_name,
19        validated_username, validated_username_not_critical,
20    },
21    ActionMechanism, ActionSpec,
22};
23use async_trait::async_trait;
24use serde_json::Value;
25use std::io;
26use std::net::IpAddr;
27use std::process::Stdio;
28use std::str::FromStr;
29use std::time::Duration;
30use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
31use tokio::sync::mpsc::UnboundedSender;
32
33// ---------------------------------------------------------------------------
34// Parameter bounds
35// ---------------------------------------------------------------------------
36//
37// These mirror the ceilings of the tools being driven (`chage`, `faillock`,
38// `pam_pwquality`, `fail2ban`, `journalctl`, `mkswap`). Naming them keeps the
39// rejection reason legible and keeps the same tool's ceiling from being spelled
40// two different ways in two arms of the same match.
41
42/// Longest scheduled-job command line.
43const MAX_SCHEDULED_COMMAND_LEN: usize = 512;
44/// Longest schedule expression (`OnCalendar=` / cron form).
45const MAX_SCHEDULE_EXPR_LEN: usize = 128;
46/// Widest `journalctl --lines` request. Values are clamped, not rejected: an
47/// over-large request is a preference, not an error.
48const MAX_JOURNAL_LINES: u64 = 10_000;
49/// Largest swap file, in MiB (1 TiB).
50const MAX_SWAP_SIZE_MB: u32 = 1_048_576;
51/// `chage`'s own ceiling for password-age days.
52const MAX_PASSWORD_AGE_DAYS: u64 = 99_999;
53/// Widest `pam_pwquality` minimum length.
54const MAX_PASSWORD_MINLEN: u64 = 128;
55/// Longest `faillock` unlock/interval window, in seconds (7 days).
56const MAX_LOCKOUT_WINDOW_SECS: u64 = 604_800;
57/// Longest fail2ban bantime/findtime, in seconds (30 days).
58const MAX_FAIL2BAN_WINDOW_SECS: u64 = 2_592_000;
59
60#[derive(Debug, thiserror::Error)]
61pub enum ExecutorError {
62    #[error("unknown action: {0}")]
63    UnknownAction(String),
64
65    #[error("missing required param: {0}")]
66    MissingParam(&'static str),
67
68    #[error("invalid param type for: {0}")]
69    InvalidParam(&'static str),
70
71    /// Richer variant that carries the offending value for actionable diagnostics.
72    ///
73    /// Used when an action constructor returns a typed `InvalidIpAddress` error —
74    /// the value is forwarded to user-facing output rather than being silently
75    /// discarded as in the generic `InvalidParam` path.
76    #[error("invalid IP address for param '{param}': '{value}'")]
77    InvalidIpAddress { param: &'static str, value: String },
78
79    #[error("io error: {0}")]
80    Io(#[from] io::Error),
81
82    /// The action outran its deadline and could not be confirmed stopped.
83    ///
84    /// Separate from a plain timeout because the safe response differs. A
85    /// timeout that stopped the work leaves the host where it was, so an
86    /// automatic rollback is reasonable. This variant means privileged work may
87    /// still be running, and rolling back over it would put two package
88    /// transactions on the host at once. The caller must not treat it as a
89    /// quiet failure.
90    #[error(
91        "{program} exceeded the {timeout_secs}s action timeout and could not be \
92         confirmed stopped: process group {pgid} still has members. Automatic \
93         rollback was skipped because the original action may still be running; \
94         inspect the host before retrying"
95    )]
96    ActionNotStopped {
97        program: String,
98        pgid: i32,
99        timeout_secs: u64,
100    },
101}
102
103/// Output of a single executed action.
104///
105/// `exit_code` is the discriminant between success and failure.  Prefer
106/// [`is_success`](Self::is_success) / [`is_nonzero`](Self::is_nonzero) at
107/// call sites — `if output.exit_code == 0` is harder to read and easier to
108/// invert by accident than `if output.is_success()`.  The raw `exit_code`
109/// stays public because the dispatcher echoes it back to callers and the
110/// rollback path includes the precise code in diagnostic messages.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct ExecutionOutput {
113    pub stdout: String,
114    pub stderr: String,
115    pub exit_code: i32,
116}
117
118impl ExecutionOutput {
119    /// `true` when the action exited cleanly (`exit_code == 0`).
120    pub fn is_success(&self) -> bool {
121        self.exit_code == 0
122    }
123
124    /// `true` when the action failed (`exit_code != 0`).
125    pub fn is_nonzero(&self) -> bool {
126        self.exit_code != 0
127    }
128}
129
130/// Abstraction over action execution, making the execute + rollback path
131/// testable without spawning real OS commands.
132///
133/// The production implementation (`RealActionExecutor`) delegates to
134/// `tokio::process::Command`. Tests can inject a mock that controls exit
135/// codes and output per program.
136#[async_trait]
137pub trait ActionExecutor: Send + Sync {
138    /// Execute an [`ActionSpec`] and return its output.
139    async fn execute(&self, spec: &ActionSpec) -> Result<ExecutionOutput, ExecutorError>;
140
141    /// Execute an action and publish stdout lines while it runs.
142    ///
143    /// Test doubles normally implement only [`execute`](Self::execute); this
144    /// default forwards their captured output after completion. Production
145    /// overrides the method so command output remains live.
146    async fn execute_with_progress(
147        &self,
148        spec: &ActionSpec,
149        progress: UnboundedSender<String>,
150    ) -> Result<ExecutionOutput, ExecutorError> {
151        let output = self.execute(spec).await?;
152        for line in output.stdout.lines().filter(|line| !line.is_empty()) {
153            let _ = progress.send(line.to_string());
154        }
155        Ok(output)
156    }
157}
158
159/// Production executor that delegates to real OS processes and filesystem ops.
160pub struct RealActionExecutor;
161
162#[async_trait]
163impl ActionExecutor for RealActionExecutor {
164    async fn execute(&self, spec: &ActionSpec) -> Result<ExecutionOutput, ExecutorError> {
165        execute_spec(spec).await
166    }
167
168    async fn execute_with_progress(
169        &self,
170        spec: &ActionSpec,
171        progress: UnboundedSender<String>,
172    ) -> Result<ExecutionOutput, ExecutorError> {
173        match &spec.mechanism {
174            ActionMechanism::Command { program, args } => {
175                execute_command_with_progress(program, args, progress).await
176            }
177            _ => execute_spec(spec).await,
178        }
179    }
180}
181
182/// Wall-clock ceiling on a single privileged action.
183///
184/// Nothing else bounds these processes: without a deadline a child that never
185/// exits — `apt-get` waiting on a dead mirror, a helper blocked on a prompt
186/// that will never arrive — wedges its connection forever, and the exclusion
187/// lock it holds is never released, so every other action contending for that
188/// resource is refused from then on.
189///
190/// The ceiling is deliberately generous rather than tight. A release upgrade
191/// or an OSTree rebase legitimately runs for tens of minutes, and killing a
192/// half-finished package transaction is worse than waiting. This is a
193/// backstop against a hang, not a performance budget. Override with
194/// `SYSKNIFE_ACTION_TIMEOUT_SECS` when an action on a slow link needs longer.
195const DEFAULT_ACTION_TIMEOUT: Duration = Duration::from_secs(2 * 60 * 60);
196
197fn action_timeout() -> Duration {
198    match std::env::var("SYSKNIFE_ACTION_TIMEOUT_SECS") {
199        Ok(raw) => match raw.trim().parse::<u64>() {
200            Ok(secs) if secs > 0 => Duration::from_secs(secs),
201            _ => {
202                eprintln!(
203                    "[sysknife-daemon] WARNING: ignoring invalid \
204                     SYSKNIFE_ACTION_TIMEOUT_SECS={raw:?}; using the default"
205                );
206                DEFAULT_ACTION_TIMEOUT
207            }
208        },
209        Err(_) => DEFAULT_ACTION_TIMEOUT,
210    }
211}
212
213/// What a `killpg` probe says about a process group.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215enum GroupState {
216    /// `ESRCH`: no process holds this group id. Gone.
217    Gone,
218    /// The group has members this process could signal.
219    AliveReachable,
220    /// `EPERM`: the group has members, but they run as a user this process
221    /// cannot signal. On an unprivileged daemon that is the normal state of a
222    /// `sudo` child still running as root, so it counts as *alive*, not gone.
223    /// Reading it as gone was the bug that let the rollback fire over live work.
224    AliveUnreachable,
225    /// Any other errno. Treated as alive, because the safe default when the
226    /// kernel will not answer is "still running", not "stopped".
227    Unknown(i32),
228}
229
230impl GroupState {
231    fn is_gone(self) -> bool {
232        matches!(self, GroupState::Gone)
233    }
234}
235
236/// Probe a process group without delivering a signal (`signal 0`).
237fn probe_group(pgid: i32) -> GroupState {
238    // SAFETY: `killpg` is async-signal-safe and takes no pointers. `pgid` is a
239    // real group id from `child.id()` for a child spawned with
240    // `process_group(0)`, so it is >= 1 and names that child's own group, never
241    // 0 (which would address the daemon's own group).
242    let rc = unsafe { libc::killpg(pgid, 0) };
243    if rc == 0 {
244        return GroupState::AliveReachable;
245    }
246    match io::Error::last_os_error().raw_os_error() {
247        Some(libc::ESRCH) => GroupState::Gone,
248        Some(libc::EPERM) => GroupState::AliveUnreachable,
249        other => GroupState::Unknown(other.unwrap_or(0)),
250    }
251}
252
253/// Send a signal to a process group. `ESRCH` is success (already gone).
254fn signal_group(pgid: i32, signal: i32) -> Result<(), io::Error> {
255    // SAFETY: see `probe_group`; same `pgid` contract.
256    let rc = unsafe { libc::killpg(pgid, signal) };
257    if rc == 0 {
258        return Ok(());
259    }
260    let err = io::Error::last_os_error();
261    if err.raw_os_error() == Some(libc::ESRCH) {
262        return Ok(());
263    }
264    Err(err)
265}
266
267/// How long a group gets to exit on SIGTERM before SIGKILL.
268///
269/// Short on purpose. The deadline has already passed, so this is the courtesy
270/// window for a package manager to unwind, not a second timeout.
271const GROUP_TERM_GRACE: Duration = Duration::from_secs(5);
272
273/// Whether this action's real work is an `rpm-ostree` transaction. Such work
274/// runs inside `rpm-ostreed`'s own cgroup (rpm-ostree is a thin D-Bus client),
275/// not this process group, so a group signal cannot reach it — it must be
276/// cancelled with `rpm-ostree cancel` instead (#142). `program` is usually
277/// `sudo`, so the real command is found in the arguments.
278fn is_rpm_ostree_action(program: &str, args: &[String]) -> bool {
279    let is_ostree = |s: &str| s == "rpm-ostree" || s.ends_with("/rpm-ostree");
280    is_ostree(program) || args.iter().any(|a| is_ostree(a))
281}
282
283/// The argv for a privileged, non-interactive signal to a whole process group:
284/// `sudo -n /usr/bin/kill -s <SIGNAL> -- -<pgid>`. Run as root, it reaches the
285/// root children a `sudo` action forked that the unprivileged daemon cannot
286/// signal itself. `-n` never prompts (the sysknife sudoers entry is NOPASSWD),
287/// `--` ends options so the negative pgid is unambiguously a group, not a flag.
288fn root_group_kill_argv(signal: &str, pgid: i32) -> Vec<String> {
289    vec![
290        "-n".to_string(),
291        "/usr/bin/kill".to_string(),
292        "-s".to_string(),
293        signal.to_string(),
294        "--".to_string(),
295        format!("-{pgid}"),
296    ]
297}
298
299/// Counts `run_sudo` invocations so a test can prove the escalation path did
300/// (not) fire without needing a real sudo. Test-only.
301#[cfg(test)]
302static SUDO_INVOCATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
303
304/// Run a bounded, output-discarding `sudo` command for the privileged reaper.
305/// Best-effort for the *verdict* (the caller re-probes the group to decide the
306/// outcome), but the exit status is logged so a later "could not be confirmed
307/// stopped" line can be told apart from a misconfigured sudoers grant or a
308/// missing `sudo` — the reaper failing and the process genuinely wedging look
309/// identical from the group probe alone.
310async fn run_sudo(args: Vec<String>) {
311    #[cfg(test)]
312    SUDO_INVOCATIONS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
313    let fut = tokio::process::Command::new("sudo")
314        .args(&args)
315        .stdin(Stdio::null())
316        .stdout(Stdio::null())
317        .stderr(Stdio::null())
318        .status();
319    let joined = args.join(" ");
320    match tokio::time::timeout(REAP_WAIT_CAP, fut).await {
321        Ok(Ok(status)) if status.success() => {}
322        Ok(Ok(status)) => {
323            eprintln!("[sysknife-daemon] privileged reap `sudo {joined}` exited {status}")
324        }
325        Ok(Err(e)) => {
326            eprintln!("[sysknife-daemon] privileged reap `sudo {joined}` could not run: {e}")
327        }
328        Err(_) => eprintln!(
329            "[sysknife-daemon] privileged reap `sudo {joined}` timed out after {}s",
330            REAP_WAIT_CAP.as_secs()
331        ),
332    }
333}
334
335/// The first privileged reap command (the args passed to `sudo`) for an action
336/// whose group survived the daemon's own signals: `rpm-ostree cancel` for an
337/// rpm-ostree transaction (its work is in another cgroup), otherwise a root TERM
338/// to the action's own process group. Split out so the dispatch and the exact
339/// argv are unit-testable without running `sudo`.
340fn reap_command(pgid: i32, program: &str, args: &[String]) -> Vec<String> {
341    if is_rpm_ostree_action(program, args) {
342        vec![
343            "-n".to_string(),
344            "/usr/bin/rpm-ostree".to_string(),
345            "cancel".to_string(),
346        ]
347    } else {
348        root_group_kill_argv("TERM", pgid)
349    }
350}
351
352/// Last-resort privileged reap for a group the daemon's own signals could not
353/// stop (its members run as root). Cancels an `rpm-ostree` transaction, or root
354/// TERM→KILLs the process group. This is the *termination* half of #140's
355/// detect-and-veto, so `ActionNotStopped` becomes a genuine last resort rather
356/// than the expected path for every sudo action.
357async fn privileged_reap(pgid: i32, program: &str, args: &[String]) {
358    run_sudo(reap_command(pgid, program, args)).await;
359    // rpm-ostree cancel is a single, blocking call; only the group-kill path
360    // escalates TERM → KILL. The client process blocks until the daemon-side
361    // transaction resolves (completes, errors, or cancels), so once `cancel`
362    // returns the transaction is stopped and the client group exits — which is
363    // why the caller's group probe (of the client) correctly reflects the
364    // transaction, even though the work itself ran in rpm-ostreed's cgroup.
365    if is_rpm_ostree_action(program, args) {
366        return;
367    }
368    tokio::time::sleep(Duration::from_millis(300)).await;
369    if !probe_group(pgid).is_gone() {
370        run_sudo(root_group_kill_argv("KILL", pgid)).await;
371    }
372}
373
374/// Upper bound on any single `child.wait()` in the timeout path.
375///
376/// The direct child of a `sudo` action runs as root and this daemon cannot
377/// signal it, so `wait()` on that child can block until the privileged work
378/// finishes on its own — hours. The action timeout exists to stop a hang, so it
379/// must not itself become one. Every wait here is bounded by this; an unreaped
380/// child becomes the subreaper's problem, not a wedged connection.
381const REAP_WAIT_CAP: Duration = Duration::from_secs(2);
382
383/// Stop an action that outran the deadline, and report honestly whether it
384/// actually stopped.
385///
386/// Signals the child's whole **process group**, not just its pid. The daemon
387/// runs unprivileged and elevates through `sudo`, which forks: signalling the
388/// pid alone leaves the privileged work running (issue #140). SIGTERM first so a
389/// package manager can unwind, then SIGKILL.
390///
391/// An unprivileged daemon cannot signal a process running as root, which every
392/// `sudo` action's real work does. When the group survives the daemon's own
393/// signals it therefore escalates to a privileged reaper ([`privileged_reap`]):
394/// a root kill of the group via the sudoers-authorised `/usr/bin/kill`, or an
395/// `rpm-ostree cancel` for a transaction that lives in another cgroup (#142).
396/// Only when even that cannot confirm the group gone does it return
397/// [`ExecutorError::ActionNotStopped`] — now a genuine last resort — and the
398/// dispatcher refuses the automatic rollback rather than starting a second
399/// privileged transaction over the first.
400async fn kill_and_reap(
401    child: &mut tokio::process::Child,
402    program: &str,
403    args: &[String],
404    cause: StopCause,
405) -> ExecutorError {
406    let secs = action_timeout().as_secs();
407    let why = cause.describe(secs);
408    let Some(pgid) = child.id().map(|pid| pid as i32) else {
409        // Already reaped: the child exited between the deadline and here, so the
410        // work is done and there is nothing to signal.
411        eprintln!("[sysknife-daemon] {program} {why}; already exited");
412        return cause.into_error(program, secs);
413    };
414
415    // A pid-targeted floor. `start_kill` (SIGKILL to the direct child) always
416    // lands when the child is ours to signal, which covers every non-`sudo`
417    // action; the group signal below covers the grandchildren `sudo` forks.
418    let _ = child.start_kill();
419    if let Err(err) = signal_group(pgid, libc::SIGTERM) {
420        eprintln!("[sysknife-daemon] SIGTERM to process group {pgid} failed: {err}");
421    }
422
423    // Reap the direct child first, bounded: an unreaped child is a zombie that
424    // keeps the group alive and would make the probe below lie. Bounded because
425    // a root `sudo` child can outlast any signal this daemon can send.
426    let _ = tokio::time::timeout(REAP_WAIT_CAP, child.wait()).await;
427
428    let grace = tokio::time::Instant::now() + GROUP_TERM_GRACE;
429    while tokio::time::Instant::now() < grace && !probe_group(pgid).is_gone() {
430        tokio::time::sleep(Duration::from_millis(50)).await;
431    }
432    if !probe_group(pgid).is_gone() {
433        if let Err(err) = signal_group(pgid, libc::SIGKILL) {
434            eprintln!("[sysknife-daemon] SIGKILL to process group {pgid} failed: {err}");
435        }
436        tokio::time::sleep(Duration::from_millis(200)).await;
437        let _ = tokio::time::timeout(REAP_WAIT_CAP, child.wait()).await;
438    }
439
440    // The group survived the daemon's own signals: its members run as root (a
441    // `sudo` action's privileged child), which an unprivileged daemon cannot
442    // signal. Escalate to a privileged reaper — a root kill of the group, or an
443    // `rpm-ostree cancel` for a transaction that lives in another cgroup (#142).
444    //
445    // Escalate only for `AliveUnreachable` (EPERM): the members run as root, the
446    // sudo action's privileged child the daemon cannot signal. A same-uid process
447    // wedged in D-state (`AliveReachable`) or an `Unknown` errno would not be
448    // helped by a root signal, so those fall straight through to
449    // `ActionNotStopped` rather than a pointless sudo round-trip.
450    //
451    // Signalling the group by its numeric pgid is safe against pid reuse: POSIX
452    // keeps a process-group id allocated for the group's whole lifetime (while it
453    // has any member), so a probe reporting the group alive guarantees the pgid
454    // still names THIS action's group, never a recycled unrelated process.
455    if probe_group(pgid) == GroupState::AliveUnreachable {
456        eprintln!(
457            "[sysknife-daemon] {program} process group {pgid} survived as root; \
458             escalating to a privileged reap"
459        );
460        privileged_reap(pgid, program, args).await;
461        tokio::time::sleep(Duration::from_millis(200)).await;
462        let _ = tokio::time::timeout(REAP_WAIT_CAP, child.wait()).await;
463    }
464
465    match probe_group(pgid) {
466        GroupState::Gone => {
467            eprintln!("[sysknife-daemon] {program} {why}; process group {pgid} stopped");
468            cause.into_error(program, secs)
469        }
470        state => {
471            eprintln!(
472                "[sysknife-daemon] {program} {why} and process group {pgid} \
473                 could not be confirmed stopped ({state:?})"
474            );
475            ExecutorError::ActionNotStopped {
476                program: program.to_string(),
477                pgid,
478                timeout_secs: secs,
479            }
480        }
481    }
482}
483
484/// Why the executor is tearing down a still-running privileged child.
485///
486/// Both causes must stop the process group — a root child left running after the
487/// executor has reported failure defeats the rollback interlock and the
488/// one-privileged-action-at-a-time guarantee — but they are not the same event,
489/// and reporting a read failure as a timeout would send an operator hunting a
490/// deadline that never fired.
491enum StopCause {
492    /// The action's own deadline elapsed.
493    Timeout,
494    /// The daemon lost the ability to read the child (a non-UTF-8 line, a broken
495    /// pipe, a `wait` that failed). Carries the error to surface once the group
496    /// is confirmed stopped.
497    Unreadable(io::Error),
498}
499
500impl StopCause {
501    /// The operator-log fragment, e.g. `exceeded the 900s action timeout`.
502    fn describe(&self, secs: u64) -> String {
503        match self {
504            StopCause::Timeout => format!("exceeded the {secs}s action timeout"),
505            StopCause::Unreadable(err) => format!("could not be read ({err})"),
506        }
507    }
508
509    /// The error to return once the group is confirmed gone. A group that
510    /// survives reports [`ExecutorError::ActionNotStopped`] instead, whatever the
511    /// cause — the caller needs to know work is still running far more than it
512    /// needs to know why the executor gave up on it.
513    fn into_error(self, program: &str, secs: u64) -> ExecutorError {
514        match self {
515            StopCause::Timeout => ExecutorError::Io(io::Error::new(
516                io::ErrorKind::TimedOut,
517                format!("{program} exceeded the {secs}s action timeout and was stopped"),
518            )),
519            StopCause::Unreadable(err) => ExecutorError::Io(err),
520        }
521    }
522}
523
524async fn execute_command_with_progress(
525    program: &'static str,
526    args: &[String],
527    progress: UnboundedSender<String>,
528) -> Result<ExecutionOutput, ExecutorError> {
529    let mut child = tokio::process::Command::new(program)
530        .args(args)
531        // Own process group, so the deadline can signal the whole tree rather
532        // than one pid. Without it the kill lands on `sudo`, which has already
533        // forked the privileged work, and the action outlives the timeout that
534        // claims to have stopped it. See issue #140.
535        .process_group(0)
536        // Null stdin, matching `execute_spec`. A background process group with a
537        // controlling terminal would otherwise get SIGTTIN on a stdin read and
538        // stop, burning the whole grace window before SIGKILL. No privileged
539        // action should read the daemon's stdin regardless.
540        .stdin(Stdio::null())
541        .stdout(Stdio::piped())
542        .stderr(Stdio::piped())
543        .spawn()
544        .map_err(ExecutorError::Io)?;
545
546    let stdout = child.stdout.take().expect("stdout was piped");
547    let stderr = child.stderr.take().expect("stderr was piped");
548    let stderr_task = tokio::spawn(async move {
549        let mut buf = Vec::new();
550        BufReader::new(stderr)
551            .read_to_end(&mut buf)
552            .await
553            .map(|_| buf)
554    });
555
556    let deadline = tokio::time::Instant::now() + action_timeout();
557
558    let mut lines = BufReader::new(stdout).lines();
559    let mut stdout_buf = String::new();
560    loop {
561        // The deadline covers the whole action, not each read: a process that
562        // emits one progress line an hour must still be cut off.
563        let next = match tokio::time::timeout_at(deadline, lines.next_line()).await {
564            Ok(Ok(line)) => line,
565            // Losing the read is not a reason to walk away from a running root
566            // child. `lines()` fails with `InvalidData` on non-UTF-8 output, so
567            // this is reachable from any action whose stdout carries a byte
568            // sequence outside UTF-8 — one oddly-encoded filename is enough.
569            Ok(Err(err)) => {
570                return Err(
571                    kill_and_reap(&mut child, program, args, StopCause::Unreadable(err)).await,
572                )
573            }
574            Err(_) => {
575                return Err(kill_and_reap(&mut child, program, args, StopCause::Timeout).await)
576            }
577        };
578        let Some(line) = next else { break };
579        if !line.is_empty() {
580            let _ = progress.send(line.clone());
581        }
582        stdout_buf.push_str(&line);
583        stdout_buf.push('\n');
584    }
585
586    let exit_status = match tokio::time::timeout_at(deadline, child.wait()).await {
587        Ok(Ok(status)) => status,
588        // A failed `wait` leaves the child's fate unknown, which is the one state
589        // the dispatcher must never treat as "stopped".
590        Ok(Err(err)) => {
591            return Err(kill_and_reap(&mut child, program, args, StopCause::Unreadable(err)).await)
592        }
593        Err(_) => return Err(kill_and_reap(&mut child, program, args, StopCause::Timeout).await),
594    };
595    let stderr_bytes = stderr_task
596        .await
597        .map_err(|_| ExecutorError::Io(io::Error::other("stderr reader task panicked")))?
598        .map_err(ExecutorError::Io)?;
599
600    Ok(ExecutionOutput {
601        stdout: stdout_buf,
602        stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
603        exit_code: exit_status.code().unwrap_or(-1),
604    })
605}
606
607/// Map an action name and JSON params to an [`ActionSpec`].
608///
609/// Returns [`ExecutorError::UnknownAction`] for unrecognised names and
610/// [`ExecutorError::MissingParam`] when a required param is absent.
611pub fn build_action_spec(action_name: &str, params: &Value) -> Result<ActionSpec, ExecutorError> {
612    match action_name {
613        // ── Deployment: no params ─────────────────────────────────────────
614        "GetSystemState" => Ok(deployment::get_system_state()),
615        "CollectDiagnostics" => Ok(deployment::collect_diagnostics()),
616        "GetDeploymentHistory" => Ok(deployment::get_deployment_history()),
617        "ListDeployments" => Ok(deployment::list_deployments()),
618        "UpdateSystem" => Ok(deployment::update_system()),
619        "CleanupDeployments" => Ok(deployment::cleanup_deployments()),
620        "RebootSystem" => Ok(deployment::reboot_system()),
621        "RollbackDeployment" => Ok(deployment::rollback_deployment()),
622        "GetKernelArguments" => Ok(deployment::get_kernel_arguments()),
623
624        // ── Deployment: parameterized ─────────────────────────────────────
625        "PinDeployment" => Ok(deployment::pin_deployment(require_u32(params, "index")?)),
626        "UnpinDeployment" => Ok(deployment::unpin_deployment(require_u32(params, "index")?)),
627        "RebaseSystem" => {
628            let target_ref = require_str(params, "target_ref")?;
629            let target_ref = validated_safe_arg(target_ref, "target_ref")?;
630            Ok(deployment::rebase_system(&target_ref))
631        }
632        "SetKernelArguments" => {
633            let add = str_array_or_empty(params, "add")?;
634            let remove = str_array_or_empty(params, "remove")?;
635            // Reject dangerous kernel arguments that could bypass security
636            // mechanisms or give unauthenticated root access on next boot.
637            for arg in add.iter() {
638                validated_safe_kernel_arg(arg, "add")?;
639            }
640            // Removal is screened too: stripping a protective arg reaches the
641            // same end state as adding its weakening counterpart.
642            for arg in remove.iter() {
643                validated_safe_kernel_arg_removal(arg, "remove")?;
644            }
645            let add_refs: Vec<&str> = add.iter().map(String::as_str).collect();
646            let remove_refs: Vec<&str> = remove.iter().map(String::as_str).collect();
647            Ok(deployment::set_kernel_arguments(&add_refs, &remove_refs))
648        }
649
650        // ── Flatpak ───────────────────────────────────────────────────────
651        // All user-scoped Flatpak operations require a `username` param so the
652        // daemon can switch to that user's environment via `runuser -l`. This
653        // ensures operations target the user's Flatpak installation
654        // (~/.local/share/flatpak/) rather than the system store.
655        "ListFlatpakRemotes" => {
656            let username = validated_username(resolve_username(params)?, "username")?;
657            Ok(flatpak::list_flatpak_remotes(&username))
658        }
659        "InstallFlatpak" => {
660            let username = validated_username(resolve_username(params)?, "username")?;
661            let app_id = validated_safe_arg(require_str(params, "app_id")?, "app_id")?;
662            // `remote` defaults to "flathub" — the universal Flatpak remote.
663            // Models frequently omit it; accepting the default avoids a
664            // MissingParam failure for the most common install case.
665            let remote = params
666                .get("remote")
667                .and_then(|v| v.as_str())
668                .unwrap_or("flathub");
669            let remote = validated_safe_arg(remote, "remote")?;
670            Ok(flatpak::install_flatpak(&username, &app_id, &remote))
671        }
672        "RemoveFlatpak" => {
673            let username = validated_username(resolve_username(params)?, "username")?;
674            let app_id = validated_safe_arg(require_str(params, "app_id")?, "app_id")?;
675            Ok(flatpak::remove_flatpak(&username, &app_id))
676        }
677        "SearchFlatpakApps" => {
678            let term = validated_safe_arg(require_str(params, "term")?, "term")?;
679            Ok(flatpak::search_flatpak_apps(&term))
680        }
681        "AddFlatpakRemote" => {
682            let username = validated_username(resolve_username(params)?, "username")?;
683            let remote = validated_safe_arg(require_str(params, "remote")?, "remote")?;
684            let url = validated_safe_arg(require_str(params, "url")?, "url")?;
685            Ok(flatpak::add_flatpak_remote(&username, &remote, &url))
686        }
687        "RemoveFlatpakRemote" => {
688            let username = validated_username(resolve_username(params)?, "username")?;
689            let remote = validated_safe_arg(require_str(params, "remote")?, "remote")?;
690            Ok(flatpak::remove_flatpak_remote(&username, &remote))
691        }
692        "GetFlatpakAppInfo" => {
693            let username = validated_username(resolve_username(params)?, "username")?;
694            let app_id = validated_safe_arg(require_str(params, "app_id")?, "app_id")?;
695            Ok(flatpak::get_flatpak_app_info(&username, &app_id))
696        }
697        "ListInstalledFlatpaks" => {
698            let username = validated_username(resolve_username(params)?, "username")?;
699            Ok(flatpak::list_installed_flatpaks(&username))
700        }
701        "UpdateFlatpak" => {
702            let username = validated_username(resolve_username(params)?, "username")?;
703            // app_id is optional — omitting it updates all installed Flatpaks.
704            // Empty string is treated as absent (no app specified → update all).
705            let app_id = params
706                .get("app_id")
707                .and_then(|v| v.as_str())
708                .filter(|id| !id.is_empty())
709                .map(|id| validated_safe_arg(id, "app_id"))
710                .transpose()?;
711            Ok(flatpak::update_flatpak(&username, app_id.as_deref()))
712        }
713
714        // ── Containers ────────────────────────────────────────────────────
715        // All container operations require a `username` param so the daemon can
716        // switch to that user's rootless Podman environment via `runuser -l`.
717        // Podman storage is per-user; running as the `sysknife` system user
718        // would see an empty, unrelated container store.
719        "ListContainers" => {
720            let username = validated_username(resolve_username(params)?, "username")?;
721            Ok(containers::list_containers(&username))
722        }
723        "CreateContainer" => {
724            let username = validated_username(resolve_username(params)?, "username")?;
725            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
726            let image = validated_safe_arg(require_str(params, "image")?, "image")?;
727            Ok(containers::create_container(&username, &name, &image))
728        }
729        "StartContainer" => {
730            let username = validated_username(resolve_username(params)?, "username")?;
731            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
732            Ok(containers::start_container(&username, &name))
733        }
734        "StopContainer" => {
735            let username = validated_username(resolve_username(params)?, "username")?;
736            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
737            Ok(containers::stop_container(&username, &name))
738        }
739        "RemoveContainer" => {
740            let username = validated_username(resolve_username(params)?, "username")?;
741            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
742            Ok(containers::remove_container(&username, &name))
743        }
744        "GetContainerInfo" => {
745            let username = validated_username(resolve_username(params)?, "username")?;
746            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
747            Ok(containers::get_container_info(&username, &name))
748        }
749
750        // ── Layering ──────────────────────────────────────────────────────
751        "GetLayeredPackages" => Ok(layering::get_layered_packages()),
752        "ResetLayeredPackageOverride" => Ok(layering::reset_layered_package_override()),
753        "InstallPackages" => {
754            let pkgs = str_array_or_empty(params, "packages")?;
755            let validated: Vec<String> = pkgs
756                .iter()
757                .map(|p| validated_install_package(p, "packages"))
758                .collect::<Result<_, _>>()?;
759            let refs: Vec<&str> = validated.iter().map(String::as_str).collect();
760            Ok(layering::install_packages(&refs))
761        }
762        "RemovePackages" => {
763            let pkgs = str_array_or_empty(params, "packages")?;
764            let validated: Vec<String> = pkgs
765                .iter()
766                .map(|p| validated_install_package(p, "packages"))
767                .collect::<Result<_, _>>()?;
768            let refs: Vec<&str> = validated.iter().map(String::as_str).collect();
769            Ok(layering::remove_packages(&refs))
770        }
771        "AddLayeredPackage" => {
772            let package = validated_install_package(require_str(params, "package")?, "package")?;
773            Ok(layering::add_layered_package(&package))
774        }
775        "RemoveLayeredPackage" => {
776            let package = validated_install_package(require_str(params, "package")?, "package")?;
777            Ok(layering::remove_layered_package(&package))
778        }
779        "ReplaceLayeredPackage" => {
780            let old = validated_install_package(require_str(params, "old")?, "old")?;
781            let new = validated_install_package(require_str(params, "new")?, "new")?;
782            Ok(layering::replace_layered_package(&old, &new))
783        }
784        "RemoveBasePackage" => {
785            let package = validated_install_package(require_str(params, "package")?, "package")?;
786            Ok(layering::remove_base_package(&package))
787        }
788        "GetPendingUpdates" => Ok(layering::get_pending_updates()),
789
790        // ── Package repositories ──────────────────────────────────────────
791        "ListPackageRepositories" => Ok(package_repos::list_package_repositories()),
792        "AddPackageRepository" => Ok(package_repos::add_package_repository(
793            validated_repo_id(params)?,
794            validated_no_newline(params, "repo_url")?,
795        )),
796        "RemovePackageRepository" => Ok(package_repos::remove_package_repository(
797            validated_repo_id(params)?,
798        )),
799        "EnablePackageRepository" => Ok(package_repos::enable_package_repository(
800            validated_repo_id(params)?,
801        )),
802        "DisablePackageRepository" => Ok(package_repos::disable_package_repository(
803            validated_repo_id(params)?,
804        )),
805
806        // ── Services ─────────────────────────────────────────────────────
807        "ListServices" => Ok(services::list_services()),
808        "StartService" => {
809            let unit = validated_activatable_unit(require_str(params, "unit")?, "unit")?;
810            Ok(services::start_service(&unit))
811        }
812        "StopService" => {
813            let unit = validated_unit_name(require_str(params, "unit")?, "unit")?;
814            Ok(services::stop_service(&unit))
815        }
816        "RestartService" => {
817            let unit = validated_activatable_unit(require_str(params, "unit")?, "unit")?;
818            Ok(services::restart_service(&unit))
819        }
820        "SetServiceEnabled" => {
821            let enabled = require_bool(params, "enabled")?;
822            // Enabling brings the unit up at boot, so it must clear the root-shell
823            // denylist; disabling one is a mitigation and stays allowed.
824            let unit = if enabled {
825                validated_activatable_unit(require_str(params, "unit")?, "unit")?
826            } else {
827                validated_unit_name(require_str(params, "unit")?, "unit")?
828            };
829            Ok(services::set_service_enabled(&unit, enabled))
830        }
831        "MaskService" => {
832            let unit = validated_unit_name(require_str(params, "unit")?, "unit")?;
833            Ok(services::mask_service(&unit))
834        }
835        "UnmaskService" => {
836            let unit = validated_activatable_unit(require_str(params, "unit")?, "unit")?;
837            Ok(services::unmask_service(&unit))
838        }
839        "GetServiceLogs" => {
840            let unit = validated_unit_name(require_str(params, "unit")?, "unit")?;
841            Ok(services::get_service_logs(&unit))
842        }
843        "GetServiceStatus" => {
844            let unit = validated_unit_name(require_str(params, "unit")?, "unit")?;
845            Ok(services::get_service_status(&unit))
846        }
847        "ReloadService" => {
848            let unit = validated_unit_name(require_str(params, "unit")?, "unit")?;
849            Ok(services::reload_service(&unit))
850        }
851        "ListTimers" => Ok(services::list_timers()),
852        "ReloadDaemon" => Ok(services::reload_daemon()),
853        "CreateScheduledJob" => {
854            // Job name: safe unit stem (no path/dot/@ templating).
855            let name = require_str(params, "name")?;
856            if name.is_empty()
857                || name.len() > 64
858                || !name
859                    .chars()
860                    .next()
861                    .is_some_and(|c| c.is_ascii_alphanumeric())
862                || !name
863                    .chars()
864                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
865            {
866                return Err(ExecutorError::InvalidParam("name"));
867            }
868            // Command: reject control characters (newlines would inject extra
869            // unit directives). systemd argv-splits ExecStart with no shell.
870            let command = require_str(params, "command")?;
871            if command.is_empty()
872                || command.len() > MAX_SCHEDULED_COMMAND_LEN
873                || command.chars().any(|c| c.is_control())
874            {
875                return Err(ExecutorError::InvalidParam("command"));
876            }
877            // Schedule: OnCalendar charset; the helper validates it semantically
878            // with `systemd-analyze calendar`.
879            let schedule = require_str(params, "schedule")?;
880            if schedule.is_empty()
881                || schedule.len() > MAX_SCHEDULE_EXPR_LEN
882                || !schedule.chars().all(|c| {
883                    c.is_ascii_alphanumeric()
884                        || matches!(c, ' ' | ':' | ',' | '*' | '/' | '.' | '~' | '+' | '-')
885                })
886            {
887                return Err(ExecutorError::InvalidParam("schedule"));
888            }
889            Ok(services::create_scheduled_job(name, command, schedule))
890        }
891        "GetServiceResourceLimits" => {
892            let unit = validated_unit_name(require_str(params, "unit")?, "unit")?;
893            Ok(services::get_service_resource_limits(&unit))
894        }
895        "SetServiceResourceLimits" => {
896            let unit = validated_unit_name(require_str(params, "unit")?, "unit")?;
897            // Build validated PROPERTY=VALUE assignments from whichever limits
898            // were supplied; at least one is required.
899            let mut assignments = Vec::new();
900            if let Some(v) = optional_validated(params, "memory_max", validated_memory_limit)? {
901                assignments.push(format!("MemoryMax={v}"));
902            }
903            if let Some(v) = optional_validated(params, "memory_high", validated_memory_limit)? {
904                assignments.push(format!("MemoryHigh={v}"));
905            }
906            if let Some(v) = optional_validated(params, "cpu_quota", validated_cpu_quota)? {
907                assignments.push(format!("CPUQuota={v}"));
908            }
909            if let Some(v) = optional_validated(params, "tasks_max", validated_tasks_max)? {
910                assignments.push(format!("TasksMax={v}"));
911            }
912            if assignments.is_empty() {
913                return Err(ExecutorError::MissingParam("memory_max"));
914            }
915            Ok(services::set_service_resource_limits(&unit, &assignments))
916        }
917
918        // ── Toolbox ───────────────────────────────────────────────────────
919        // Toolbox operations require a `username` param — toolbox containers are
920        // per-user (rootless Podman) and must be managed in the user's context.
921        "ListToolboxes" => {
922            let username = validated_username(resolve_username(params)?, "username")?;
923            Ok(toolbox::list_toolboxes(&username))
924        }
925        "CreateToolbox" => {
926            let username = validated_username(resolve_username(params)?, "username")?;
927            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
928            let image = params
929                .get("image")
930                .and_then(|v| v.as_str())
931                .map(|img| validated_safe_arg(img, "image"))
932                .transpose()?;
933            let release = params
934                .get("release")
935                .and_then(|v| v.as_str())
936                .map(|r| validated_safe_arg(r, "release"))
937                .transpose()?;
938            Ok(toolbox::create_toolbox(
939                &username,
940                &name,
941                release.as_deref(),
942                image.as_deref(),
943            ))
944        }
945        "RemoveToolbox" => {
946            let username = validated_username(resolve_username(params)?, "username")?;
947            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
948            Ok(toolbox::remove_toolbox(&username, &name))
949        }
950
951        // ── Identity ─────────────────────────────────────────────────────
952        "GetDateTime" => Ok(identity::get_datetime()),
953        "SetHostname" => {
954            let hostname = validated_hostname(require_str(params, "hostname")?, "hostname")?;
955            Ok(identity::set_hostname(&hostname))
956        }
957        "SetTimezone" => {
958            let timezone = validated_timezone(require_str(params, "timezone")?, "timezone")?;
959            Ok(identity::set_timezone(&timezone))
960        }
961        "SetLocale" => {
962            let locale = validated_locale(require_str(params, "locale")?, "locale")?;
963            Ok(identity::set_locale(&locale))
964        }
965        "SetNtp" => Ok(identity::set_ntp(require_bool(params, "enabled")?)),
966
967        // ── Filesystem ────────────────────────────────────────────────────
968        "GetDiskUsage" => Ok(filesystem::disk_usage_spec()),
969
970        // ── Processes ────────────────────────────────────────────────────
971        "ListProcesses" => Ok(processes::list_processes_spec()),
972        "SignalProcess" => {
973            // pid may arrive as a JSON number or a numeric string.
974            let pid = params
975                .get("pid")
976                .and_then(|v| {
977                    v.as_u64()
978                        .or_else(|| v.as_str().and_then(|s| s.trim().parse::<u64>().ok()))
979                })
980                .ok_or(ExecutorError::MissingParam("pid"))?;
981            // Reject pid 0 (whole process group) and 1 (init/systemd); anything
982            // outside the u32 pid space is invalid.
983            if pid < 2 || pid > u32::MAX as u64 {
984                return Err(ExecutorError::InvalidParam("pid"));
985            }
986            let signal = validated_kill_signal(
987                params
988                    .get("signal")
989                    .and_then(|v| v.as_str())
990                    .unwrap_or("TERM"),
991            )?;
992            Ok(processes::signal_process(pid as u32, signal))
993        }
994
995        // ── Journald ──────────────────────────────────────────────────────
996        "GetJournalLog" => {
997            let unit = optional_validated(params, "unit", validated_unit_name)?;
998            let priority = optional_validated(params, "priority", validated_journal_priority)?;
999            let since = optional_validated(params, "since", validated_journal_time)?;
1000            let until = optional_validated(params, "until", validated_journal_time)?;
1001            let grep = optional_validated(params, "grep", validated_journal_grep)?;
1002            // `lines` defaults to 100 and is clamped so an enormous value cannot
1003            // make the daemon buffer an unbounded journal dump.
1004            let lines = params
1005                .get("lines")
1006                .and_then(|v| v.as_u64())
1007                .unwrap_or(100)
1008                .clamp(1, MAX_JOURNAL_LINES) as u32;
1009            let boot = params
1010                .get("boot")
1011                .and_then(|v| v.as_bool())
1012                .unwrap_or(false);
1013            let kernel = params
1014                .get("kernel")
1015                .and_then(|v| v.as_bool())
1016                .unwrap_or(false);
1017            Ok(journald::get_journal_log(&journald::JournalQuery {
1018                lines,
1019                unit: unit.as_deref(),
1020                priority: priority.as_deref(),
1021                boot,
1022                kernel,
1023                since: since.as_deref(),
1024                until: until.as_deref(),
1025                grep: grep.as_deref(),
1026            }))
1027        }
1028        "VacuumJournal" => {
1029            // Exactly one of size_mb / retain_days selects the vacuum mode.
1030            let size_mb = params.get("size_mb").and_then(|v| v.as_u64());
1031            let retain_days = params.get("retain_days").and_then(|v| v.as_u64());
1032            match (size_mb, retain_days) {
1033                (Some(mb), None) if (1..=u32::MAX as u64).contains(&mb) => {
1034                    Ok(journald::vacuum_journal_by_size(mb as u32))
1035                }
1036                (None, Some(days)) if (1..=u32::MAX as u64).contains(&days) => {
1037                    Ok(journald::vacuum_journal_by_time(days as u32))
1038                }
1039                (None, None) => Err(ExecutorError::MissingParam("size_mb")),
1040                // both supplied, or an out-of-range value
1041                _ => Err(ExecutorError::InvalidParam("size_mb")),
1042            }
1043        }
1044
1045        // ── Storage / LVM ───────────────────────────────────────────────────
1046        "GetLvmReport" => Ok(lvm::get_lvm_report()),
1047        "ExtendLogicalVolume" => {
1048            let vg = validated_lvm_name(require_str(params, "vg")?, "vg")?;
1049            let lv = validated_lvm_name(require_str(params, "lv")?, "lv")?;
1050            let size = validated_lvm_size(require_str(params, "size")?, "size")?;
1051            Ok(lvm::extend_logical_volume(&vg, &lv, &size))
1052        }
1053        "CreateLogicalVolume" => {
1054            let vg = validated_lvm_name(require_str(params, "vg")?, "vg")?;
1055            let name = validated_lvm_name(require_str(params, "name")?, "name")?;
1056            let size = validated_lvm_size(require_str(params, "size")?, "size")?;
1057            Ok(lvm::create_logical_volume(&vg, &name, &size))
1058        }
1059        "CreateLvSnapshot" => {
1060            let vg = validated_lvm_name(require_str(params, "vg")?, "vg")?;
1061            let origin = validated_lvm_name(require_str(params, "origin")?, "origin")?;
1062            let snapshot = validated_lvm_name(require_str(params, "snapshot")?, "snapshot")?;
1063            let size = validated_lvm_size(require_str(params, "size")?, "size")?;
1064            Ok(lvm::create_lv_snapshot(&vg, &origin, &snapshot, &size))
1065        }
1066
1067        // ── Kernel / sysctl ─────────────────────────────────────────────────
1068        "GetSysctl" => {
1069            // `key` is optional — absent means dump the whole table (sysctl -a).
1070            let key = optional_validated(params, "key", validated_sysctl_key)?;
1071            Ok(sysctl::get_sysctl(key.as_deref()))
1072        }
1073        "SetSysctl" => {
1074            let key = validated_sysctl_key(require_str(params, "key")?, "key")?;
1075            let value = validated_sysctl_value(require_str(params, "value")?, "value")?;
1076            Ok(sysctl::set_sysctl(&key, &value))
1077        }
1078
1079        // ── Filesystem mounts / swap ────────────────────────────────────────
1080        "GetMounts" => Ok(mounts::get_mounts()),
1081        "AddMount" => {
1082            let device = validated_mount_device(require_str(params, "device")?, "device")?;
1083            let mountpoint =
1084                validated_mount_point(require_str(params, "mountpoint")?, "mountpoint")?;
1085            let fstype = validated_fstype(require_str(params, "fstype")?, "fstype")?;
1086            let options = optional_validated(params, "options", validated_mount_options)?;
1087            Ok(mounts::add_mount(
1088                &device,
1089                &mountpoint,
1090                &fstype,
1091                options.as_deref(),
1092            ))
1093        }
1094        "RemoveMount" => {
1095            let mountpoint =
1096                validated_mount_point(require_str(params, "mountpoint")?, "mountpoint")?;
1097            Ok(mounts::remove_mount(&mountpoint))
1098        }
1099        "AddSwap" => {
1100            let file = validated_swap_path(require_str(params, "file")?, "file")?;
1101            let size_mb = require_u32(params, "size_mb")?;
1102            // 1 MiB .. 1 TiB — reject 0 (empty) and absurdly large requests.
1103            if !(1..=MAX_SWAP_SIZE_MB).contains(&size_mb) {
1104                return Err(ExecutorError::InvalidParam("size_mb"));
1105            }
1106            Ok(mounts::add_swap(&file, size_mb))
1107        }
1108        "RemoveSwap" => {
1109            let file = validated_swap_path(require_str(params, "file")?, "file")?;
1110            Ok(mounts::remove_swap(&file))
1111        }
1112
1113        // ── Scoped sudoers.d ────────────────────────────────────────────────
1114        "GetSudoGrants" => Ok(sudoers::get_sudo_grants()),
1115        "GrantSudoAccess" => {
1116            let name = validated_sudoers_name(require_str(params, "name")?, "name")?;
1117            let user = validated_username(require_str(params, "user")?, "user")?;
1118            let commands = validated_sudo_commands(require_str(params, "commands")?, "commands")?;
1119            // runas defaults to root; if given it must be "ALL" or a username.
1120            let runas = match params
1121                .get("runas")
1122                .and_then(|v| v.as_str())
1123                .filter(|s| !s.is_empty())
1124            {
1125                Some("ALL") => Some("ALL".to_string()),
1126                Some(u) => Some(validated_username(u, "runas")?),
1127                None => None,
1128            };
1129            let nopasswd = params
1130                .get("nopasswd")
1131                .and_then(|v| v.as_bool())
1132                .unwrap_or(false);
1133            // `commands = "ALL"` together with `nopasswd` mints a standing,
1134            // passwordless, unrestricted root credential (`user ALL=(ALL)
1135            // NOPASSWD: ALL`). Unlike every other action here, the effect
1136            // outlives the job: it is a permanent privilege grant, not a
1137            // one-time change, and it is indistinguishable from the daemon's
1138            // own authority thereafter. Require the caller to give up one of
1139            // the two dimensions — scope the commands, or keep the password
1140            // prompt. `visudo` would happily accept the combination, so this
1141            // is the only place it can be refused.
1142            if commands == "ALL" && nopasswd {
1143                return Err(ExecutorError::InvalidParam("commands"));
1144            }
1145            Ok(sudoers::grant_sudo_access(
1146                &name,
1147                &user,
1148                &commands,
1149                runas.as_deref(),
1150                nopasswd,
1151            ))
1152        }
1153        "RevokeSudoAccess" => {
1154            let name = validated_sudoers_name(require_str(params, "name")?, "name")?;
1155            Ok(sudoers::revoke_sudo_access(&name))
1156        }
1157
1158        // ── apt pinning (preferences.d) ─────────────────────────────────────
1159        "GetAptPins" => {
1160            let package = optional_validated(params, "package", validated_apt_package)?;
1161            Ok(apt_preferences::get_apt_pins(package.as_deref()))
1162        }
1163        "SetAptPin" => {
1164            let name = validated_apt_pin_name(require_str(params, "name")?, "name")?;
1165            let package = validated_apt_package(require_str(params, "package")?, "package")?;
1166            let pin = validated_apt_pin_expr(require_str(params, "pin")?, "pin")?;
1167            let priority = params
1168                .get("priority")
1169                .and_then(|v| v.as_i64())
1170                .ok_or(ExecutorError::MissingParam("priority"))?;
1171            if !(-1..=1000).contains(&priority) {
1172                return Err(ExecutorError::InvalidParam("priority"));
1173            }
1174            Ok(apt_preferences::set_apt_pin(
1175                &name, &package, &pin, priority,
1176            ))
1177        }
1178        "RemoveAptPin" => {
1179            let name = validated_apt_pin_name(require_str(params, "name")?, "name")?;
1180            Ok(apt_preferences::remove_apt_pin(&name))
1181        }
1182
1183        // ── Log management (logrotate + rsyslog) ────────────────────────────
1184        "GetLogrotateStatus" => {
1185            let config = optional_validated(params, "config", validated_log_path)?;
1186            Ok(logging::get_logrotate_status(config.as_deref()))
1187        }
1188        "ConfigureLogRotation" => {
1189            let name = validated_sudoers_name(require_str(params, "name")?, "name")?;
1190            let path = validated_log_path(require_str(params, "path")?, "path")?;
1191            let frequency = require_str(params, "frequency")?;
1192            if !matches!(frequency, "daily" | "weekly" | "monthly") {
1193                return Err(ExecutorError::InvalidParam("frequency"));
1194            }
1195            let rotate = require_u32(params, "rotate")?;
1196            if rotate > 1000 {
1197                return Err(ExecutorError::InvalidParam("rotate"));
1198            }
1199            let compress = params
1200                .get("compress")
1201                .and_then(|v| v.as_bool())
1202                .unwrap_or(false);
1203            Ok(logging::configure_log_rotation(
1204                &name, &path, frequency, rotate, compress,
1205            ))
1206        }
1207        "RemoveLogRotation" => {
1208            let name = validated_sudoers_name(require_str(params, "name")?, "name")?;
1209            Ok(logging::remove_log_rotation(&name))
1210        }
1211        "ConfigureRemoteSyslog" => {
1212            let host = validated_syslog_host(require_str(params, "host")?, "host")?;
1213            let port = require_u32(params, "port")?;
1214            if !(1..=crate::actions::validate::MAX_PORT).contains(&port) {
1215                return Err(ExecutorError::InvalidParam("port"));
1216            }
1217            let protocol = require_str(params, "protocol")?;
1218            if !matches!(protocol, "tcp" | "udp") {
1219                return Err(ExecutorError::InvalidParam("protocol"));
1220            }
1221            Ok(logging::configure_remote_syslog(
1222                &host,
1223                port as u16,
1224                protocol,
1225            ))
1226        }
1227        "RemoveRemoteSyslog" => Ok(logging::remove_remote_syslog()),
1228
1229        // ── PAM password policy ───────────────────────────────────────────
1230        "GetPasswordAging" => {
1231            let user = validated_username(require_str(params, "user")?, "user")?;
1232            Ok(pam::get_password_aging(&user))
1233        }
1234        "SetPasswordAging" => {
1235            let user = validated_username(require_str(params, "user")?, "user")?;
1236            // chage days: 0..=99999 (chage's own ceiling). At least one required.
1237            let mut flags = Vec::new();
1238            for (key, opt) in [("max_days", "-M"), ("min_days", "-m"), ("warn_days", "-W")] {
1239                if let Some(n) = params.get(key).and_then(|v| v.as_u64()) {
1240                    if n > MAX_PASSWORD_AGE_DAYS {
1241                        return Err(ExecutorError::InvalidParam(key));
1242                    }
1243                    flags.push(opt.to_string());
1244                    flags.push(n.to_string());
1245                }
1246            }
1247            if flags.is_empty() {
1248                return Err(ExecutorError::MissingParam("max_days"));
1249            }
1250            Ok(pam::set_password_aging(&user, &flags))
1251        }
1252        "SetPasswordPolicy" => {
1253            // minlen 1..=128; *credit knobs -64..=64 (negative = require that
1254            // many chars of the class). At least one required.
1255            let mut extra = Vec::new();
1256            if let Some(n) = params.get("minlen").and_then(|v| v.as_u64()) {
1257                if !(1..=MAX_PASSWORD_MINLEN).contains(&n) {
1258                    return Err(ExecutorError::InvalidParam("minlen"));
1259                }
1260                extra.push("--minlen".to_string());
1261                extra.push(n.to_string());
1262            }
1263            for (key, flag) in [
1264                ("dcredit", "--dcredit"),
1265                ("ucredit", "--ucredit"),
1266                ("lcredit", "--lcredit"),
1267                ("ocredit", "--ocredit"),
1268            ] {
1269                if let Some(n) = params.get(key).and_then(|v| v.as_i64()) {
1270                    if !(-64..=64).contains(&n) {
1271                        return Err(ExecutorError::InvalidParam(key));
1272                    }
1273                    extra.push(flag.to_string());
1274                    extra.push(n.to_string());
1275                }
1276            }
1277            if extra.is_empty() {
1278                return Err(ExecutorError::MissingParam("minlen"));
1279            }
1280            Ok(pam::set_password_policy(&extra))
1281        }
1282        "SetAccountLockout" => {
1283            // deny 1..=1000; unlock_time/fail_interval seconds 0..=604800 (7d).
1284            let mut extra = Vec::new();
1285            if let Some(n) = params.get("deny").and_then(|v| v.as_u64()) {
1286                if !(1..=1000).contains(&n) {
1287                    return Err(ExecutorError::InvalidParam("deny"));
1288                }
1289                extra.push("--deny".to_string());
1290                extra.push(n.to_string());
1291            }
1292            for (key, flag) in [
1293                ("unlock_time", "--unlock-time"),
1294                ("fail_interval", "--fail-interval"),
1295            ] {
1296                if let Some(n) = params.get(key).and_then(|v| v.as_u64()) {
1297                    if n > MAX_LOCKOUT_WINDOW_SECS {
1298                        return Err(ExecutorError::InvalidParam(key));
1299                    }
1300                    extra.push(flag.to_string());
1301                    extra.push(n.to_string());
1302                }
1303            }
1304            if extra.is_empty() {
1305                return Err(ExecutorError::MissingParam("deny"));
1306            }
1307            Ok(pam::set_account_lockout(&extra))
1308        }
1309
1310        // ── System info ──────────────────────────────────────────────────
1311        "GetMemoryInfo" => Ok(system_info::get_memory_info_spec()),
1312        "GetHostState" => Ok(system_info::get_host_state()),
1313
1314        // ── Network ───────────────────────────────────────────────────────
1315        "GetFirewallState" => Ok(network::get_firewall_state()),
1316        "GetNetworkStatus" => Ok(network::get_network_status()),
1317        "GetListeningPorts" => Ok(network::get_listening_ports()),
1318        "ConfigureWifi" => {
1319            let ssid = validated_safe_arg(require_str(params, "ssid")?, "ssid")?;
1320            // password is optional — open networks connect without one.
1321            let password = params
1322                .get("password")
1323                .and_then(|v| v.as_str())
1324                .filter(|p| !p.is_empty())
1325                .map(|p| validated_safe_arg(p, "password"))
1326                .transpose()?;
1327            Ok(network::configure_wifi(&ssid, password.as_deref()))
1328        }
1329        "SetDnsServers" => {
1330            let interface = validated_safe_arg(require_str(params, "interface")?, "interface")?;
1331            let servers = str_array_or_empty(params, "servers")?;
1332            let validated: Vec<String> = servers
1333                .iter()
1334                .map(|s| validated_safe_arg(s, "servers"))
1335                .collect::<Result<_, _>>()?;
1336            let refs: Vec<&str> = validated.iter().map(String::as_str).collect();
1337            Ok(network::set_dns_servers(&interface, &refs))
1338        }
1339        "ConfigureFirewall" => {
1340            let zone = validated_safe_arg(require_str(params, "zone")?, "zone")?;
1341            let service = validated_safe_arg(require_str(params, "service")?, "service")?;
1342            Ok(network::configure_firewall(
1343                &zone,
1344                &service,
1345                require_bool(params, "enabled")?,
1346            ))
1347        }
1348
1349        // ── Users ─────────────────────────────────────────────────────────
1350        "ListUsers" => Ok(users::list_users()),
1351        "ListGroups" => Ok(users::list_groups()),
1352        "CreateUser" => {
1353            let username = validated_username(resolve_username(params)?, "username")?;
1354            let shell = params
1355                .get("shell")
1356                .and_then(|v| v.as_str())
1357                .map(|s| validated_safe_arg(s, "shell"))
1358                .transpose()?;
1359            let home = params
1360                .get("home")
1361                .and_then(|v| v.as_str())
1362                .map(|h| validated_safe_arg(h, "home"))
1363                .transpose()?;
1364            Ok(users::create_user(
1365                &username,
1366                shell.as_deref(),
1367                home.as_deref(),
1368            ))
1369        }
1370        "DeleteUser" => {
1371            let username = validated_username_not_critical(resolve_username(params)?, "username")?;
1372            Ok(users::delete_user(&username))
1373        }
1374        "AddUserToGroup" => {
1375            let username = validated_username(resolve_username(params)?, "username")?;
1376            let group = validated_group(require_str(params, "group")?, "group")?;
1377            Ok(users::add_user_to_group(&username, &group))
1378        }
1379        "RemoveUserFromGroup" => {
1380            let username = validated_username(resolve_username(params)?, "username")?;
1381            let group = validated_group(require_str(params, "group")?, "group")?;
1382            Ok(users::remove_user_from_group(&username, &group))
1383        }
1384        "CreateGroup" => {
1385            let group = validated_group(require_str(params, "group")?, "group")?;
1386            let system = params
1387                .get("system")
1388                .and_then(|v| v.as_bool())
1389                .unwrap_or(false);
1390            Ok(users::create_group(&group, system))
1391        }
1392        "DeleteGroup" => {
1393            let group = validated_group_not_critical(require_str(params, "group")?, "group")?;
1394            Ok(users::delete_group(&group))
1395        }
1396        "LockUserAccount" => {
1397            let username = validated_username_not_critical(resolve_username(params)?, "username")?;
1398            Ok(users::lock_user_account(&username))
1399        }
1400        "UnlockUserAccount" => {
1401            let username = validated_username(resolve_username(params)?, "username")?;
1402            Ok(users::unlock_user_account(&username))
1403        }
1404
1405        // ── SSH ──────────────────────────────────────────────────────────
1406        "GetAuthorizedKeys" => {
1407            let username = validated_username(resolve_username(params)?, "username")?;
1408            Ok(ssh::get_authorized_keys(&username))
1409        }
1410        "AddAuthorizedKey" => {
1411            let username = validated_username(resolve_username(params)?, "username")?;
1412            let public_key = validated_public_key(require_str(params, "public_key")?)?;
1413            Ok(ssh::add_authorized_key(&username, &public_key))
1414        }
1415        "RemoveAuthorizedKey" => {
1416            let username = validated_username(resolve_username(params)?, "username")?;
1417            let public_key = validated_public_key(require_str(params, "public_key")?)?;
1418            Ok(ssh::remove_authorized_key(&username, &public_key))
1419        }
1420        "SetSshdOption" => {
1421            // Allowlist the option name and its permitted values (the helper
1422            // re-validates as defense-in-depth). This is deliberately not an
1423            // arbitrary sshd_config editor.
1424            let option = require_str(params, "option")?;
1425            let value = require_str(params, "value")?;
1426            let allowed_values: &[&str] = match option {
1427                "PermitRootLogin" => &["yes", "no", "prohibit-password", "forced-commands-only"],
1428                "PasswordAuthentication"
1429                | "PubkeyAuthentication"
1430                | "X11Forwarding"
1431                | "PermitEmptyPasswords" => &["yes", "no"],
1432                _ => return Err(ExecutorError::InvalidParam("option")),
1433            };
1434            if !allowed_values.contains(&value) {
1435                return Err(ExecutorError::InvalidParam("value"));
1436            }
1437            Ok(ssh::set_sshd_option(option, value))
1438        }
1439
1440        // ── apt ──────────────────────────────────────────────────────────
1441        "AptUpdate" => Ok(apt::apt_update()),
1442        "AptUpgrade" => Ok(apt::apt_upgrade()),
1443        "AptInstall" => {
1444            let package = validated_install_package(require_str(params, "package")?, "package")?;
1445            Ok(apt::apt_install(&package))
1446        }
1447        "AptRemove" => {
1448            let package = validated_install_package(require_str(params, "package")?, "package")?;
1449            Ok(apt::apt_remove(&package))
1450        }
1451        "AptPurge" => {
1452            let package = validated_install_package(require_str(params, "package")?, "package")?;
1453            Ok(apt::apt_purge(&package))
1454        }
1455        "AptAutoremove" => Ok(apt::apt_autoremove()),
1456        "AptHold" => {
1457            let package = validated_install_package(require_str(params, "package")?, "package")?;
1458            Ok(apt::apt_hold(&package))
1459        }
1460        "AptUnhold" => {
1461            let package = validated_install_package(require_str(params, "package")?, "package")?;
1462            Ok(apt::apt_unhold(&package))
1463        }
1464        "AptSearch" => {
1465            let term = validated_safe_arg(require_str(params, "term")?, "term")?;
1466            Ok(apt::apt_search(&term))
1467        }
1468        "AptListInstalled" => Ok(apt::apt_list_installed()),
1469        "AptShow" => {
1470            let package = validated_safe_arg(require_str(params, "package")?, "package")?;
1471            Ok(apt::apt_show(&package))
1472        }
1473        "AptListUpgradable" => Ok(apt::apt_list_upgradable()),
1474        "AptHistoryList" => Ok(apt::apt_history_list()),
1475        "ConfigureUnattendedUpgrades" => Ok(apt::configure_unattended_upgrades(require_bool(
1476            params, "enabled",
1477        )?)),
1478
1479        // ── ppa ──────────────────────────────────────────────────────────
1480        "AddPpa" => {
1481            let name = validated_ppa_name(require_str(params, "name")?, "name")?;
1482            Ok(ppa::add_ppa(&name))
1483        }
1484        "RemovePpa" => {
1485            let name = validated_ppa_name(require_str(params, "name")?, "name")?;
1486            Ok(ppa::remove_ppa(&name))
1487        }
1488
1489        // ── snap ─────────────────────────────────────────────────────────
1490        "SnapInstall" => {
1491            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1492            let channel = params
1493                .get("channel")
1494                .and_then(|v| v.as_str())
1495                .filter(|s| !s.is_empty())
1496                .map(|s| validated_safe_arg(s, "channel"))
1497                .transpose()?;
1498            let auto_update = params
1499                .get("auto_update")
1500                .and_then(|v| v.as_bool())
1501                .unwrap_or(false);
1502            snap::snap_install(&name, channel.as_deref(), auto_update).map_err(|e| match e {
1503                snap::SnapInstallError::InvalidArg { param, .. } => {
1504                    ExecutorError::InvalidParam(param)
1505                }
1506            })
1507        }
1508        "SnapRemove" => {
1509            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1510            Ok(snap::snap_remove(&name))
1511        }
1512        "SnapRefresh" => {
1513            let name = params
1514                .get("name")
1515                .and_then(|v| v.as_str())
1516                .filter(|s| !s.is_empty())
1517                .map(|s| validated_safe_arg(s, "name"))
1518                .transpose()?;
1519            Ok(snap::snap_refresh(name.as_deref()))
1520        }
1521        "SnapHold" => {
1522            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1523            Ok(snap::snap_hold(&name))
1524        }
1525        "SnapUnhold" => {
1526            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1527            Ok(snap::snap_unhold(&name))
1528        }
1529        "SnapList" => Ok(snap::snap_list()),
1530        "SnapInfo" => {
1531            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1532            Ok(snap::snap_info(&name))
1533        }
1534        "SnapRevert" => {
1535            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1536            Ok(snap::snap_revert(&name))
1537        }
1538        "SnapClassicInstall" => {
1539            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1540            Ok(snap::snap_classic_install(&name))
1541        }
1542
1543        // ── grub ─────────────────────────────────────────────────────────
1544        "GrubGetKargs" => Ok(grub::grub_get_kargs()),
1545        "GrubSetKargs" => {
1546            let append: Vec<String> = params
1547                .get("append")
1548                .and_then(|v| v.as_array())
1549                .map(|arr| {
1550                    arr.iter()
1551                        .filter_map(|v| v.as_str())
1552                        .map(String::from)
1553                        .collect()
1554                })
1555                .unwrap_or_default();
1556            let delete: Vec<String> = params
1557                .get("delete")
1558                .and_then(|v| v.as_array())
1559                .map(|arr| {
1560                    arr.iter()
1561                        .filter_map(|v| v.as_str())
1562                        .map(String::from)
1563                        .collect()
1564                })
1565                .unwrap_or_default();
1566            // Validate each arg in both lists. `append` gets the charset check
1567            // (rejects `=`, `,`, shell metacharacters — the latter also blocks
1568            // CSV injection into the helper's comma-separated list) *and* the
1569            // kernel-arg denylist, so a bare `single`/`s`/`1` cannot boot the
1570            // host into a single-user root shell — parity with
1571            // SetKernelArguments. `delete` gets the charset check plus the
1572            // removal screen: dropping `module.sig_enforce=1` or `lockdown=`
1573            // weakens the next boot exactly as adding its counterpart would.
1574            for a in &append {
1575                validated_safe_arg(a, "append")?;
1576                validated_safe_kernel_arg(a, "append")?;
1577            }
1578            for d in &delete {
1579                validated_safe_arg(d, "delete")?;
1580                validated_safe_kernel_arg_removal(d, "delete")?;
1581            }
1582            // The constructor itself enforces "at least one of append/delete
1583            // non-empty" — this is the single source of truth for the invariant.
1584            let append_refs: Vec<&str> = append.iter().map(String::as_str).collect();
1585            let delete_refs: Vec<&str> = delete.iter().map(String::as_str).collect();
1586            grub::grub_set_kargs(&append_refs, &delete_refs)
1587                .map_err(|_| ExecutorError::MissingParam("append or delete"))
1588        }
1589
1590        // ── reboot ────────────────────────────────────────────────────────
1591        "CheckPendingReboot" => Ok(reboot::check_pending_reboot()),
1592
1593        // ── ufw ──────────────────────────────────────────────────────────
1594        "UfwEnable" => Ok(ufw::ufw_enable()),
1595        "UfwDisable" => Ok(ufw::ufw_disable()),
1596        "UfwAllow" => {
1597            let port_or_service = validated_port_or_service(
1598                require_str(params, "port_or_service")?,
1599                "port_or_service",
1600            )?;
1601            Ok(ufw::ufw_allow(&port_or_service))
1602        }
1603        "UfwDeny" => {
1604            let port_or_service = validated_port_or_service(
1605                require_str(params, "port_or_service")?,
1606                "port_or_service",
1607            )?;
1608            Ok(ufw::ufw_deny(&port_or_service))
1609        }
1610        "UfwReset" => Ok(ufw::ufw_reset()),
1611        "UfwStatus" => {
1612            let numbered = match params.get("numbered") {
1613                None => false,
1614                Some(value) => value
1615                    .as_bool()
1616                    .ok_or(ExecutorError::InvalidParam("numbered"))?,
1617            };
1618            Ok(ufw::ufw_status_with_numbered(numbered))
1619        }
1620
1621        // ── distrobox ────────────────────────────────────────────────────
1622        "DistroboxList" => Ok(distrobox::distrobox_list()),
1623        "DistroboxCreate" => {
1624            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1625            let image = validated_safe_arg(require_str(params, "image")?, "image")?;
1626            Ok(distrobox::distrobox_create(&name, &image))
1627        }
1628        "DistroboxRemove" => {
1629            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1630            Ok(distrobox::distrobox_remove(&name))
1631        }
1632
1633        // ── netplan ──────────────────────────────────────────────────────
1634        "NetplanGetConfig" => Ok(netplan::netplan_get_config()),
1635        "NetplanApply" => Ok(netplan::netplan_apply()),
1636        "NetplanSet" => {
1637            let key = validated_safe_arg(require_str(params, "key")?, "key")?;
1638            let value = validated_safe_arg(require_str(params, "value")?, "value")?;
1639            Ok(netplan::netplan_set(&key, &value))
1640        }
1641        "NetplanGenerate" => Ok(netplan::netplan_generate()),
1642
1643        // ── ufw Tier 3 ────────────────────────────────────────────────────
1644        "UfwDeleteRule" => {
1645            let rule_number = require_positive_u32(params, "rule_number")?;
1646            ufw::ufw_delete_rule(rule_number)
1647                .map_err(|_| ExecutorError::InvalidParam("rule_number"))
1648        }
1649        "UfwLimit" => {
1650            let target = validated_port_or_service(require_str(params, "target")?, "target")?;
1651            Ok(ufw::ufw_limit(&target))
1652        }
1653
1654        // ── Ubuntu Pro ────────────────────────────────────────────────────
1655        "ProStatus" => Ok(ubuntu_pro::pro_status()),
1656        "ProAttach" => {
1657            // token is a credential: read it from params but do NOT log it.
1658            let token = require_str(params, "token")?;
1659            // Minimal structural validation: non-empty, no shell metacharacters.
1660            let token = validated_safe_arg(token, "token")?;
1661            Ok(ubuntu_pro::pro_attach(&token))
1662        }
1663        "ProDetach" => Ok(ubuntu_pro::pro_detach()),
1664        "EnableProService" => {
1665            let service = validated_pro_service(require_str(params, "service")?, "service")?;
1666            Ok(ubuntu_pro::enable_pro_service(&service))
1667        }
1668        "DisableProService" => {
1669            let service = validated_pro_service(require_str(params, "service")?, "service")?;
1670            Ok(ubuntu_pro::disable_pro_service(&service))
1671        }
1672
1673        // ── Livepatch ─────────────────────────────────────────────────────
1674        "LivepatchStatus" => Ok(livepatch::livepatch_status()),
1675
1676        // ── Multipass ─────────────────────────────────────────────────────
1677        "MultipassList" => Ok(multipass::multipass_list()),
1678
1679        // ── Release upgrade ───────────────────────────────────────────────
1680        "UbuntuReleaseUpgrade" => Ok(release_upgrade::ubuntu_release_upgrade()),
1681
1682        // ── resolvectl (cross-distro / systemd-resolved) ──────────────────
1683        "ResolvectlStatus" => Ok(resolvectl::resolvectl_status()),
1684        "ResolvectlSetDns" => {
1685            let interface = validated_safe_arg(require_str(params, "interface")?, "interface")?;
1686            let raw_servers: Vec<String> = params
1687                .get("servers")
1688                .and_then(|v| v.as_array())
1689                .map(|arr| {
1690                    arr.iter()
1691                        .filter_map(|v| v.as_str())
1692                        .map(String::from)
1693                        .collect()
1694                })
1695                .unwrap_or_default();
1696            if raw_servers.is_empty() {
1697                return Err(ExecutorError::MissingParam("servers"));
1698            }
1699            // Parse every server string as a typed IpAddr before passing to the
1700            // constructor. This rejects leading-dash strings (flag injection) and
1701            // malformed addresses that would silently misconfigure systemd-resolved.
1702            let mut parsed_servers: Vec<IpAddr> = Vec::with_capacity(raw_servers.len());
1703            for s in &raw_servers {
1704                let addr = IpAddr::from_str(s).map_err(|_| ExecutorError::InvalidIpAddress {
1705                    param: "servers",
1706                    value: s.clone(),
1707                })?;
1708                parsed_servers.push(addr);
1709            }
1710            Ok(resolvectl::resolvectl_set_dns(&interface, &parsed_servers))
1711        }
1712
1713        // ── apparmor ──────────────────────────────────────────────────────
1714        "AppArmorStatus" => Ok(apparmor::apparmor_status()),
1715        "AppArmorEnforce" => {
1716            let profile_path =
1717                validated_apparmor_profile(require_str(params, "profile_path")?, "profile_path")?;
1718            Ok(apparmor::apparmor_enforce(&profile_path))
1719        }
1720        "AppArmorComplain" => {
1721            let profile_path =
1722                validated_apparmor_profile(require_str(params, "profile_path")?, "profile_path")?;
1723            Ok(apparmor::apparmor_complain(&profile_path))
1724        }
1725
1726        // ── cloud-init ────────────────────────────────────────────────────
1727        "CloudInitStatus" => Ok(cloudinit::cloud_init_status()),
1728
1729        // ── Ubuntu Flatpak ─────────────────────────────────────────────────
1730        "UbuntuInstallFlatpak" => {
1731            let username = validated_username(resolve_username(params)?, "username")?;
1732            let app_id = validated_safe_arg(require_str(params, "app_id")?, "app_id")?;
1733            let remote = validated_safe_arg(require_str(params, "remote")?, "remote")?;
1734            Ok(flatpak::ubuntu_install_flatpak(&username, &app_id, &remote))
1735        }
1736        "UbuntuRemoveFlatpak" => {
1737            let username = validated_username(resolve_username(params)?, "username")?;
1738            let app_id = validated_safe_arg(require_str(params, "app_id")?, "app_id")?;
1739            Ok(flatpak::ubuntu_remove_flatpak(&username, &app_id))
1740        }
1741        "UbuntuUpdateFlatpak" => {
1742            let username = validated_username(resolve_username(params)?, "username")?;
1743            let app_id = params
1744                .get("app_id")
1745                .and_then(|v| v.as_str())
1746                .filter(|s| !s.is_empty())
1747                .map(|s| validated_safe_arg(s, "app_id"))
1748                .transpose()?;
1749            Ok(flatpak::ubuntu_update_flatpak(&username, app_id.as_deref()))
1750        }
1751        "UbuntuListFlatpaks" => {
1752            let username = validated_username(resolve_username(params)?, "username")?;
1753            Ok(flatpak::ubuntu_list_flatpaks(&username))
1754        }
1755
1756        // ── fail2ban ──────────────────────────────────────────────────────
1757        "Fail2banStatus" => {
1758            let jail = params
1759                .get("jail")
1760                .and_then(|v| v.as_str())
1761                .filter(|s| !s.is_empty())
1762                .map(|s| validated_safe_arg(s, "jail"))
1763                .transpose()?;
1764            fail2ban::fail2ban_status(jail.as_deref()).map_err(|e| match e {
1765                fail2ban::Fail2banError::InvalidIpAddress(_) => ExecutorError::InvalidParam("jail"),
1766                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("jail"),
1767            })
1768        }
1769        "Fail2banBanIp" => {
1770            let jail = validated_safe_arg(require_str(params, "jail")?, "jail")?;
1771            let ip = require_str(params, "ip")?;
1772            fail2ban::fail2ban_ban_ip(&jail, ip).map_err(|e| match e {
1773                fail2ban::Fail2banError::InvalidIpAddress(v) => ExecutorError::InvalidIpAddress {
1774                    param: "ip",
1775                    value: v,
1776                },
1777                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("jail"),
1778            })
1779        }
1780        "Fail2banUnbanIp" => {
1781            let jail = validated_safe_arg(require_str(params, "jail")?, "jail")?;
1782            let ip = require_str(params, "ip")?;
1783            fail2ban::fail2ban_unban_ip(&jail, ip).map_err(|e| match e {
1784                fail2ban::Fail2banError::InvalidIpAddress(v) => ExecutorError::InvalidIpAddress {
1785                    param: "ip",
1786                    value: v,
1787                },
1788                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("jail"),
1789            })
1790        }
1791        "ConfigureFail2banJail" => {
1792            let name = validated_sudoers_name(require_str(params, "name")?, "name")?;
1793            let mut extra = Vec::new();
1794            if let Some(n) = params.get("enabled").and_then(|v| v.as_bool()) {
1795                extra.push("--enabled".to_string());
1796                extra.push(if n { "true" } else { "false" }.to_string());
1797            }
1798            if let Some(n) = params.get("maxretry").and_then(|v| v.as_u64()) {
1799                if !(1..=100).contains(&n) {
1800                    return Err(ExecutorError::InvalidParam("maxretry"));
1801                }
1802                extra.push("--maxretry".to_string());
1803                extra.push(n.to_string());
1804            }
1805            for (key, flag) in [("bantime", "--bantime"), ("findtime", "--findtime")] {
1806                if let Some(n) = params.get(key).and_then(|v| v.as_u64()) {
1807                    if n > MAX_FAIL2BAN_WINDOW_SECS {
1808                        return Err(ExecutorError::InvalidParam(key));
1809                    }
1810                    extra.push(flag.to_string());
1811                    extra.push(n.to_string());
1812                }
1813            }
1814            if extra.is_empty() {
1815                return Err(ExecutorError::MissingParam("maxretry"));
1816            }
1817            fail2ban::configure_fail2ban_jail(&name, &extra).map_err(|e| match e {
1818                fail2ban::Fail2banError::InvalidIpAddress(_) => ExecutorError::InvalidParam("name"),
1819                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("name"),
1820            })
1821        }
1822
1823        // ── auditd file-watch rules ───────────────────────────────────────
1824        "GetAuditRules" => Ok(auditd::get_audit_rules()),
1825        "AddAuditRule" => {
1826            let path = validated_audit_path(require_str(params, "path")?, "path")?;
1827            let perms = validated_audit_perms(require_str(params, "perms")?, "perms")?;
1828            let key = validated_sudoers_name(require_str(params, "key")?, "key")?;
1829            Ok(auditd::add_audit_rule(&path, &perms, &key))
1830        }
1831        "RemoveAuditRule" => {
1832            let key = validated_sudoers_name(require_str(params, "key")?, "key")?;
1833            Ok(auditd::remove_audit_rule(&key))
1834        }
1835
1836        // ── certbot / ACME ────────────────────────────────────────────────
1837        "GetCertificates" => Ok(certbot::get_certificates()),
1838        "ObtainCertificate" => {
1839            // Accept a "domains" array or a single "domain" string; ≥1 required.
1840            let mut domains = Vec::new();
1841            if let Some(arr) = params.get("domains").and_then(|v| v.as_array()) {
1842                for d in arr {
1843                    let s = d.as_str().ok_or(ExecutorError::InvalidParam("domains"))?;
1844                    domains.push(validated_domain(s, "domains")?);
1845                }
1846            } else if let Some(d) = params.get("domain").and_then(|v| v.as_str()) {
1847                domains.push(validated_domain(d, "domain")?);
1848            }
1849            if domains.is_empty() {
1850                return Err(ExecutorError::MissingParam("domains"));
1851            }
1852            let email = validated_email(require_str(params, "email")?, "email")?;
1853            let challenge = params
1854                .get("challenge")
1855                .and_then(|v| v.as_str())
1856                .unwrap_or("standalone");
1857            if !matches!(challenge, "standalone" | "nginx" | "apache") {
1858                return Err(ExecutorError::InvalidParam("challenge"));
1859            }
1860            Ok(certbot::obtain_certificate(&domains, &email, challenge))
1861        }
1862        "RenewCertificates" => Ok(certbot::renew_certificates()),
1863
1864        _ => Err(ExecutorError::UnknownAction(action_name.to_string())),
1865    }
1866}
1867
1868/// Execute an [`ActionSpec`] and return the output.
1869///
1870/// For `Command` mechanisms, the process is spawned and its stdout/stderr
1871/// are captured. For file mechanisms, the operation is performed directly
1872/// on the filesystem and an empty stdout is returned.
1873pub async fn execute_spec(spec: &ActionSpec) -> Result<ExecutionOutput, ExecutorError> {
1874    match &spec.mechanism {
1875        ActionMechanism::Command { program, args } => {
1876            // Spawned rather than `.output()`ed so the child can be killed on
1877            // timeout; `.output()` gives no handle to kill, so a hung process
1878            // would hold the task forever.
1879            let mut child = tokio::process::Command::new(program)
1880                .args(args)
1881                .stdin(Stdio::null())
1882                // Own process group: the deadline below must be able to stop the
1883                // whole tree, not just the pid we spawned. See issue #140.
1884                .process_group(0)
1885                .stdout(Stdio::piped())
1886                .stderr(Stdio::piped())
1887                .spawn()?;
1888
1889            // `wait_with_output` consumes the child, which would leave nothing
1890            // to kill when the deadline fires. Drain the pipes in their own
1891            // tasks instead — draining also stops a chatty process from
1892            // blocking on a full pipe buffer while we wait.
1893            let stdout_h = child.stdout.take().expect("stdout was piped");
1894            let stderr_h = child.stderr.take().expect("stderr was piped");
1895            let stdout_task = tokio::spawn(async move {
1896                let mut buf = Vec::new();
1897                BufReader::new(stdout_h)
1898                    .read_to_end(&mut buf)
1899                    .await
1900                    .map(|_| buf)
1901            });
1902            let stderr_task = tokio::spawn(async move {
1903                let mut buf = Vec::new();
1904                BufReader::new(stderr_h)
1905                    .read_to_end(&mut buf)
1906                    .await
1907                    .map(|_| buf)
1908            });
1909
1910            let status = match tokio::time::timeout(action_timeout(), child.wait()).await {
1911                Ok(Ok(status)) => status,
1912                // Same rule as the streaming path: a `wait` that fails leaves a
1913                // privileged child in an unknown state, so stop the group before
1914                // reporting the failure upward.
1915                Ok(Err(err)) => {
1916                    return Err(kill_and_reap(
1917                        &mut child,
1918                        program,
1919                        args,
1920                        StopCause::Unreadable(err),
1921                    )
1922                    .await)
1923                }
1924                Err(_) => {
1925                    return Err(kill_and_reap(&mut child, program, args, StopCause::Timeout).await)
1926                }
1927            };
1928            let join =
1929                |e| ExecutorError::Io(io::Error::other(format!("reader task panicked: {e}")));
1930            let stdout = stdout_task.await.map_err(join)??;
1931            let stderr = stderr_task.await.map_err(join)??;
1932
1933            Ok(ExecutionOutput {
1934                stdout: String::from_utf8_lossy(&stdout).into_owned(),
1935                stderr: String::from_utf8_lossy(&stderr).into_owned(),
1936                exit_code: status.code().unwrap_or(-1),
1937            })
1938        }
1939        ActionMechanism::FileScan { path } => {
1940            let mut entries = tokio::fs::read_dir(path).await?;
1941            let mut names = Vec::new();
1942            while let Some(entry) = entries.next_entry().await? {
1943                names.push(entry.file_name().to_string_lossy().into_owned());
1944            }
1945            names.sort();
1946            Ok(ExecutionOutput {
1947                stdout: names.join("\n"),
1948                stderr: String::new(),
1949                exit_code: 0,
1950            })
1951        }
1952        ActionMechanism::FileWrite { path, content } => {
1953            if let Some(parent) = std::path::Path::new(path).parent() {
1954                tokio::fs::create_dir_all(parent).await?;
1955            }
1956            tokio::fs::write(path, content).await?;
1957            Ok(ExecutionOutput {
1958                stdout: String::new(),
1959                stderr: String::new(),
1960                exit_code: 0,
1961            })
1962        }
1963        ActionMechanism::FilePatch {
1964            path,
1965            search,
1966            replace,
1967        } => {
1968            let content = tokio::fs::read_to_string(path).await?;
1969            let patched = content.replacen(search.as_str(), replace.as_str(), 1);
1970            if patched == content && !search.is_empty() {
1971                return Ok(ExecutionOutput {
1972                    stdout: String::new(),
1973                    stderr: format!("search string not found in file: {}", path),
1974                    exit_code: 1,
1975                });
1976            }
1977            tokio::fs::write(path, patched).await?;
1978            Ok(ExecutionOutput {
1979                stdout: String::new(),
1980                stderr: String::new(),
1981                exit_code: 0,
1982            })
1983        }
1984        ActionMechanism::FileDelete { path } => {
1985            tokio::fs::remove_file(path).await?;
1986            Ok(ExecutionOutput {
1987                stdout: String::new(),
1988                stderr: String::new(),
1989                exit_code: 0,
1990            })
1991        }
1992    }
1993}
1994
1995fn require_str<'a>(params: &'a Value, key: &'static str) -> Result<&'a str, ExecutorError> {
1996    match params.get(key) {
1997        None => Err(ExecutorError::MissingParam(key)),
1998        Some(v) => v.as_str().ok_or(ExecutorError::InvalidParam(key)),
1999    }
2000}
2001
2002/// Extract an optional string param and validate it. An absent key or an empty
2003/// string yields `None` (the filter is simply omitted); a present non-empty
2004/// value is passed through `validator`, propagating any validation error.
2005fn optional_validated<F>(
2006    params: &Value,
2007    key: &'static str,
2008    validator: F,
2009) -> Result<Option<String>, ExecutorError>
2010where
2011    F: FnOnce(&str, &'static str) -> Result<String, ExecutorError>,
2012{
2013    match params
2014        .get(key)
2015        .and_then(|v| v.as_str())
2016        .filter(|s| !s.is_empty())
2017    {
2018        Some(s) => Ok(Some(validator(s, key)?)),
2019        None => Ok(None),
2020    }
2021}
2022
2023/// Extract the username from params, accepting either `"username"` or `"user"`
2024/// as the key.  The `"username"` key takes precedence.
2025///
2026/// Tolerates the `"user"` alias because LLMs trained on general Linux tooling
2027/// frequently produce `"user"` — accepting both here eliminates an entire class
2028/// of Describe/Execute failures without requiring the model to be perfect.
2029///
2030/// Returns [`ExecutorError::MissingParam`] if neither key is present,
2031/// [`ExecutorError::InvalidParam`] if the value is not a string.
2032fn resolve_username(params: &Value) -> Result<&str, ExecutorError> {
2033    params
2034        .get("username")
2035        .or_else(|| params.get("user"))
2036        .ok_or(ExecutorError::MissingParam("username"))
2037        .and_then(|v| v.as_str().ok_or(ExecutorError::InvalidParam("username")))
2038}
2039
2040/// Validate a repo_id: must be non-empty and contain only ASCII letters,
2041/// digits, hyphens, and underscores. Rejects `/`, `.`, and whitespace to
2042/// prevent path traversal (e.g. `../cron.d/evil`) and shell injection.
2043fn validated_repo_id(params: &Value) -> Result<&str, ExecutorError> {
2044    let id = require_str(params, "repo_id")?;
2045    let valid = !id.is_empty()
2046        && id
2047            .chars()
2048            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
2049    if valid {
2050        Ok(id)
2051    } else {
2052        Err(ExecutorError::InvalidParam("repo_id"))
2053    }
2054}
2055
2056/// Validate that a string contains no newlines. Used for repo_url to prevent
2057/// INI-section injection into `.repo` file content.
2058fn validated_no_newline<'a>(
2059    params: &'a Value,
2060    key: &'static str,
2061) -> Result<&'a str, ExecutorError> {
2062    let val = require_str(params, key)?;
2063    if val.contains('\n') || val.contains('\r') {
2064        Err(ExecutorError::InvalidParam(key))
2065    } else {
2066        Ok(val)
2067    }
2068}
2069
2070/// Validate an SSH public key: must start with a known key-type prefix,
2071/// contain only printable ASCII, no newlines, no single quotes (to prevent
2072/// shell injection in `sh -c` scripts), and be at most 8192 characters.
2073fn validated_public_key(s: &str) -> Result<String, ExecutorError> {
2074    const MAX_LEN: usize = 8192;
2075    const ALLOWED_PREFIXES: &[&str] = &[
2076        "ssh-rsa",
2077        "ssh-ed25519",
2078        "ssh-ed25519-sk",
2079        "ecdsa-sha2-nistp256",
2080        "ecdsa-sha2-nistp384",
2081        "ecdsa-sha2-nistp521",
2082        "sk-ssh-ed25519",
2083        "sk-ecdsa-sha2-nistp256",
2084    ];
2085
2086    if s.is_empty() || s.len() > MAX_LEN {
2087        return Err(ExecutorError::InvalidParam("public_key"));
2088    }
2089    if !ALLOWED_PREFIXES.iter().any(|p| s.starts_with(p)) {
2090        return Err(ExecutorError::InvalidParam("public_key"));
2091    }
2092    // No newlines, no shell metacharacters, only printable ASCII.
2093    //
2094    // Blocked characters and why:
2095    //   '\''  — breaks single-quoted shell strings in add_authorized_key
2096    //   '|'   — shell pipe (the ssh key ops no longer build a sed address,
2097    //           but '|' never appears in a valid key, so keep rejecting it)
2098    //   ';'   — shell command separator
2099    //   '`'   — shell command substitution
2100    //   '$'   — shell variable expansion
2101    //   '\\'  — shell escape; could be used to smuggle other metacharacters
2102    //   '&'   — shell background / AND operator
2103    //
2104    // None of these characters appear in valid SSH public key data (type prefix,
2105    // base64 body, or ASCII comment) so this list is safe to block unconditionally.
2106    if s.chars().any(|c| {
2107        matches!(c, '\n' | '\r' | '\'' | '|' | ';' | '`' | '$' | '\\' | '&')
2108            || !c.is_ascii()
2109            || c.is_ascii_control()
2110    }) {
2111        return Err(ExecutorError::InvalidParam("public_key"));
2112    }
2113    Ok(s.to_string())
2114}
2115
2116fn require_bool(params: &Value, key: &'static str) -> Result<bool, ExecutorError> {
2117    match params.get(key) {
2118        None => Err(ExecutorError::MissingParam(key)),
2119        Some(v) => v.as_bool().ok_or(ExecutorError::InvalidParam(key)),
2120    }
2121}
2122
2123fn require_u32(params: &Value, key: &'static str) -> Result<u32, ExecutorError> {
2124    match params.get(key) {
2125        None => Err(ExecutorError::MissingParam(key)),
2126        Some(v) => {
2127            let n = v.as_u64().ok_or(ExecutorError::InvalidParam(key))?;
2128            u32::try_from(n).map_err(|_| ExecutorError::InvalidParam(key))
2129        }
2130    }
2131}
2132
2133/// Like [`require_u32`] but additionally rejects zero.
2134///
2135/// Used for rule numbers and similar 1-based indices where 0 is never valid.
2136fn require_positive_u32(params: &Value, key: &'static str) -> Result<u32, ExecutorError> {
2137    let n = require_u32(params, key)?;
2138    if n == 0 {
2139        return Err(ExecutorError::InvalidParam(key));
2140    }
2141    Ok(n)
2142}
2143
2144/// Returns a vec of owned strings from a JSON array, or an empty vec if the
2145/// key is absent or null. Returns [`ExecutorError::InvalidParam`] if the key
2146/// is present but not an array of strings.
2147fn str_array_or_empty(params: &Value, key: &'static str) -> Result<Vec<String>, ExecutorError> {
2148    match params.get(key) {
2149        None | Some(Value::Null) => Ok(vec![]),
2150        Some(Value::Array(arr)) => arr
2151            .iter()
2152            .map(|v| {
2153                v.as_str()
2154                    .map(String::from)
2155                    .ok_or(ExecutorError::InvalidParam(key))
2156            })
2157            .collect(),
2158        _ => Err(ExecutorError::InvalidParam(key)),
2159    }
2160}
2161
2162/// Reject kernel command-line arguments that could bypass security mechanisms
2163/// or drop to an unauthenticated root shell on next boot. Applies only to
2164/// arguments being *added* (`SetKernelArguments`'s `add`, `GrubSetKargs`'s
2165/// `append`) — removing an existing argument is always safe.
2166///
2167/// `param` names the request field being validated so the error points at the
2168/// caller's actual parameter (`"add"` for `SetKernelArguments`, `"append"` for
2169/// `GrubSetKargs`).
2170///
2171/// This is a *denylist* layered on top of the caller's charset validation —
2172/// both callers run their charset check first. In particular `GrubSetKargs`
2173/// runs [`validated_safe_arg`] (which already rejects `=` and `,`), so on that
2174/// path the load-bearing checks here are the bare runlevel shortcuts
2175/// (`single`/`s`/`1`).
2176///
2177/// Blocked (case-insensitive):
2178///
2179/// - `init=`           — replaces init, can give a root shell
2180/// - `selinux=0`       — disables SELinux
2181/// - `enforcing=0`     — sets SELinux to permissive
2182/// - `security=`       — overrides LSM module selection
2183/// - `apparmor=0`      — disables the AppArmor LSM (Ubuntu's default MAC)
2184/// - `systemd.unit=emergency` / `systemd.unit=rescue` / `systemd.unit=single`
2185///   — unprotected root shell
2186/// - `single` / `1` / `s` — single-user mode (root without password)
2187/// - `module_blacklist=` — can disable security-critical kernel modules
2188/// - `mitigations=off` — disables CPU speculative-execution vulnerability
2189///   mitigations (Spectre/Meltdown/MDS/etc.)
2190/// - `lockdown=`       — weakens or disables the kernel lockdown LSM
2191/// - `pti=off`         — disables Page Table Isolation (Meltdown mitigation)
2192/// - `nosmap` / `nosmep` — disable SMAP/SMEP, CPU features that block a large
2193///   class of kernel-exploitation techniques
2194/// - `systemd.debug_shell` — the same root shell as `systemd.unit=debug-shell`,
2195///   asked for by a different name
2196fn validated_safe_kernel_arg(arg: &str, param: &'static str) -> Result<(), ExecutorError> {
2197    const BLOCKED_PREFIXES: &[&str] = &[
2198        "init=",
2199        "selinux=0",
2200        "enforcing=0",
2201        "security=",
2202        "module_blacklist=",
2203        "apparmor=0",
2204        "mitigations=off",
2205        "lockdown=",
2206        "pti=off",
2207        // `systemd.unit=` is not the only way to ask for `debug-shell.service`.
2208        // systemd-debug-generator also honours `systemd.debug_shell`, which
2209        // pulls the unit into the boot transaction and spawns a root shell on
2210        // tty9 before anyone logs in — the identical end state the
2211        // `BLOCKED_UNIT_PREFIXES` screen below exists to prevent. Underscore is
2212        // the real spelling per systemd-debug-generator(8); `rd.` is the
2213        // initrd-honoured variant, and the hyphen forms are listed so a
2214        // near-miss cannot creep back.
2215        "systemd.debug_shell",
2216        "systemd.debug-shell",
2217        "rd.systemd.debug_shell",
2218        "rd.systemd.debug-shell",
2219    ];
2220    const BLOCKED_EXACT: &[&str] = &["single", "s", "1", "nosmap", "nosmep"];
2221    // Shared with `validated_activatable_unit`, deliberately: these two screens
2222    // encode the same idea from opposite directions — one refuses to START a
2223    // root-shell unit, the other refuses to BOOT into it — and keeping two lists
2224    // let them drift until `debug-shell` and `runlevel1` were blocked on one path
2225    // and reachable on the other.
2226    use crate::actions::validate::ROOT_SHELL_UNITS as BLOCKED_UNIT_PREFIXES;
2227
2228    let lower = arg.to_lowercase();
2229    // Strip optional value (e.g. "quiet=1" → "quiet") for exact matches.
2230    let base = lower.split('=').next().unwrap_or(&lower);
2231
2232    if BLOCKED_PREFIXES.iter().any(|p| lower.starts_with(p)) {
2233        return Err(ExecutorError::InvalidParam(param));
2234    }
2235    if BLOCKED_EXACT.iter().any(|e| lower == *e) {
2236        return Err(ExecutorError::InvalidParam(param));
2237    }
2238    // Block systemd.unit= pointing to emergency/rescue/single targets.
2239    if let Some(unit_val) = lower.strip_prefix("systemd.unit=") {
2240        if BLOCKED_UNIT_PREFIXES
2241            .iter()
2242            .any(|u| unit_val.starts_with(u))
2243        {
2244            return Err(ExecutorError::InvalidParam(param));
2245        }
2246    }
2247    // Guard against the base arg matching dangerous exact values even with =.
2248    if BLOCKED_EXACT.contains(&base) {
2249        return Err(ExecutorError::InvalidParam(param));
2250    }
2251    Ok(())
2252}
2253
2254/// Validate a kernel argument that is about to be **removed** from the boot line.
2255///
2256/// [`validated_safe_kernel_arg`] screens additions. Removal was left unscreened
2257/// on the premise that "removing a dangerous arg is always safe", which inverts
2258/// the risk: the dangerous move is removing a *protective* arg. Deleting
2259/// `module.sig_enforce=1` or `lockdown=confidentiality` reaches the same end
2260/// state as adding its weakening counterpart, which the add-path refuses — so
2261/// leaving `remove` open handed back every guarantee the add-path buys.
2262///
2263/// The prefixes below are the KSPP-recommended boot parameters plus the LSM
2264/// selectors; each is a protection the host loses the moment the token leaves
2265/// the boot line. `WEAKENING` is the escape hatch that keeps the screen from
2266/// collapsing into "no removals at all": an argument that is itself a downgrade
2267/// must stay removable, or SysKnife could never harden a host that already boots
2268/// with `mitigations=off`.
2269fn validated_safe_kernel_arg_removal(arg: &str, param: &'static str) -> Result<(), ExecutorError> {
2270    /// Removing one of these hardens the host, so removal stays allowed even
2271    /// though the token matches a protective prefix below.
2272    const WEAKENING: &[&str] = &[
2273        "selinux=0",
2274        "enforcing=0",
2275        "apparmor=0",
2276        "mitigations=off",
2277        "pti=off",
2278        "lockdown=none",
2279        "debugfs=on",
2280        "iommu=off",
2281        "intel_iommu=off",
2282        "module.sig_enforce=0",
2283        "init_on_alloc=0",
2284        "init_on_free=0",
2285        "randomize_kstack_offset=off",
2286        "page_alloc.shuffle=0",
2287    ];
2288    const PROTECTIVE_PREFIXES: &[&str] = &[
2289        "lockdown=",
2290        "module.sig_enforce=",
2291        "security=",
2292        "selinux=",
2293        "enforcing=",
2294        "apparmor=",
2295        "pti=",
2296        "mitigations=",
2297        "init_on_alloc=",
2298        "init_on_free=",
2299        "page_alloc.shuffle=",
2300        "randomize_kstack_offset=",
2301        "slub_debug=",
2302        "page_poison=",
2303        "vsyscall=",
2304        "debugfs=",
2305        "iommu=",
2306        "intel_iommu=",
2307        "amd_iommu=",
2308    ];
2309    const PROTECTIVE_EXACT: &[&str] = &["slab_nomerge", "nosmt", "kaslr"];
2310
2311    let lower = arg.to_lowercase();
2312    if WEAKENING.contains(&lower.as_str()) {
2313        return Ok(());
2314    }
2315    // Protective wins over the add-path inversion below. `security=` is refused
2316    // by BOTH screens: adding it picks an LSM, removing it drops the one in use.
2317    if PROTECTIVE_PREFIXES.iter().any(|p| lower.starts_with(p))
2318        || PROTECTIVE_EXACT.contains(&lower.as_str())
2319    {
2320        return Err(ExecutorError::InvalidParam(param));
2321    }
2322    // Everything else — ordinary boot arguments, and the add-path's own denylist
2323    // (`init=`, a bare `single`, an emergency `systemd.unit=`, all weakenings the
2324    // host is better off without) — stays removable.
2325    Ok(())
2326}
2327
2328/// Validate a `kill` signal against a strict allowlist, returning the canonical
2329/// signal name for `kill -s <name>`.
2330///
2331/// Only stop/reload signals are permitted (`TERM`, `KILL`, `HUP`, `INT`); this
2332/// blocks exotic or numeric signals and, combined with the caller's `pid >= 2`
2333/// check, keeps `SignalProcess` from becoming an arbitrary-signal primitive.
2334/// Accepts case-insensitive input with an optional `SIG` prefix.
2335fn validated_kill_signal(s: &str) -> Result<&'static str, ExecutorError> {
2336    let normalized = s.trim().to_ascii_uppercase();
2337    match normalized.strip_prefix("SIG").unwrap_or(&normalized) {
2338        "TERM" => Ok("TERM"),
2339        "KILL" => Ok("KILL"),
2340        "HUP" => Ok("HUP"),
2341        "INT" => Ok("INT"),
2342        _ => Err(ExecutorError::InvalidParam("signal")),
2343    }
2344}
2345
2346/// Return the rollback [`ActionSpec`] for `action_name`, or `None` if no
2347/// automatic rollback is defined.
2348///
2349/// Only the rpm-ostree deployment and layering actions support rollback —
2350/// they all revert via `rpm-ostree rollback`. All other actions either have
2351/// no sensible rollback or are low-risk enough that a rollback would be
2352/// net-harmful.
2353///
2354/// `RollbackDeployment` itself is excluded to prevent infinite recursion.
2355pub fn rollback_spec_for(action_name: &str) -> Option<ActionSpec> {
2356    match action_name {
2357        "UpdateSystem"
2358        | "InstallPackages"
2359        | "RemovePackages"
2360        | "RebaseSystem"
2361        | "SetKernelArguments"
2362        | "AddLayeredPackage"
2363        | "RemoveLayeredPackage"
2364        | "ReplaceLayeredPackage"
2365        | "ResetLayeredPackageOverride"
2366        | "RemoveBasePackage" => Some(ActionSpec {
2367            action_name: "RollbackDeployment",
2368            mechanism: ActionMechanism::Command {
2369                program: "rpm-ostree",
2370                args: vec!["rollback".to_string()],
2371            },
2372            risk_level: sysknife_types::RiskLevel::High,
2373            reboot_required: true,
2374            rollback_available: false,
2375        }),
2376        _ => None,
2377    }
2378}
2379
2380#[cfg(test)]
2381mod tests {
2382    use super::*;
2383    use serde_json::json;
2384    use sysknife_types::RiskLevel;
2385    use tempfile::tempdir;
2386
2387    // ── build_action_spec ─────────────────────────────────────────────────
2388
2389    #[test]
2390    fn build_spec_no_params_for_get_system_state() {
2391        let spec = build_action_spec("GetSystemState", &json!({})).unwrap();
2392        assert_eq!(spec.action_name, "GetSystemState");
2393        assert_eq!(spec.risk_level, RiskLevel::Low);
2394    }
2395
2396    #[test]
2397    fn build_spec_get_datetime_is_low_risk() {
2398        let spec = build_action_spec("GetDateTime", &json!({})).unwrap();
2399        assert_eq!(spec.action_name, "GetDateTime");
2400        assert_eq!(spec.risk_level, RiskLevel::Low);
2401        assert!(!spec.reboot_required);
2402    }
2403
2404    #[test]
2405    fn build_spec_unknown_action_returns_error() {
2406        let err = build_action_spec("NonExistent", &json!({})).unwrap_err();
2407        assert!(
2408            matches!(&err, ExecutorError::UnknownAction(n) if n == "NonExistent"),
2409            "expected UnknownAction, got: {err}"
2410        );
2411    }
2412
2413    #[test]
2414    fn build_spec_missing_param_for_install_flatpak() {
2415        // username is the first required param; its absence is reported first.
2416        let err = build_action_spec("InstallFlatpak", &json!({})).unwrap_err();
2417        assert!(
2418            matches!(err, ExecutorError::MissingParam("username")),
2419            "expected MissingParam(username), got: {err}"
2420        );
2421    }
2422
2423    /// LLMs trained on standard Linux tooling frequently produce `"user"` instead
2424    /// of `"username"`.  `resolve_username` accepts both keys so these actions
2425    /// never fail with a spurious MissingParam.
2426    #[test]
2427    fn build_spec_flatpak_accepts_user_alias() {
2428        let spec = build_action_spec("ListInstalledFlatpaks", &json!({ "user": "alice" })).unwrap();
2429        assert_eq!(spec.action_name, "ListInstalledFlatpaks");
2430    }
2431
2432    /// `resolve_username` prefers `"username"` when both keys are present.
2433    #[test]
2434    fn build_spec_resolve_username_prefers_explicit_username() {
2435        let spec = build_action_spec(
2436            "ListInstalledFlatpaks",
2437            &json!({ "username": "alice", "user": "bob" }),
2438        )
2439        .unwrap();
2440        // Verify it didn't error — the "alice" value passes validation.
2441        assert_eq!(spec.action_name, "ListInstalledFlatpaks");
2442    }
2443
2444    /// `remote` defaults to "flathub" when absent — eliminates the most common
2445    /// model omission without changing behaviour when the param is explicit.
2446    #[test]
2447    fn build_spec_install_flatpak_defaults_remote_to_flathub() {
2448        let spec = build_action_spec(
2449            "InstallFlatpak",
2450            &json!({ "username": "alice", "app_id": "org.mozilla.firefox" }),
2451        )
2452        .unwrap();
2453        assert_eq!(
2454            spec.mechanism,
2455            ActionMechanism::Command {
2456                program: "sudo",
2457                args: vec![
2458                    "runuser".to_string(),
2459                    "-u".to_string(),
2460                    "alice".to_string(),
2461                    "--".to_string(),
2462                    "flatpak".to_string(),
2463                    "install".to_string(),
2464                    "--user".to_string(),
2465                    "-y".to_string(),
2466                    "flathub".to_string(),
2467                    "org.mozilla.firefox".to_string(),
2468                ],
2469            }
2470        );
2471    }
2472
2473    #[test]
2474    fn build_spec_install_flatpak_injects_app_and_remote() {
2475        let spec = build_action_spec(
2476            "InstallFlatpak",
2477            &json!({
2478                "username": "alice",
2479                "app_id": "org.mozilla.firefox",
2480                "remote": "flathub"
2481            }),
2482        )
2483        .unwrap();
2484        assert_eq!(spec.action_name, "InstallFlatpak");
2485        assert_eq!(
2486            spec.mechanism,
2487            ActionMechanism::Command {
2488                program: "sudo",
2489                args: vec![
2490                    "runuser".to_string(),
2491                    "-u".to_string(),
2492                    "alice".to_string(),
2493                    "--".to_string(),
2494                    "flatpak".to_string(),
2495                    "install".to_string(),
2496                    "--user".to_string(),
2497                    "-y".to_string(),
2498                    "flathub".to_string(),
2499                    "org.mozilla.firefox".to_string(),
2500                ],
2501            }
2502        );
2503    }
2504
2505    #[test]
2506    fn build_spec_pin_deployment_injects_index() {
2507        let spec = build_action_spec("PinDeployment", &json!({ "index": 1 })).unwrap();
2508        assert_eq!(
2509            spec.mechanism,
2510            ActionMechanism::Command {
2511                program: "sudo",
2512                args: vec![
2513                    "ostree".to_string(),
2514                    "admin".to_string(),
2515                    "pin".to_string(),
2516                    "1".to_string()
2517                ],
2518            }
2519        );
2520    }
2521
2522    #[test]
2523    fn build_spec_unpin_deployment_includes_unpin_flag() {
2524        let spec = build_action_spec("UnpinDeployment", &json!({ "index": 2 })).unwrap();
2525        assert_eq!(
2526            spec.mechanism,
2527            ActionMechanism::Command {
2528                program: "sudo",
2529                args: vec![
2530                    "ostree".to_string(),
2531                    "admin".to_string(),
2532                    "pin".to_string(),
2533                    "--unpin".to_string(),
2534                    "2".to_string(),
2535                ],
2536            }
2537        );
2538    }
2539
2540    #[test]
2541    fn require_u32_rejects_overflow() {
2542        let err = build_action_spec("PinDeployment", &json!({ "index": u64::MAX })).unwrap_err();
2543        assert!(
2544            matches!(err, ExecutorError::InvalidParam("index")),
2545            "expected InvalidParam(index), got: {err}"
2546        );
2547    }
2548
2549    #[test]
2550    fn build_spec_rebase_system_injects_target_ref() {
2551        let spec = build_action_spec(
2552            "RebaseSystem",
2553            &json!({ "target_ref": "fedora/41/x86_64/silverblue" }),
2554        )
2555        .unwrap();
2556        assert_eq!(
2557            spec.mechanism,
2558            ActionMechanism::Command {
2559                program: "sudo",
2560                args: vec![
2561                    "rpm-ostree".to_string(),
2562                    "rebase".to_string(),
2563                    "fedora/41/x86_64/silverblue".to_string(),
2564                ],
2565            }
2566        );
2567    }
2568
2569    #[test]
2570    fn build_spec_set_kernel_arguments_appends_and_deletes() {
2571        let spec = build_action_spec(
2572            "SetKernelArguments",
2573            &json!({ "add": ["nomodeset"], "remove": ["quiet"] }),
2574        )
2575        .unwrap();
2576        assert_eq!(
2577            spec.mechanism,
2578            ActionMechanism::Command {
2579                program: "sudo",
2580                args: vec![
2581                    "rpm-ostree".to_string(),
2582                    "kargs".to_string(),
2583                    "--append=nomodeset".to_string(),
2584                    "--delete=quiet".to_string(),
2585                ],
2586            }
2587        );
2588    }
2589
2590    #[test]
2591    fn build_spec_set_kernel_arguments_with_empty_arrays() {
2592        let spec =
2593            build_action_spec("SetKernelArguments", &json!({ "add": [], "remove": [] })).unwrap();
2594        assert_eq!(
2595            spec.mechanism,
2596            ActionMechanism::Command {
2597                program: "sudo",
2598                args: vec!["rpm-ostree".to_string(), "kargs".to_string()],
2599            }
2600        );
2601    }
2602
2603    #[test]
2604    fn build_spec_set_kernel_arguments_defaults_when_keys_absent() {
2605        let spec = build_action_spec("SetKernelArguments", &json!({})).unwrap();
2606        assert_eq!(
2607            spec.mechanism,
2608            ActionMechanism::Command {
2609                program: "sudo",
2610                args: vec!["rpm-ostree".to_string(), "kargs".to_string()],
2611            }
2612        );
2613    }
2614
2615    // ── Critical-account denylist (DeleteUser/DeleteGroup/LockUserAccount) ──
2616
2617    #[test]
2618    fn delete_user_rejects_critical_account() {
2619        let err = build_action_spec("DeleteUser", &json!({ "username": "root" })).unwrap_err();
2620        assert!(
2621            matches!(err, ExecutorError::InvalidParam("username")),
2622            "expected InvalidParam(username), got: {err}"
2623        );
2624    }
2625
2626    #[test]
2627    fn delete_group_rejects_critical_group() {
2628        let err = build_action_spec("DeleteGroup", &json!({ "group": "sudo" })).unwrap_err();
2629        assert!(
2630            matches!(err, ExecutorError::InvalidParam("group")),
2631            "expected InvalidParam(group), got: {err}"
2632        );
2633    }
2634
2635    #[test]
2636    fn lock_user_account_rejects_critical_account() {
2637        let err = build_action_spec("LockUserAccount", &json!({ "username": "root" })).unwrap_err();
2638        assert!(
2639            matches!(err, ExecutorError::InvalidParam("username")),
2640            "expected InvalidParam(username), got: {err}"
2641        );
2642    }
2643
2644    #[test]
2645    fn delete_user_lock_user_account_and_delete_group_allow_normal_names() {
2646        assert!(build_action_spec("DeleteUser", &json!({ "username": "alice" })).is_ok());
2647        assert!(build_action_spec("LockUserAccount", &json!({ "username": "alice" })).is_ok());
2648        assert!(build_action_spec("DeleteGroup", &json!({ "group": "developers" })).is_ok());
2649    }
2650
2651    // ── execute_spec ──────────────────────────────────────────────────────
2652
2653    #[test]
2654    fn build_spec_add_package_repository_rejects_path_traversal() {
2655        let err = build_action_spec(
2656            "AddPackageRepository",
2657            &json!({ "repo_id": "../cron.d/evil", "repo_url": "https://evil.example/repo" }),
2658        )
2659        .unwrap_err();
2660        assert!(
2661            matches!(err, ExecutorError::InvalidParam("repo_id")),
2662            "expected InvalidParam(repo_id), got: {err}"
2663        );
2664    }
2665
2666    #[test]
2667    fn build_spec_add_package_repository_rejects_newline_in_url() {
2668        let err = build_action_spec(
2669            "AddPackageRepository",
2670            &json!({ "repo_id": "myrepo", "repo_url": "https://ok.example/\nbaseurl=evil" }),
2671        )
2672        .unwrap_err();
2673        assert!(
2674            matches!(err, ExecutorError::InvalidParam("repo_url")),
2675            "expected InvalidParam(repo_url), got: {err}"
2676        );
2677    }
2678
2679    #[test]
2680    fn build_spec_add_package_repository_accepts_valid_repo_id() {
2681        let spec = build_action_spec(
2682            "AddPackageRepository",
2683            &json!({ "repo_id": "my-repo_123", "repo_url": "https://ok.example/repo" }),
2684        )
2685        .unwrap();
2686        assert_eq!(spec.action_name, "AddPackageRepository");
2687    }
2688
2689    #[test]
2690    fn build_spec_remove_package_repository_rejects_path_traversal() {
2691        let err = build_action_spec(
2692            "RemovePackageRepository",
2693            &json!({ "repo_id": "../../etc/passwd" }),
2694        )
2695        .unwrap_err();
2696        assert!(
2697            matches!(err, ExecutorError::InvalidParam("repo_id")),
2698            "expected InvalidParam(repo_id), got: {err}"
2699        );
2700    }
2701
2702    #[tokio::test]
2703    async fn execute_spec_command_captures_stdout() {
2704        let spec = ActionSpec {
2705            action_name: "GetSystemState",
2706            mechanism: ActionMechanism::Command {
2707                program: "echo",
2708                args: vec!["hello".to_string()],
2709            },
2710            risk_level: RiskLevel::Low,
2711            reboot_required: false,
2712            rollback_available: false,
2713        };
2714        let out = execute_spec(&spec).await.unwrap();
2715        assert_eq!(out.stdout.trim(), "hello");
2716        assert_eq!(out.exit_code, 0);
2717    }
2718
2719    /// Regression guard for the live subprocess stdout relay. This coverage
2720    /// previously lived in the dispatcher (`stream_command_sends_job_progress_
2721    /// lines_during_execution`) and was lost when the streaming code moved here;
2722    /// The `ActionNotStopped` message is what an operator reads in the job
2723    /// summary, and the dispatcher keys the rollback veto off this variant, so
2724    /// its fields and wording are load-bearing. No integration test constructs
2725    /// it (the real path needs a root child), so pin it directly.
2726    #[test]
2727    fn action_not_stopped_names_the_group_and_the_timeout() {
2728        let err = ExecutorError::ActionNotStopped {
2729            program: "rpm-ostree".to_string(),
2730            pgid: 4242,
2731            timeout_secs: 7200,
2732        };
2733        let msg = err.to_string();
2734        assert!(msg.contains("4242"), "must name the pgid to inspect: {msg}");
2735        assert!(msg.contains("7200"), "must name the timeout: {msg}");
2736        assert!(
2737            msg.contains("could not be confirmed stopped"),
2738            "must say what happened: {msg}"
2739        );
2740        assert!(
2741            msg.contains("rollback was skipped"),
2742            "must say the rollback was skipped: {msg}"
2743        );
2744    }
2745
2746    /// A same-uid group is genuinely killable, so `kill_and_reap` must return the
2747    /// plain stopped-timeout `Io`, not `ActionNotStopped`. This pins the
2748    /// discrimination the variant exists for, and that the function returns
2749    /// promptly rather than hanging on the reap.
2750    #[tokio::test]
2751    async fn kill_and_reap_confirms_a_killable_group_stopped_and_returns_bounded() {
2752        let mut child = tokio::process::Command::new("sh")
2753            .args(["-c", "sleep 3600 & wait"])
2754            .process_group(0)
2755            .stdin(Stdio::null())
2756            .stdout(Stdio::null())
2757            .stderr(Stdio::null())
2758            .spawn()
2759            .expect("spawn");
2760        SUDO_INVOCATIONS.store(0, std::sync::atomic::Ordering::SeqCst);
2761        let started = tokio::time::Instant::now();
2762        let err = kill_and_reap(&mut child, "sh", &[], StopCause::Timeout).await;
2763        let elapsed = started.elapsed();
2764
2765        assert!(
2766            matches!(&err, ExecutorError::Io(e) if e.kind() == io::ErrorKind::TimedOut),
2767            "a killable group must report a plain stopped-timeout, got: {err:?}"
2768        );
2769        assert!(
2770            elapsed < Duration::from_secs(GROUP_TERM_GRACE.as_secs() + 3),
2771            "must return promptly, took {elapsed:?}"
2772        );
2773        // A same-uid group is killed by the daemon's own signals, so the
2774        // privileged escalation must NOT fire (a mutation that always escalates
2775        // would shell out to sudo and trip this).
2776        assert_eq!(
2777            SUDO_INVOCATIONS.load(std::sync::atomic::Ordering::SeqCst),
2778            0,
2779            "a killable group must not escalate to the privileged reaper"
2780        );
2781    }
2782
2783    /// Losing the ability to READ a privileged child must stop it, exactly as a
2784    /// timeout does. `lines()` fails with `InvalidData` on non-UTF-8 stdout —
2785    /// reachable from any action whose output carries a byte sequence that is not
2786    /// valid UTF-8 (a filename in a foreign encoding is enough). Returning that
2787    /// error without reaping leaves a root process group running while the
2788    /// executor reports the action failed, so the dispatcher's rollback starts a
2789    /// second privileged transaction on top of the first.
2790    #[tokio::test]
2791    async fn a_child_that_outlives_a_stdout_read_failure_is_stopped_not_orphaned() {
2792        let dir = tempfile::tempdir().expect("tempdir");
2793        let pgid_file = dir.path().join("pgid");
2794        // `process_group(0)` makes the shell its own group leader, so `$$` IS the
2795        // pgid. It prints one good line, then a lone \377 (never valid UTF-8),
2796        // then outlives the read failure unless the executor stops it.
2797        let script = format!(
2798            "echo $$ > {}; echo started; printf '\\377\\n'; sleep 3600",
2799            pgid_file.display()
2800        );
2801        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2802        let err = execute_command_with_progress("sh", &["-c".to_string(), script], tx)
2803            .await
2804            .expect_err("non-UTF-8 stdout must fail the action");
2805        assert!(
2806            matches!(&err, ExecutorError::Io(e) if e.kind() == io::ErrorKind::InvalidData),
2807            "the read failure itself must be surfaced, got: {err:?}"
2808        );
2809
2810        let pgid: i32 = std::fs::read_to_string(&pgid_file)
2811            .expect("the shell must have recorded its pgid")
2812            .trim()
2813            .parse()
2814            .expect("pgid");
2815        assert!(
2816            probe_group(pgid).is_gone(),
2817            "process group {pgid} survived the read failure; \
2818             the privileged child was orphaned"
2819        );
2820    }
2821
2822    #[test]
2823    fn reap_command_cancels_rpm_ostree_but_group_kills_everything_else() {
2824        // rpm-ostree -> cancel (its work is in another cgroup, a signal can't reach it).
2825        assert_eq!(
2826            reap_command(
2827                99,
2828                "sudo",
2829                &["/usr/bin/rpm-ostree".to_string(), "upgrade".to_string()]
2830            ),
2831            vec!["-n", "/usr/bin/rpm-ostree", "cancel"]
2832        );
2833        // Everything else -> a root TERM to its own process group.
2834        assert_eq!(
2835            reap_command(
2836                99,
2837                "sudo",
2838                &[
2839                    "env".to_string(),
2840                    "apt-get".to_string(),
2841                    "install".to_string()
2842                ]
2843            ),
2844            root_group_kill_argv("TERM", 99)
2845        );
2846    }
2847
2848    #[test]
2849    fn root_group_kill_argv_targets_the_whole_group_non_interactively() {
2850        // sudo -n /usr/bin/kill -s KILL -- -<pgid>: non-interactive (NOPASSWD),
2851        // options terminated so the negative pgid is a group, not a flag.
2852        assert_eq!(
2853            root_group_kill_argv("KILL", 4242),
2854            vec!["-n", "/usr/bin/kill", "-s", "KILL", "--", "-4242"]
2855        );
2856        assert_eq!(
2857            root_group_kill_argv("TERM", 7)[3..].to_vec(),
2858            vec!["TERM", "--", "-7"]
2859        );
2860    }
2861
2862    #[test]
2863    fn is_rpm_ostree_action_detects_the_transaction_client_behind_sudo() {
2864        let sudo = |a: &[&str]| {
2865            is_rpm_ostree_action("sudo", &a.iter().map(|s| s.to_string()).collect::<Vec<_>>())
2866        };
2867        // rpm-ostree runs behind sudo, absolute or bare, and directly.
2868        assert!(sudo(&["/usr/bin/rpm-ostree", "upgrade"]));
2869        assert!(sudo(&[
2870            "rpm-ostree",
2871            "rebase",
2872            "fedora:fedora/40/x86_64/silverblue"
2873        ]));
2874        assert!(is_rpm_ostree_action("rpm-ostree", &["status".to_string()]));
2875        // Package managers whose work IS in the process group must NOT be
2876        // treated as rpm-ostree (they get the group kill, not `cancel`).
2877        assert!(!sudo(&[
2878            "env",
2879            "DEBIAN_FRONTEND=noninteractive",
2880            "apt-get",
2881            "install",
2882            "vim"
2883        ]));
2884        assert!(!sudo(&["/usr/bin/kill", "-s", "KILL", "--", "-1"]));
2885        assert!(!is_rpm_ostree_action("sudo", &[]));
2886        // Absolute path as the top-level program (no sudo wrapper).
2887        assert!(is_rpm_ostree_action(
2888            "/usr/bin/rpm-ostree",
2889            &["deploy".to_string()]
2890        ));
2891        // A path segment must match, not a substring (guards a future refactor
2892        // to `.contains()`).
2893        assert!(!is_rpm_ostree_action(
2894            "sudo",
2895            &["explain-rpm-ostree-usage".to_string()]
2896        ));
2897    }
2898
2899    /// restored at its owning layer. Proves `RealActionExecutor` forwards each
2900    /// stdout line over the mpsc channel as it arrives and reports the exit code.
2901    #[tokio::test]
2902    async fn real_executor_streams_each_stdout_line() {
2903        let spec = ActionSpec {
2904            action_name: "GetSystemState",
2905            mechanism: ActionMechanism::Command {
2906                program: "printf",
2907                args: vec!["line-one\\nline-two\\nline-three\\n".to_string()],
2908            },
2909            risk_level: RiskLevel::Low,
2910            reboot_required: false,
2911            rollback_available: false,
2912        };
2913        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2914        let out = RealActionExecutor
2915            .execute_with_progress(&spec, tx)
2916            .await
2917            .unwrap();
2918
2919        let mut lines = Vec::new();
2920        while let Ok(line) = rx.try_recv() {
2921            lines.push(line);
2922        }
2923        assert_eq!(lines, vec!["line-one", "line-two", "line-three"]);
2924        assert_eq!(out.exit_code, 0);
2925        assert!(out.stdout.contains("line-two"));
2926    }
2927
2928    #[tokio::test]
2929    async fn execute_spec_file_write_creates_file() {
2930        let dir = tempdir().unwrap();
2931        let path = dir.path().join("test.conf").to_string_lossy().into_owned();
2932        let spec = ActionSpec {
2933            action_name: "AddPackageRepository",
2934            mechanism: ActionMechanism::FileWrite {
2935                path: path.clone(),
2936                content: "[repo]\nbaseurl=https://example.test\n".to_string(),
2937            },
2938            risk_level: RiskLevel::Medium,
2939            reboot_required: false,
2940            rollback_available: true,
2941        };
2942        let out = execute_spec(&spec).await.unwrap();
2943        assert_eq!(out.exit_code, 0);
2944        assert_eq!(
2945            std::fs::read_to_string(&path).unwrap(),
2946            "[repo]\nbaseurl=https://example.test\n"
2947        );
2948    }
2949
2950    #[tokio::test]
2951    async fn execute_spec_file_patch_replaces_first_occurrence() {
2952        let dir = tempdir().unwrap();
2953        let path = dir.path().join("repo.conf").to_string_lossy().into_owned();
2954        std::fs::write(&path, "[myrepo]\nenabled=0\n").unwrap();
2955        let spec = ActionSpec {
2956            action_name: "EnablePackageRepository",
2957            mechanism: ActionMechanism::FilePatch {
2958                path: path.clone(),
2959                search: "enabled=0".to_string(),
2960                replace: "enabled=1".to_string(),
2961            },
2962            risk_level: RiskLevel::Medium,
2963            reboot_required: false,
2964            rollback_available: true,
2965        };
2966        execute_spec(&spec).await.unwrap();
2967        assert_eq!(
2968            std::fs::read_to_string(&path).unwrap(),
2969            "[myrepo]\nenabled=1\n"
2970        );
2971    }
2972
2973    #[tokio::test]
2974    async fn execute_spec_file_patch_returns_error_when_search_not_found() {
2975        let dir = tempdir().unwrap();
2976        let path = dir.path().join("repo.conf").to_string_lossy().into_owned();
2977        std::fs::write(&path, "[myrepo]\nenabled=1\n").unwrap();
2978        let spec = ActionSpec {
2979            action_name: "EnablePackageRepository",
2980            mechanism: ActionMechanism::FilePatch {
2981                path: path.clone(),
2982                search: "enabled=0".to_string(),
2983                replace: "enabled=1".to_string(),
2984            },
2985            risk_level: RiskLevel::Medium,
2986            reboot_required: false,
2987            rollback_available: true,
2988        };
2989        let out = execute_spec(&spec).await.unwrap();
2990        assert_eq!(out.exit_code, 1, "should fail when search string is absent");
2991        assert!(
2992            out.stderr.contains("search string not found in file"),
2993            "stderr should explain the failure: {}",
2994            out.stderr
2995        );
2996        // File should remain unchanged.
2997        assert_eq!(
2998            std::fs::read_to_string(&path).unwrap(),
2999            "[myrepo]\nenabled=1\n"
3000        );
3001    }
3002
3003    #[tokio::test]
3004    async fn execute_spec_file_patch_allows_empty_search_string() {
3005        // An empty search string triggers replacen's prepend behavior and should
3006        // not be rejected — the caller explicitly asked for a no-op search.
3007        let dir = tempdir().unwrap();
3008        let path = dir.path().join("file.txt").to_string_lossy().into_owned();
3009        std::fs::write(&path, "hello").unwrap();
3010        let spec = ActionSpec {
3011            action_name: "Test",
3012            mechanism: ActionMechanism::FilePatch {
3013                path: path.clone(),
3014                search: String::new(),
3015                replace: "prefix-".to_string(),
3016            },
3017            risk_level: RiskLevel::Low,
3018            reboot_required: false,
3019            rollback_available: false,
3020        };
3021        let out = execute_spec(&spec).await.unwrap();
3022        assert_eq!(out.exit_code, 0);
3023        assert_eq!(std::fs::read_to_string(&path).unwrap(), "prefix-hello");
3024    }
3025
3026    #[tokio::test]
3027    async fn execute_spec_file_delete_removes_file() {
3028        let dir = tempdir().unwrap();
3029        let path = dir.path().join("repo.conf").to_string_lossy().into_owned();
3030        std::fs::write(&path, "[myrepo]\n").unwrap();
3031        let spec = ActionSpec {
3032            action_name: "RemovePackageRepository",
3033            mechanism: ActionMechanism::FileDelete { path: path.clone() },
3034            risk_level: RiskLevel::Medium,
3035            reboot_required: false,
3036            rollback_available: true,
3037        };
3038        execute_spec(&spec).await.unwrap();
3039        assert!(!std::path::Path::new(&path).exists());
3040    }
3041
3042    #[tokio::test]
3043    async fn execute_spec_file_scan_lists_directory_entries() {
3044        let dir = tempdir().unwrap();
3045        std::fs::write(dir.path().join("a.repo"), "[a]\n").unwrap();
3046        std::fs::write(dir.path().join("b.repo"), "[b]\n").unwrap();
3047        let spec = ActionSpec {
3048            action_name: "ListPackageRepositories",
3049            mechanism: ActionMechanism::FileScan {
3050                path: dir.path().to_string_lossy().into_owned(),
3051            },
3052            risk_level: RiskLevel::Low,
3053            reboot_required: false,
3054            rollback_available: false,
3055        };
3056        let out = execute_spec(&spec).await.unwrap();
3057        assert!(
3058            out.stdout.contains("a.repo"),
3059            "expected a.repo in: {}",
3060            out.stdout
3061        );
3062        assert!(
3063            out.stdout.contains("b.repo"),
3064            "expected b.repo in: {}",
3065            out.stdout
3066        );
3067        assert_eq!(out.exit_code, 0);
3068    }
3069
3070    // ── rollback_spec_for ─────────────────────────────────────────────────────
3071
3072    #[test]
3073    fn rollback_spec_for_update_system_is_rpm_ostree_rollback() {
3074        let spec = rollback_spec_for("UpdateSystem").unwrap();
3075        assert_eq!(spec.action_name, "RollbackDeployment");
3076        assert!(
3077            matches!(
3078                &spec.mechanism,
3079                ActionMechanism::Command { program: "rpm-ostree", args }
3080                if args == &["rollback".to_string()]
3081            ),
3082            "expected rpm-ostree rollback, got: {:?}",
3083            spec.mechanism
3084        );
3085        assert!(!spec.rollback_available, "rollback spec must not recurse");
3086    }
3087
3088    #[test]
3089    fn rollback_spec_for_install_packages_is_rpm_ostree_rollback() {
3090        assert!(rollback_spec_for("InstallPackages").is_some());
3091    }
3092
3093    #[test]
3094    fn rollback_spec_for_remove_packages_is_rpm_ostree_rollback() {
3095        assert!(rollback_spec_for("RemovePackages").is_some());
3096    }
3097
3098    #[test]
3099    fn rollback_spec_for_rebase_system_is_rpm_ostree_rollback() {
3100        assert!(rollback_spec_for("RebaseSystem").is_some());
3101    }
3102
3103    #[test]
3104    fn rollback_spec_for_set_kernel_arguments_is_rpm_ostree_rollback() {
3105        assert!(rollback_spec_for("SetKernelArguments").is_some());
3106    }
3107
3108    #[test]
3109    fn rollback_spec_for_read_only_action_returns_none() {
3110        assert!(rollback_spec_for("GetSystemState").is_none());
3111        assert!(rollback_spec_for("ListUsers").is_none());
3112        assert!(rollback_spec_for("GetFirewallState").is_none());
3113    }
3114
3115    #[test]
3116    fn rollback_spec_for_non_rollbackable_actions_return_none() {
3117        assert!(rollback_spec_for("AddUserToGroup").is_none());
3118        assert!(rollback_spec_for("DeleteUser").is_none());
3119        assert!(rollback_spec_for("CleanupDeployments").is_none());
3120        // No infinite recursion — RollbackDeployment has no rollback of its own
3121        assert!(rollback_spec_for("RollbackDeployment").is_none());
3122    }
3123
3124    // ── validated_public_key ──────────────────────────────────────────────
3125
3126    #[test]
3127    fn public_key_accepts_valid_ed25519() {
3128        let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host";
3129        assert!(validated_public_key(key).is_ok());
3130    }
3131
3132    #[test]
3133    fn public_key_accepts_valid_rsa() {
3134        let key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCtest user@host";
3135        assert!(validated_public_key(key).is_ok());
3136    }
3137
3138    #[test]
3139    fn public_key_rejects_empty() {
3140        assert!(matches!(
3141            validated_public_key(""),
3142            Err(ExecutorError::InvalidParam("public_key"))
3143        ));
3144    }
3145
3146    #[test]
3147    fn public_key_rejects_unknown_prefix() {
3148        assert!(matches!(
3149            validated_public_key("sk-rsa AAAA... user@host"),
3150            Err(ExecutorError::InvalidParam("public_key"))
3151        ));
3152        assert!(matches!(
3153            validated_public_key("AAAAB3Nz... user@host"),
3154            Err(ExecutorError::InvalidParam("public_key"))
3155        ));
3156    }
3157
3158    #[test]
3159    fn public_key_rejects_single_quote() {
3160        let key = "ssh-ed25519 AAAA' $(rm -rf /) user@host";
3161        assert!(matches!(
3162            validated_public_key(key),
3163            Err(ExecutorError::InvalidParam("public_key"))
3164        ));
3165    }
3166
3167    /// The install/remove package actions must refuse a filesystem path, because
3168    /// `apt-get install /tmp/x.deb` / `rpm-ostree install /tmp/x.rpm` install a
3169    /// local file and run its scripts as root. `validate.rs` proves the validator
3170    /// refuses paths; only this proves each action arm actually calls it. Table
3171    /// driven so an arm added later that forgets the validator fails here, which
3172    /// is exactly the regression that shipped `InstallPackages`/`RemovePackages`
3173    /// on the generic safe-arg by mistake.
3174    #[test]
3175    fn package_actions_reject_a_local_file_target() {
3176        let reject: &[(&str, serde_json::Value)] = &[
3177            ("AptInstall", json!({"package": "/tmp/evil.deb"})),
3178            ("AptRemove", json!({"package": "/tmp/evil.deb"})),
3179            ("AptPurge", json!({"package": "./evil.deb"})),
3180            ("AptHold", json!({"package": "/tmp/evil.deb"})),
3181            ("AptUnhold", json!({"package": "/tmp/evil.deb"})),
3182            ("AddLayeredPackage", json!({"package": "/tmp/evil.rpm"})),
3183            ("RemoveLayeredPackage", json!({"package": "/tmp/evil.rpm"})),
3184            ("RemoveBasePackage", json!({"package": "/tmp/evil.rpm"})),
3185            (
3186                "ReplaceLayeredPackage",
3187                json!({"old": "/tmp/evil.rpm", "new": "nginx"}),
3188            ),
3189            (
3190                "ReplaceLayeredPackage",
3191                json!({"old": "nginx", "new": "/tmp/evil.rpm"}),
3192            ),
3193            ("InstallPackages", json!({"packages": ["/tmp/evil.rpm"]})),
3194            ("RemovePackages", json!({"packages": ["/tmp/evil.rpm"]})),
3195        ];
3196        for (action, params) in reject {
3197            assert!(
3198                matches!(
3199                    build_action_spec(action, params),
3200                    Err(ExecutorError::InvalidParam(_))
3201                ),
3202                "{action} must refuse a local-file package target: {params}"
3203            );
3204        }
3205        // Positive twin: real package specs must still build, or the test above
3206        // would pass for a validator that rejects everything.
3207        let accept: &[(&str, serde_json::Value)] = &[
3208            ("AptInstall", json!({"package": "nginx"})),
3209            ("AddLayeredPackage", json!({"package": "nginx=1.24.0-1"})),
3210            (
3211                "InstallPackages",
3212                json!({"packages": ["nginx", "python3-pip"]}),
3213            ),
3214        ];
3215        for (action, params) in accept {
3216            assert!(
3217                build_action_spec(action, params).is_ok(),
3218                "{action} must accept a real package spec: {params}"
3219            );
3220        }
3221    }
3222
3223    /// The activation verbs must refuse a root-shell unit through the reachable
3224    /// action, and `SetServiceEnabled` must gate only on `enabled: true`. Mutation
3225    /// testing showed reverting these call sites to the loose validator passed the
3226    /// whole suite, so the denylist was pinned only at the validator, not here.
3227    #[test]
3228    fn activating_actions_refuse_a_root_shell_unit() {
3229        for action in ["StartService", "RestartService", "UnmaskService"] {
3230            for unit in [
3231                "debug-shell.service",
3232                "emergency.target",
3233                "rescue.service",
3234                "runlevel1.target",
3235            ] {
3236                assert!(
3237                    matches!(
3238                        build_action_spec(action, &json!({"unit": unit})),
3239                        Err(ExecutorError::InvalidParam("unit"))
3240                    ),
3241                    "{action} must not activate {unit}"
3242                );
3243            }
3244            assert!(
3245                build_action_spec(action, &json!({"unit": "nginx.service"})).is_ok(),
3246                "{action} must still activate an ordinary unit"
3247            );
3248        }
3249        assert!(
3250            build_action_spec(
3251                "SetServiceEnabled",
3252                &json!({"unit": "debug-shell.service", "enabled": true})
3253            )
3254            .is_err(),
3255            "enabling a root-shell unit brings it up at boot and must be refused"
3256        );
3257        assert!(
3258            build_action_spec(
3259                "SetServiceEnabled",
3260                &json!({"unit": "debug-shell.service", "enabled": false})
3261            )
3262            .is_ok(),
3263            "disabling a root-shell unit is a mitigation and must stay reachable"
3264        );
3265        // The safe verbs must not have been tightened into the denylist, or an
3266        // operator loses the ability to stop or mask a running root shell.
3267        for action in ["StopService", "MaskService"] {
3268            assert!(
3269                build_action_spec(action, &json!({"unit": "debug-shell.service"})).is_ok(),
3270                "{action} on debug-shell is a mitigation and must stay allowed"
3271            );
3272        }
3273    }
3274
3275    #[test]
3276    fn authorized_keys_actions_reject_a_traversal_username() {
3277        // `actions/ssh.rs` builds `/home/{username}/.ssh/authorized_keys` by
3278        // interpolation, so the only thing keeping the path inside the user's
3279        // home is `validated_username` being called in these three match arms.
3280        // `validate.rs` tests the validator in isolation, and `ssh_key_ops.rs`
3281        // calls the action functions directly — neither proves the guard is
3282        // actually wired to the reachable actions.
3283        for action in [
3284            "GetAuthorizedKeys",
3285            "AddAuthorizedKey",
3286            "RemoveAuthorizedKey",
3287        ] {
3288            for bad in ["../../etc", "..", "root/../../etc"] {
3289                let err = build_action_spec(
3290                    action,
3291                    &json!({
3292                        "username": bad,
3293                        "public_key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample u@h",
3294                    }),
3295                )
3296                .unwrap_err();
3297                assert!(
3298                    matches!(err, ExecutorError::InvalidParam("username")),
3299                    "{action} must reject username {bad:?}, got {err:?}"
3300                );
3301            }
3302        }
3303    }
3304
3305    #[test]
3306    fn ip_taking_actions_reject_a_malformed_address() {
3307        // `ExecutorError::InvalidIpAddress` was constructed by three actions
3308        // and reached by no test.
3309        let cases: [(&str, serde_json::Value); 3] = [
3310            (
3311                "ResolvectlSetDns",
3312                json!({ "interface": "eth0", "servers": ["not-an-ip"] }),
3313            ),
3314            (
3315                "Fail2banBanIp",
3316                json!({ "jail": "sshd", "ip": "999.1.1.1" }),
3317            ),
3318            (
3319                "Fail2banUnbanIp",
3320                json!({ "jail": "sshd", "ip": "1.2.3.4.5" }),
3321            ),
3322        ];
3323        for (action, params) in cases {
3324            let err = build_action_spec(action, &params).unwrap_err();
3325            assert!(
3326                matches!(err, ExecutorError::InvalidIpAddress { .. }),
3327                "{action} must reject a malformed IP, got {err:?}"
3328            );
3329        }
3330    }
3331
3332    #[test]
3333    fn public_key_rejects_pipe_metacharacter() {
3334        // '|' is a shell pipe and never appears in a valid key. (It was also
3335        // the sed address delimiter before the key ops were made regex-free;
3336        // the rejection stands on its own merits either way.)
3337        let key = "ssh-ed25519 AAAA|; rm -rf /etc user@host";
3338        assert!(matches!(
3339            validated_public_key(key),
3340            Err(ExecutorError::InvalidParam("public_key"))
3341        ));
3342    }
3343
3344    #[test]
3345    fn public_key_accepts_regex_metacharacters_so_consumers_must_not_use_regex() {
3346        // Deliberate and load-bearing: `.` is legal inside a key comment
3347        // (`alice@example.com`), so the validator cannot blocklist regex
3348        // metacharacters without rejecting valid keys. Any consumer that
3349        // interprets a key as a pattern is therefore the defect — see
3350        // `actions::ssh::REMOVE_KEY_SCRIPT`, which uses `grep -Fxv` for
3351        // exactly this reason.
3352        let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample alice@example.com";
3353        assert!(validated_public_key(key).is_ok());
3354        // The wildcard-shaped payload passes validation too. It is safe only
3355        // because no consumer treats it as a pattern.
3356        assert!(validated_public_key("ssh-ed25519 .*").is_ok());
3357    }
3358
3359    #[test]
3360    fn public_key_rejects_shell_metacharacters() {
3361        for (metachar, desc) in [
3362            (';', "semicolon"),
3363            ('`', "backtick"),
3364            ('$', "dollar"),
3365            ('\\', "backslash"),
3366            ('&', "ampersand"),
3367        ] {
3368            let key = format!("ssh-ed25519 AAAA{metachar}injected user@host");
3369            assert!(
3370                matches!(
3371                    validated_public_key(&key),
3372                    Err(ExecutorError::InvalidParam("public_key"))
3373                ),
3374                "{desc} should be rejected"
3375            );
3376        }
3377    }
3378
3379    #[test]
3380    fn public_key_rejects_newline() {
3381        let key = "ssh-ed25519 AAAA\nmalicious: line user@host";
3382        assert!(matches!(
3383            validated_public_key(key),
3384            Err(ExecutorError::InvalidParam("public_key"))
3385        ));
3386        let key_cr = "ssh-ed25519 AAAA\rmalicious: line user@host";
3387        assert!(matches!(
3388            validated_public_key(key_cr),
3389            Err(ExecutorError::InvalidParam("public_key"))
3390        ));
3391    }
3392
3393    #[test]
3394    fn public_key_rejects_too_long() {
3395        // Build a key that exceeds MAX_LEN (8192 bytes)
3396        let long_payload = "A".repeat(8192);
3397        let key = format!("ssh-ed25519 {long_payload} user@host");
3398        assert!(matches!(
3399            validated_public_key(&key),
3400            Err(ExecutorError::InvalidParam("public_key"))
3401        ));
3402    }
3403
3404    // ── str_array_or_empty ────────────────────────────────────────────────
3405
3406    #[test]
3407    fn str_array_or_empty_rejects_non_string_element() {
3408        let params = json!({ "packages": ["vim", 42, "curl"] });
3409        assert!(matches!(
3410            str_array_or_empty(&params, "packages"),
3411            Err(ExecutorError::InvalidParam("packages"))
3412        ));
3413    }
3414
3415    #[test]
3416    fn str_array_or_empty_accepts_string_array() {
3417        let params = json!({ "packages": ["vim", "curl"] });
3418        assert_eq!(
3419            str_array_or_empty(&params, "packages").unwrap(),
3420            vec!["vim".to_string(), "curl".to_string()]
3421        );
3422    }
3423
3424    #[test]
3425    fn str_array_or_empty_returns_empty_when_key_absent() {
3426        let params = json!({});
3427        assert_eq!(
3428            str_array_or_empty(&params, "packages").unwrap(),
3429            Vec::<String>::new()
3430        );
3431    }
3432
3433    // ── validated_safe_kernel_arg ─────────────────────────────────────────
3434
3435    #[test]
3436    fn kernel_arg_allows_safe_args() {
3437        assert!(validated_safe_kernel_arg("quiet", "add").is_ok());
3438        assert!(validated_safe_kernel_arg("splash", "add").is_ok());
3439        assert!(validated_safe_kernel_arg("rd.driver.blacklist=nouveau", "add").is_ok());
3440        assert!(validated_safe_kernel_arg("console=ttyS0,115200", "add").is_ok());
3441    }
3442
3443    #[test]
3444    fn kernel_arg_blocks_init_override() {
3445        assert!(matches!(
3446            validated_safe_kernel_arg("init=/bin/sh", "add"),
3447            Err(ExecutorError::InvalidParam("add"))
3448        ));
3449        assert!(matches!(
3450            validated_safe_kernel_arg("INIT=/sbin/bash", "add"),
3451            Err(ExecutorError::InvalidParam("add"))
3452        ));
3453    }
3454
3455    #[test]
3456    fn kernel_arg_blocks_selinux_disable() {
3457        assert!(matches!(
3458            validated_safe_kernel_arg("selinux=0", "add"),
3459            Err(ExecutorError::InvalidParam("add"))
3460        ));
3461        assert!(matches!(
3462            validated_safe_kernel_arg("enforcing=0", "add"),
3463            Err(ExecutorError::InvalidParam("add"))
3464        ));
3465    }
3466
3467    #[test]
3468    fn kernel_arg_blocks_security_override() {
3469        assert!(matches!(
3470            validated_safe_kernel_arg("security=none", "add"),
3471            Err(ExecutorError::InvalidParam("add"))
3472        ));
3473    }
3474
3475    #[test]
3476    fn kernel_arg_blocks_module_blacklist() {
3477        assert!(matches!(
3478            validated_safe_kernel_arg("module_blacklist=dm_crypt", "add"),
3479            Err(ExecutorError::InvalidParam("add"))
3480        ));
3481    }
3482
3483    // ── validated_safe_kernel_arg_removal ─────────────────────────────────
3484    //
3485    // "Removing an argument is always safe" was the stated premise for exempting
3486    // `remove`/`delete` from any policy check. It is false: several arguments
3487    // protect the host by being PRESENT, so deleting one lands the same end state
3488    // as adding its weakening counterpart, which the add-path already refuses.
3489
3490    #[test]
3491    fn kernel_arg_removal_blocks_stripping_a_hardening_arg() {
3492        // KSPP-recommended boot parameters plus the LSM selectors. Each is a
3493        // protection the host loses the moment the token leaves the boot line.
3494        for arg in [
3495            "lockdown=confidentiality",
3496            "module.sig_enforce=1",
3497            "selinux=1",
3498            "enforcing=1",
3499            "apparmor=1",
3500            "security=selinux",
3501            "pti=on",
3502            "mitigations=auto,nosmt",
3503            "init_on_alloc=1",
3504            "init_on_free=1",
3505            "slab_nomerge",
3506            "page_alloc.shuffle=1",
3507            "randomize_kstack_offset=on",
3508            "slub_debug=FZP",
3509            "vsyscall=none",
3510            "debugfs=off",
3511            "iommu=force",
3512            "intel_iommu=on",
3513            "amd_iommu=force_isolation",
3514        ] {
3515            assert!(
3516                matches!(
3517                    validated_safe_kernel_arg_removal(arg, "remove"),
3518                    Err(ExecutorError::InvalidParam("remove"))
3519                ),
3520                "removing {arg} is a boot-security downgrade and must be refused"
3521            );
3522        }
3523    }
3524
3525    /// The screen must not turn into "no removals at all" — an argument that is
3526    /// itself a weakening (the add-path refuses it) has to stay removable, or
3527    /// SysKnife could never undo `mitigations=off` on a host that already has it.
3528    #[test]
3529    fn kernel_arg_removal_allows_undoing_a_weakening_arg() {
3530        for arg in [
3531            "mitigations=off",
3532            "selinux=0",
3533            "enforcing=0",
3534            "apparmor=0",
3535            "pti=off",
3536            "lockdown=none",
3537            "debugfs=on",
3538            "init=/bin/sh",
3539            "single",
3540        ] {
3541            assert!(
3542                validated_safe_kernel_arg_removal(arg, "remove").is_ok(),
3543                "{arg} weakens the host, so removing it must stay allowed"
3544            );
3545        }
3546    }
3547
3548    #[test]
3549    fn kernel_arg_removal_allows_ordinary_args() {
3550        for arg in [
3551            "quiet",
3552            "splash",
3553            "nomodeset",
3554            "console=ttyS0,115200",
3555            "rd.driver.blacklist=nouveau",
3556        ] {
3557            assert!(
3558                validated_safe_kernel_arg_removal(arg, "remove").is_ok(),
3559                "{arg} carries no boot-security meaning and must stay removable"
3560            );
3561        }
3562    }
3563
3564    #[test]
3565    fn kernel_arg_blocks_systemd_unit_emergency_rescue() {
3566        assert!(matches!(
3567            validated_safe_kernel_arg("systemd.unit=emergency.target", "add"),
3568            Err(ExecutorError::InvalidParam("add"))
3569        ));
3570        assert!(matches!(
3571            validated_safe_kernel_arg("systemd.unit=rescue.target", "add"),
3572            Err(ExecutorError::InvalidParam("add"))
3573        ));
3574        assert!(matches!(
3575            validated_safe_kernel_arg("systemd.unit=single.target", "add"),
3576            Err(ExecutorError::InvalidParam("add"))
3577        ));
3578    }
3579
3580    #[test]
3581    fn kernel_arg_blocks_apparmor_disable() {
3582        assert!(matches!(
3583            validated_safe_kernel_arg("apparmor=0", "add"),
3584            Err(ExecutorError::InvalidParam("add"))
3585        ));
3586    }
3587
3588    #[test]
3589    fn kernel_arg_blocks_mitigations_off() {
3590        assert!(matches!(
3591            validated_safe_kernel_arg("mitigations=off", "add"),
3592            Err(ExecutorError::InvalidParam("add"))
3593        ));
3594    }
3595
3596    #[test]
3597    fn kernel_arg_blocks_lockdown_override() {
3598        assert!(matches!(
3599            validated_safe_kernel_arg("lockdown=none", "add"),
3600            Err(ExecutorError::InvalidParam("add"))
3601        ));
3602    }
3603
3604    #[test]
3605    fn kernel_arg_blocks_pti_off() {
3606        assert!(matches!(
3607            validated_safe_kernel_arg("pti=off", "add"),
3608            Err(ExecutorError::InvalidParam("add"))
3609        ));
3610    }
3611
3612    #[test]
3613    fn kernel_arg_blocks_smap_smep_disable() {
3614        assert!(matches!(
3615            validated_safe_kernel_arg("nosmap", "add"),
3616            Err(ExecutorError::InvalidParam("add"))
3617        ));
3618        assert!(matches!(
3619            validated_safe_kernel_arg("nosmep", "add"),
3620            Err(ExecutorError::InvalidParam("add"))
3621        ));
3622    }
3623
3624    #[test]
3625    fn kernel_arg_blocks_single_user_shortcuts() {
3626        // Runlevel shortcuts that drop to a root shell.
3627        assert!(matches!(
3628            validated_safe_kernel_arg("single", "add"),
3629            Err(ExecutorError::InvalidParam("add"))
3630        ));
3631        assert!(matches!(
3632            validated_safe_kernel_arg("s", "add"),
3633            Err(ExecutorError::InvalidParam("add"))
3634        ));
3635        assert!(matches!(
3636            validated_safe_kernel_arg("1", "add"),
3637            Err(ExecutorError::InvalidParam("add"))
3638        ));
3639    }
3640
3641    #[test]
3642    fn signal_process_guardrails() {
3643        // Reject pid 0 (whole process group) and 1 (init/systemd).
3644        for bad_pid in [0, 1] {
3645            let err = build_action_spec("SignalProcess", &json!({ "pid": bad_pid })).unwrap_err();
3646            assert!(
3647                matches!(err, ExecutorError::InvalidParam("pid")),
3648                "pid {bad_pid} must be rejected, got {err:?}"
3649            );
3650        }
3651        // Reject a signal outside the allowlist.
3652        let err = build_action_spec("SignalProcess", &json!({ "pid": 4242, "signal": "STOP" }))
3653            .unwrap_err();
3654        assert!(
3655            matches!(err, ExecutorError::InvalidParam("signal")),
3656            "got {err:?}"
3657        );
3658        // Missing pid is a MissingParam.
3659        assert!(matches!(
3660            build_action_spec("SignalProcess", &json!({})).unwrap_err(),
3661            ExecutorError::MissingParam("pid")
3662        ));
3663        // A valid pid + signal builds, and accepts a numeric string + SIG prefix.
3664        let spec = build_action_spec(
3665            "SignalProcess",
3666            &json!({ "pid": "4242", "signal": "sigkill" }),
3667        )
3668        .unwrap();
3669        assert_eq!(spec.action_name, "SignalProcess");
3670        assert_eq!(
3671            spec.mechanism,
3672            ActionMechanism::Command {
3673                program: "sudo",
3674                args: vec![
3675                    "kill".to_string(),
3676                    "-s".to_string(),
3677                    "KILL".to_string(),
3678                    "4242".to_string()
3679                ],
3680            }
3681        );
3682        // Default signal is TERM when omitted.
3683        let spec = build_action_spec("SignalProcess", &json!({ "pid": 4242 })).unwrap();
3684        if let ActionMechanism::Command { args, .. } = spec.mechanism {
3685            assert_eq!(args, vec!["kill", "-s", "TERM", "4242"]);
3686        } else {
3687            panic!("expected Command mechanism");
3688        }
3689    }
3690
3691    #[test]
3692    fn create_scheduled_job_validates_name_command_schedule() {
3693        // A newline in the command would inject extra unit directives.
3694        assert!(matches!(
3695            build_action_spec(
3696                "CreateScheduledJob",
3697                &json!({ "name": "backup", "command": "/bin/true\nExecStartPre=/evil", "schedule": "daily" })
3698            )
3699            .unwrap_err(),
3700            ExecutorError::InvalidParam("command")
3701        ));
3702        // A path-like / dotted name is rejected (must be a safe unit stem).
3703        assert!(matches!(
3704            build_action_spec(
3705                "CreateScheduledJob",
3706                &json!({ "name": "../evil", "command": "/bin/true", "schedule": "daily" })
3707            )
3708            .unwrap_err(),
3709            ExecutorError::InvalidParam("name")
3710        ));
3711        // A schedule with shell metacharacters is rejected by the charset gate.
3712        assert!(matches!(
3713            build_action_spec(
3714                "CreateScheduledJob",
3715                &json!({ "name": "backup", "command": "/bin/true", "schedule": "daily; rm -rf /" })
3716            )
3717            .unwrap_err(),
3718            ExecutorError::InvalidParam("schedule")
3719        ));
3720        // A valid job routes through the scoped helper with the right argv.
3721        let spec = build_action_spec(
3722            "CreateScheduledJob",
3723            &json!({ "name": "nightly-backup", "command": "/usr/bin/backup --full", "schedule": "*-*-* 02:00:00" }),
3724        )
3725        .unwrap();
3726        assert_eq!(
3727            spec.mechanism,
3728            ActionMechanism::Command {
3729                program: "sudo",
3730                args: vec![
3731                    "/usr/lib/sysknife/scheduled-job-edit".to_string(),
3732                    "--name".to_string(),
3733                    "nightly-backup".to_string(),
3734                    "--command".to_string(),
3735                    "/usr/bin/backup --full".to_string(),
3736                    "--schedule".to_string(),
3737                    "*-*-* 02:00:00".to_string(),
3738                ],
3739            }
3740        );
3741    }
3742
3743    #[test]
3744    fn set_sshd_option_allowlist_guardrails() {
3745        // Non-allowlisted option rejected.
3746        assert!(matches!(
3747            build_action_spec(
3748                "SetSshdOption",
3749                &json!({ "option": "Ciphers", "value": "aes256-gcm@openssh.com" })
3750            )
3751            .unwrap_err(),
3752            ExecutorError::InvalidParam("option")
3753        ));
3754        // Allowlisted option, disallowed value.
3755        assert!(matches!(
3756            build_action_spec(
3757                "SetSshdOption",
3758                &json!({ "option": "PermitRootLogin", "value": "maybe" })
3759            )
3760            .unwrap_err(),
3761            ExecutorError::InvalidParam("value")
3762        ));
3763        // Valid combo routes through the scoped helper.
3764        let spec = build_action_spec(
3765            "SetSshdOption",
3766            &json!({ "option": "PasswordAuthentication", "value": "no" }),
3767        )
3768        .unwrap();
3769        assert_eq!(
3770            spec.mechanism,
3771            ActionMechanism::Command {
3772                program: "sudo",
3773                args: vec![
3774                    "/usr/lib/sysknife/sshd-option-edit".to_string(),
3775                    "--option".to_string(),
3776                    "PasswordAuthentication".to_string(),
3777                    "--value".to_string(),
3778                    "no".to_string(),
3779                ],
3780            }
3781        );
3782    }
3783
3784    #[test]
3785    fn configure_unattended_upgrades_toggles_helper_flag() {
3786        for (enabled, flag) in [(true, "--enable"), (false, "--disable")] {
3787            let spec = build_action_spec(
3788                "ConfigureUnattendedUpgrades",
3789                &json!({ "enabled": enabled }),
3790            )
3791            .unwrap();
3792            assert_eq!(
3793                spec.mechanism,
3794                ActionMechanism::Command {
3795                    program: "sudo",
3796                    args: vec![
3797                        "/usr/lib/sysknife/unattended-upgrades-edit".to_string(),
3798                        flag.to_string(),
3799                    ],
3800                }
3801            );
3802        }
3803        assert!(matches!(
3804            build_action_spec("ConfigureUnattendedUpgrades", &json!({})).unwrap_err(),
3805            ExecutorError::MissingParam("enabled")
3806        ));
3807    }
3808
3809    #[test]
3810    fn grub_set_kargs_append_blocks_single_user_shortcut() {
3811        // Regression: GrubSetKargs previously used only the charset validator,
3812        // which accepts the bare `single`/`s`/`1` runlevel shortcuts. The
3813        // kernel-arg denylist must apply to `append` too — booting into a
3814        // single-user root shell is exactly the SetKernelArguments threat.
3815        // Every BLOCKED_EXACT entry is valueless, so it passes the charset
3816        // check and this denylist call is the only thing stopping it — the
3817        // call is load-bearing here, not redundant with `validated_safe_arg`.
3818        for dangerous in ["single", "s", "1", "nosmap", "nosmep"] {
3819            let err = build_action_spec(
3820                "GrubSetKargs",
3821                &json!({ "append": [dangerous], "delete": [] }),
3822            )
3823            .unwrap_err();
3824            assert!(
3825                matches!(err, ExecutorError::InvalidParam("append")),
3826                "GrubSetKargs must reject append=[{dangerous:?}] via the denylist, got {err:?}"
3827            );
3828        }
3829        // A benign flag still builds successfully.
3830        assert!(build_action_spec(
3831            "GrubSetKargs",
3832            &json!({ "append": ["quiet"], "delete": [] })
3833        )
3834        .is_ok());
3835    }
3836
3837    #[test]
3838    fn kernel_arg_build_spec_rejects_dangerous_arg() {
3839        // End-to-end: build_action_spec must propagate the blocklist error.
3840        // This action does NOT apply the `validated_safe_arg` charset check,
3841        // so `init=/bin/bash` reaches `validated_safe_kernel_arg` and is
3842        // caught by BLOCKED_PREFIXES — the `=`-bearing half of that denylist
3843        // is live here even though GrubSetKargs never reaches it.
3844        let err = build_action_spec(
3845            "SetKernelArguments",
3846            &json!({ "add": ["init=/bin/bash"], "remove": [] }),
3847        )
3848        .unwrap_err();
3849        assert!(
3850            matches!(err, ExecutorError::InvalidParam("add")),
3851            "expected InvalidParam(add), got {err:?}"
3852        );
3853    }
3854
3855    #[test]
3856    fn grub_set_kargs_cannot_delete_a_protective_karg() {
3857        // A review flagged `delete: ["apparmor=1"]` as a way to strip AppArmor
3858        // because the kernel-arg denylist is not applied to `delete`. It is
3859        // not reachable: `delete` goes through `validated_safe_arg`, whose
3860        // charset excludes `=`, so any `key=value` token is refused before the
3861        // denylist would matter. Pinned here so a future widening of that
3862        // charset cannot silently open the hole.
3863        for karg in [
3864            "apparmor=1",
3865            "lockdown=confidentiality",
3866            "mitigations=auto",
3867            "pti=on",
3868            "selinux=1",
3869        ] {
3870            let err = build_action_spec("GrubSetKargs", &json!({ "append": [], "delete": [karg] }))
3871                .unwrap_err();
3872            assert!(
3873                matches!(err, ExecutorError::InvalidParam("delete")),
3874                "deleting {karg:?} must be refused, got {err:?}"
3875            );
3876        }
3877    }
3878
3879    /// Every action that claims `rollback_available: true` MUST have a
3880    /// corresponding entry in `rollback_spec_for()`; every action that claims
3881    /// `false` MUST NOT. This prevents the spec and the executor from
3882    /// drifting apart.
3883    #[test]
3884    fn rollback_available_matches_rollback_spec_for_all_actions() {
3885        // Iterate the FULL catalogue (`crate::actions::all_specs`), not a
3886        // hand-picked subset of families — a manually-chained list here once
3887        // silently omitted `ppa`, `netplan`, `grub`, and `ubuntu_pro`, which is
3888        // exactly how `AddPpa`/`RemovePpa`/`NetplanSet`/`GrubSetKargs`/
3889        // `ProAttach`/`ProDetach` were able to claim `rollback_available: true`
3890        // with no matching `rollback_spec_for` entry for years without this
3891        // test catching it.
3892        for spec in crate::actions::all_specs() {
3893            let has_rollback = rollback_spec_for(spec.action_name).is_some();
3894            assert_eq!(
3895                spec.rollback_available,
3896                has_rollback,
3897                "action {:?}: rollback_available={} but rollback_spec_for returns {}",
3898                spec.action_name,
3899                spec.rollback_available,
3900                if has_rollback { "Some" } else { "None" },
3901            );
3902        }
3903    }
3904
3905    // ── Risk level reclassification (NIST 800-53 / CIS Controls v8.1) ────────
3906    // These five actions were incorrectly classified Medium; they must be High.
3907    // T1136.001 (CreateUser), T1562.004 (ConfigureFirewall), T1562.001 (MaskService),
3908    // supply-chain vector (AddPackageRepository), T1557 path (SetDnsServers).
3909
3910    #[test]
3911    fn create_user_is_high_risk() {
3912        let spec = build_action_spec("CreateUser", &json!({ "username": "alice" })).unwrap();
3913        assert_eq!(
3914            spec.risk_level,
3915            RiskLevel::High,
3916            "CreateUser must be High (T1136.001 Persistence)"
3917        );
3918    }
3919
3920    #[test]
3921    fn configure_firewall_is_high_risk() {
3922        let spec = build_action_spec(
3923            "ConfigureFirewall",
3924            &json!({ "zone": "public", "service": "ssh", "enabled": true }),
3925        )
3926        .unwrap();
3927        assert_eq!(
3928            spec.risk_level,
3929            RiskLevel::High,
3930            "ConfigureFirewall must be High (T1562.004 Defense Evasion)"
3931        );
3932    }
3933
3934    #[test]
3935    fn mask_service_is_high_risk() {
3936        let spec = build_action_spec("MaskService", &json!({ "unit": "auditd.service" })).unwrap();
3937        assert_eq!(
3938            spec.risk_level,
3939            RiskLevel::High,
3940            "MaskService must be High (T1562.001 Impair Defenses)"
3941        );
3942    }
3943
3944    #[test]
3945    fn add_package_repository_is_high_risk() {
3946        let spec = build_action_spec(
3947            "AddPackageRepository",
3948            &json!({ "repo_id": "my-repo", "repo_url": "https://ok.example/repo" }),
3949        )
3950        .unwrap();
3951        assert_eq!(
3952            spec.risk_level,
3953            RiskLevel::High,
3954            "AddPackageRepository must be High (supply-chain vector)"
3955        );
3956    }
3957
3958    #[test]
3959    fn set_dns_servers_is_high_risk() {
3960        let spec = build_action_spec(
3961            "SetDnsServers",
3962            &json!({ "interface": "eth0", "servers": ["8.8.8.8"] }),
3963        )
3964        .unwrap();
3965        assert_eq!(
3966            spec.risk_level,
3967            RiskLevel::High,
3968            "SetDnsServers must be High (DNS hijacking / T1557)"
3969        );
3970    }
3971}