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" => Ok(ufw::ufw_status()),
1612
1613        // ── distrobox ────────────────────────────────────────────────────
1614        "DistroboxList" => Ok(distrobox::distrobox_list()),
1615        "DistroboxCreate" => {
1616            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1617            let image = validated_safe_arg(require_str(params, "image")?, "image")?;
1618            Ok(distrobox::distrobox_create(&name, &image))
1619        }
1620        "DistroboxRemove" => {
1621            let name = validated_safe_arg(require_str(params, "name")?, "name")?;
1622            Ok(distrobox::distrobox_remove(&name))
1623        }
1624
1625        // ── netplan ──────────────────────────────────────────────────────
1626        "NetplanGetConfig" => Ok(netplan::netplan_get_config()),
1627        "NetplanApply" => Ok(netplan::netplan_apply()),
1628        "NetplanSet" => {
1629            let key = validated_safe_arg(require_str(params, "key")?, "key")?;
1630            let value = validated_safe_arg(require_str(params, "value")?, "value")?;
1631            Ok(netplan::netplan_set(&key, &value))
1632        }
1633        "NetplanGenerate" => Ok(netplan::netplan_generate()),
1634
1635        // ── ufw Tier 3 ────────────────────────────────────────────────────
1636        "UfwDeleteRule" => {
1637            let rule_number = require_positive_u32(params, "rule_number")?;
1638            ufw::ufw_delete_rule(rule_number)
1639                .map_err(|_| ExecutorError::InvalidParam("rule_number"))
1640        }
1641        "UfwLimit" => {
1642            let target = validated_port_or_service(require_str(params, "target")?, "target")?;
1643            Ok(ufw::ufw_limit(&target))
1644        }
1645
1646        // ── Ubuntu Pro ────────────────────────────────────────────────────
1647        "ProStatus" => Ok(ubuntu_pro::pro_status()),
1648        "ProAttach" => {
1649            // token is a credential: read it from params but do NOT log it.
1650            let token = require_str(params, "token")?;
1651            // Minimal structural validation: non-empty, no shell metacharacters.
1652            let token = validated_safe_arg(token, "token")?;
1653            Ok(ubuntu_pro::pro_attach(&token))
1654        }
1655        "ProDetach" => Ok(ubuntu_pro::pro_detach()),
1656        "EnableProService" => {
1657            let service = validated_pro_service(require_str(params, "service")?, "service")?;
1658            Ok(ubuntu_pro::enable_pro_service(&service))
1659        }
1660        "DisableProService" => {
1661            let service = validated_pro_service(require_str(params, "service")?, "service")?;
1662            Ok(ubuntu_pro::disable_pro_service(&service))
1663        }
1664
1665        // ── Livepatch ─────────────────────────────────────────────────────
1666        "LivepatchStatus" => Ok(livepatch::livepatch_status()),
1667
1668        // ── Multipass ─────────────────────────────────────────────────────
1669        "MultipassList" => Ok(multipass::multipass_list()),
1670
1671        // ── Release upgrade ───────────────────────────────────────────────
1672        "UbuntuReleaseUpgrade" => Ok(release_upgrade::ubuntu_release_upgrade()),
1673
1674        // ── resolvectl (cross-distro / systemd-resolved) ──────────────────
1675        "ResolvectlStatus" => Ok(resolvectl::resolvectl_status()),
1676        "ResolvectlSetDns" => {
1677            let interface = validated_safe_arg(require_str(params, "interface")?, "interface")?;
1678            let raw_servers: Vec<String> = params
1679                .get("servers")
1680                .and_then(|v| v.as_array())
1681                .map(|arr| {
1682                    arr.iter()
1683                        .filter_map(|v| v.as_str())
1684                        .map(String::from)
1685                        .collect()
1686                })
1687                .unwrap_or_default();
1688            if raw_servers.is_empty() {
1689                return Err(ExecutorError::MissingParam("servers"));
1690            }
1691            // Parse every server string as a typed IpAddr before passing to the
1692            // constructor. This rejects leading-dash strings (flag injection) and
1693            // malformed addresses that would silently misconfigure systemd-resolved.
1694            let mut parsed_servers: Vec<IpAddr> = Vec::with_capacity(raw_servers.len());
1695            for s in &raw_servers {
1696                let addr = IpAddr::from_str(s).map_err(|_| ExecutorError::InvalidIpAddress {
1697                    param: "servers",
1698                    value: s.clone(),
1699                })?;
1700                parsed_servers.push(addr);
1701            }
1702            Ok(resolvectl::resolvectl_set_dns(&interface, &parsed_servers))
1703        }
1704
1705        // ── apparmor ──────────────────────────────────────────────────────
1706        "AppArmorStatus" => Ok(apparmor::apparmor_status()),
1707        "AppArmorEnforce" => {
1708            let profile_path =
1709                validated_apparmor_profile(require_str(params, "profile_path")?, "profile_path")?;
1710            Ok(apparmor::apparmor_enforce(&profile_path))
1711        }
1712        "AppArmorComplain" => {
1713            let profile_path =
1714                validated_apparmor_profile(require_str(params, "profile_path")?, "profile_path")?;
1715            Ok(apparmor::apparmor_complain(&profile_path))
1716        }
1717
1718        // ── cloud-init ────────────────────────────────────────────────────
1719        "CloudInitStatus" => Ok(cloudinit::cloud_init_status()),
1720
1721        // ── Ubuntu Flatpak ─────────────────────────────────────────────────
1722        "UbuntuInstallFlatpak" => {
1723            let username = validated_username(resolve_username(params)?, "username")?;
1724            let app_id = validated_safe_arg(require_str(params, "app_id")?, "app_id")?;
1725            let remote = validated_safe_arg(require_str(params, "remote")?, "remote")?;
1726            Ok(flatpak::ubuntu_install_flatpak(&username, &app_id, &remote))
1727        }
1728        "UbuntuRemoveFlatpak" => {
1729            let username = validated_username(resolve_username(params)?, "username")?;
1730            let app_id = validated_safe_arg(require_str(params, "app_id")?, "app_id")?;
1731            Ok(flatpak::ubuntu_remove_flatpak(&username, &app_id))
1732        }
1733        "UbuntuUpdateFlatpak" => {
1734            let username = validated_username(resolve_username(params)?, "username")?;
1735            let app_id = params
1736                .get("app_id")
1737                .and_then(|v| v.as_str())
1738                .filter(|s| !s.is_empty())
1739                .map(|s| validated_safe_arg(s, "app_id"))
1740                .transpose()?;
1741            Ok(flatpak::ubuntu_update_flatpak(&username, app_id.as_deref()))
1742        }
1743        "UbuntuListFlatpaks" => {
1744            let username = validated_username(resolve_username(params)?, "username")?;
1745            Ok(flatpak::ubuntu_list_flatpaks(&username))
1746        }
1747
1748        // ── fail2ban ──────────────────────────────────────────────────────
1749        "Fail2banStatus" => {
1750            let jail = params
1751                .get("jail")
1752                .and_then(|v| v.as_str())
1753                .filter(|s| !s.is_empty())
1754                .map(|s| validated_safe_arg(s, "jail"))
1755                .transpose()?;
1756            fail2ban::fail2ban_status(jail.as_deref()).map_err(|e| match e {
1757                fail2ban::Fail2banError::InvalidIpAddress(_) => ExecutorError::InvalidParam("jail"),
1758                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("jail"),
1759            })
1760        }
1761        "Fail2banBanIp" => {
1762            let jail = validated_safe_arg(require_str(params, "jail")?, "jail")?;
1763            let ip = require_str(params, "ip")?;
1764            fail2ban::fail2ban_ban_ip(&jail, ip).map_err(|e| match e {
1765                fail2ban::Fail2banError::InvalidIpAddress(v) => ExecutorError::InvalidIpAddress {
1766                    param: "ip",
1767                    value: v,
1768                },
1769                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("jail"),
1770            })
1771        }
1772        "Fail2banUnbanIp" => {
1773            let jail = validated_safe_arg(require_str(params, "jail")?, "jail")?;
1774            let ip = require_str(params, "ip")?;
1775            fail2ban::fail2ban_unban_ip(&jail, ip).map_err(|e| match e {
1776                fail2ban::Fail2banError::InvalidIpAddress(v) => ExecutorError::InvalidIpAddress {
1777                    param: "ip",
1778                    value: v,
1779                },
1780                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("jail"),
1781            })
1782        }
1783        "ConfigureFail2banJail" => {
1784            let name = validated_sudoers_name(require_str(params, "name")?, "name")?;
1785            let mut extra = Vec::new();
1786            if let Some(n) = params.get("enabled").and_then(|v| v.as_bool()) {
1787                extra.push("--enabled".to_string());
1788                extra.push(if n { "true" } else { "false" }.to_string());
1789            }
1790            if let Some(n) = params.get("maxretry").and_then(|v| v.as_u64()) {
1791                if !(1..=100).contains(&n) {
1792                    return Err(ExecutorError::InvalidParam("maxretry"));
1793                }
1794                extra.push("--maxretry".to_string());
1795                extra.push(n.to_string());
1796            }
1797            for (key, flag) in [("bantime", "--bantime"), ("findtime", "--findtime")] {
1798                if let Some(n) = params.get(key).and_then(|v| v.as_u64()) {
1799                    if n > MAX_FAIL2BAN_WINDOW_SECS {
1800                        return Err(ExecutorError::InvalidParam(key));
1801                    }
1802                    extra.push(flag.to_string());
1803                    extra.push(n.to_string());
1804                }
1805            }
1806            if extra.is_empty() {
1807                return Err(ExecutorError::MissingParam("maxretry"));
1808            }
1809            fail2ban::configure_fail2ban_jail(&name, &extra).map_err(|e| match e {
1810                fail2ban::Fail2banError::InvalidIpAddress(_) => ExecutorError::InvalidParam("name"),
1811                fail2ban::Fail2banError::InvalidJail(_) => ExecutorError::InvalidParam("name"),
1812            })
1813        }
1814
1815        // ── auditd file-watch rules ───────────────────────────────────────
1816        "GetAuditRules" => Ok(auditd::get_audit_rules()),
1817        "AddAuditRule" => {
1818            let path = validated_audit_path(require_str(params, "path")?, "path")?;
1819            let perms = validated_audit_perms(require_str(params, "perms")?, "perms")?;
1820            let key = validated_sudoers_name(require_str(params, "key")?, "key")?;
1821            Ok(auditd::add_audit_rule(&path, &perms, &key))
1822        }
1823        "RemoveAuditRule" => {
1824            let key = validated_sudoers_name(require_str(params, "key")?, "key")?;
1825            Ok(auditd::remove_audit_rule(&key))
1826        }
1827
1828        // ── certbot / ACME ────────────────────────────────────────────────
1829        "GetCertificates" => Ok(certbot::get_certificates()),
1830        "ObtainCertificate" => {
1831            // Accept a "domains" array or a single "domain" string; ≥1 required.
1832            let mut domains = Vec::new();
1833            if let Some(arr) = params.get("domains").and_then(|v| v.as_array()) {
1834                for d in arr {
1835                    let s = d.as_str().ok_or(ExecutorError::InvalidParam("domains"))?;
1836                    domains.push(validated_domain(s, "domains")?);
1837                }
1838            } else if let Some(d) = params.get("domain").and_then(|v| v.as_str()) {
1839                domains.push(validated_domain(d, "domain")?);
1840            }
1841            if domains.is_empty() {
1842                return Err(ExecutorError::MissingParam("domains"));
1843            }
1844            let email = validated_email(require_str(params, "email")?, "email")?;
1845            let challenge = params
1846                .get("challenge")
1847                .and_then(|v| v.as_str())
1848                .unwrap_or("standalone");
1849            if !matches!(challenge, "standalone" | "nginx" | "apache") {
1850                return Err(ExecutorError::InvalidParam("challenge"));
1851            }
1852            Ok(certbot::obtain_certificate(&domains, &email, challenge))
1853        }
1854        "RenewCertificates" => Ok(certbot::renew_certificates()),
1855
1856        _ => Err(ExecutorError::UnknownAction(action_name.to_string())),
1857    }
1858}
1859
1860/// Execute an [`ActionSpec`] and return the output.
1861///
1862/// For `Command` mechanisms, the process is spawned and its stdout/stderr
1863/// are captured. For file mechanisms, the operation is performed directly
1864/// on the filesystem and an empty stdout is returned.
1865pub async fn execute_spec(spec: &ActionSpec) -> Result<ExecutionOutput, ExecutorError> {
1866    match &spec.mechanism {
1867        ActionMechanism::Command { program, args } => {
1868            // Spawned rather than `.output()`ed so the child can be killed on
1869            // timeout; `.output()` gives no handle to kill, so a hung process
1870            // would hold the task forever.
1871            let mut child = tokio::process::Command::new(program)
1872                .args(args)
1873                .stdin(Stdio::null())
1874                // Own process group: the deadline below must be able to stop the
1875                // whole tree, not just the pid we spawned. See issue #140.
1876                .process_group(0)
1877                .stdout(Stdio::piped())
1878                .stderr(Stdio::piped())
1879                .spawn()?;
1880
1881            // `wait_with_output` consumes the child, which would leave nothing
1882            // to kill when the deadline fires. Drain the pipes in their own
1883            // tasks instead — draining also stops a chatty process from
1884            // blocking on a full pipe buffer while we wait.
1885            let stdout_h = child.stdout.take().expect("stdout was piped");
1886            let stderr_h = child.stderr.take().expect("stderr was piped");
1887            let stdout_task = tokio::spawn(async move {
1888                let mut buf = Vec::new();
1889                BufReader::new(stdout_h)
1890                    .read_to_end(&mut buf)
1891                    .await
1892                    .map(|_| buf)
1893            });
1894            let stderr_task = tokio::spawn(async move {
1895                let mut buf = Vec::new();
1896                BufReader::new(stderr_h)
1897                    .read_to_end(&mut buf)
1898                    .await
1899                    .map(|_| buf)
1900            });
1901
1902            let status = match tokio::time::timeout(action_timeout(), child.wait()).await {
1903                Ok(Ok(status)) => status,
1904                // Same rule as the streaming path: a `wait` that fails leaves a
1905                // privileged child in an unknown state, so stop the group before
1906                // reporting the failure upward.
1907                Ok(Err(err)) => {
1908                    return Err(kill_and_reap(
1909                        &mut child,
1910                        program,
1911                        args,
1912                        StopCause::Unreadable(err),
1913                    )
1914                    .await)
1915                }
1916                Err(_) => {
1917                    return Err(kill_and_reap(&mut child, program, args, StopCause::Timeout).await)
1918                }
1919            };
1920            let join =
1921                |e| ExecutorError::Io(io::Error::other(format!("reader task panicked: {e}")));
1922            let stdout = stdout_task.await.map_err(join)??;
1923            let stderr = stderr_task.await.map_err(join)??;
1924
1925            Ok(ExecutionOutput {
1926                stdout: String::from_utf8_lossy(&stdout).into_owned(),
1927                stderr: String::from_utf8_lossy(&stderr).into_owned(),
1928                exit_code: status.code().unwrap_or(-1),
1929            })
1930        }
1931        ActionMechanism::FileScan { path } => {
1932            let mut entries = tokio::fs::read_dir(path).await?;
1933            let mut names = Vec::new();
1934            while let Some(entry) = entries.next_entry().await? {
1935                names.push(entry.file_name().to_string_lossy().into_owned());
1936            }
1937            names.sort();
1938            Ok(ExecutionOutput {
1939                stdout: names.join("\n"),
1940                stderr: String::new(),
1941                exit_code: 0,
1942            })
1943        }
1944        ActionMechanism::FileWrite { path, content } => {
1945            if let Some(parent) = std::path::Path::new(path).parent() {
1946                tokio::fs::create_dir_all(parent).await?;
1947            }
1948            tokio::fs::write(path, content).await?;
1949            Ok(ExecutionOutput {
1950                stdout: String::new(),
1951                stderr: String::new(),
1952                exit_code: 0,
1953            })
1954        }
1955        ActionMechanism::FilePatch {
1956            path,
1957            search,
1958            replace,
1959        } => {
1960            let content = tokio::fs::read_to_string(path).await?;
1961            let patched = content.replacen(search.as_str(), replace.as_str(), 1);
1962            if patched == content && !search.is_empty() {
1963                return Ok(ExecutionOutput {
1964                    stdout: String::new(),
1965                    stderr: format!("search string not found in file: {}", path),
1966                    exit_code: 1,
1967                });
1968            }
1969            tokio::fs::write(path, patched).await?;
1970            Ok(ExecutionOutput {
1971                stdout: String::new(),
1972                stderr: String::new(),
1973                exit_code: 0,
1974            })
1975        }
1976        ActionMechanism::FileDelete { path } => {
1977            tokio::fs::remove_file(path).await?;
1978            Ok(ExecutionOutput {
1979                stdout: String::new(),
1980                stderr: String::new(),
1981                exit_code: 0,
1982            })
1983        }
1984    }
1985}
1986
1987fn require_str<'a>(params: &'a Value, key: &'static str) -> Result<&'a str, ExecutorError> {
1988    match params.get(key) {
1989        None => Err(ExecutorError::MissingParam(key)),
1990        Some(v) => v.as_str().ok_or(ExecutorError::InvalidParam(key)),
1991    }
1992}
1993
1994/// Extract an optional string param and validate it. An absent key or an empty
1995/// string yields `None` (the filter is simply omitted); a present non-empty
1996/// value is passed through `validator`, propagating any validation error.
1997fn optional_validated<F>(
1998    params: &Value,
1999    key: &'static str,
2000    validator: F,
2001) -> Result<Option<String>, ExecutorError>
2002where
2003    F: FnOnce(&str, &'static str) -> Result<String, ExecutorError>,
2004{
2005    match params
2006        .get(key)
2007        .and_then(|v| v.as_str())
2008        .filter(|s| !s.is_empty())
2009    {
2010        Some(s) => Ok(Some(validator(s, key)?)),
2011        None => Ok(None),
2012    }
2013}
2014
2015/// Extract the username from params, accepting either `"username"` or `"user"`
2016/// as the key.  The `"username"` key takes precedence.
2017///
2018/// Tolerates the `"user"` alias because LLMs trained on general Linux tooling
2019/// frequently produce `"user"` — accepting both here eliminates an entire class
2020/// of Describe/Execute failures without requiring the model to be perfect.
2021///
2022/// Returns [`ExecutorError::MissingParam`] if neither key is present,
2023/// [`ExecutorError::InvalidParam`] if the value is not a string.
2024fn resolve_username(params: &Value) -> Result<&str, ExecutorError> {
2025    params
2026        .get("username")
2027        .or_else(|| params.get("user"))
2028        .ok_or(ExecutorError::MissingParam("username"))
2029        .and_then(|v| v.as_str().ok_or(ExecutorError::InvalidParam("username")))
2030}
2031
2032/// Validate a repo_id: must be non-empty and contain only ASCII letters,
2033/// digits, hyphens, and underscores. Rejects `/`, `.`, and whitespace to
2034/// prevent path traversal (e.g. `../cron.d/evil`) and shell injection.
2035fn validated_repo_id(params: &Value) -> Result<&str, ExecutorError> {
2036    let id = require_str(params, "repo_id")?;
2037    let valid = !id.is_empty()
2038        && id
2039            .chars()
2040            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
2041    if valid {
2042        Ok(id)
2043    } else {
2044        Err(ExecutorError::InvalidParam("repo_id"))
2045    }
2046}
2047
2048/// Validate that a string contains no newlines. Used for repo_url to prevent
2049/// INI-section injection into `.repo` file content.
2050fn validated_no_newline<'a>(
2051    params: &'a Value,
2052    key: &'static str,
2053) -> Result<&'a str, ExecutorError> {
2054    let val = require_str(params, key)?;
2055    if val.contains('\n') || val.contains('\r') {
2056        Err(ExecutorError::InvalidParam(key))
2057    } else {
2058        Ok(val)
2059    }
2060}
2061
2062/// Validate an SSH public key: must start with a known key-type prefix,
2063/// contain only printable ASCII, no newlines, no single quotes (to prevent
2064/// shell injection in `sh -c` scripts), and be at most 8192 characters.
2065fn validated_public_key(s: &str) -> Result<String, ExecutorError> {
2066    const MAX_LEN: usize = 8192;
2067    const ALLOWED_PREFIXES: &[&str] = &[
2068        "ssh-rsa",
2069        "ssh-ed25519",
2070        "ssh-ed25519-sk",
2071        "ecdsa-sha2-nistp256",
2072        "ecdsa-sha2-nistp384",
2073        "ecdsa-sha2-nistp521",
2074        "sk-ssh-ed25519",
2075        "sk-ecdsa-sha2-nistp256",
2076    ];
2077
2078    if s.is_empty() || s.len() > MAX_LEN {
2079        return Err(ExecutorError::InvalidParam("public_key"));
2080    }
2081    if !ALLOWED_PREFIXES.iter().any(|p| s.starts_with(p)) {
2082        return Err(ExecutorError::InvalidParam("public_key"));
2083    }
2084    // No newlines, no shell metacharacters, only printable ASCII.
2085    //
2086    // Blocked characters and why:
2087    //   '\''  — breaks single-quoted shell strings in add_authorized_key
2088    //   '|'   — shell pipe (the ssh key ops no longer build a sed address,
2089    //           but '|' never appears in a valid key, so keep rejecting it)
2090    //   ';'   — shell command separator
2091    //   '`'   — shell command substitution
2092    //   '$'   — shell variable expansion
2093    //   '\\'  — shell escape; could be used to smuggle other metacharacters
2094    //   '&'   — shell background / AND operator
2095    //
2096    // None of these characters appear in valid SSH public key data (type prefix,
2097    // base64 body, or ASCII comment) so this list is safe to block unconditionally.
2098    if s.chars().any(|c| {
2099        matches!(c, '\n' | '\r' | '\'' | '|' | ';' | '`' | '$' | '\\' | '&')
2100            || !c.is_ascii()
2101            || c.is_ascii_control()
2102    }) {
2103        return Err(ExecutorError::InvalidParam("public_key"));
2104    }
2105    Ok(s.to_string())
2106}
2107
2108fn require_bool(params: &Value, key: &'static str) -> Result<bool, ExecutorError> {
2109    match params.get(key) {
2110        None => Err(ExecutorError::MissingParam(key)),
2111        Some(v) => v.as_bool().ok_or(ExecutorError::InvalidParam(key)),
2112    }
2113}
2114
2115fn require_u32(params: &Value, key: &'static str) -> Result<u32, ExecutorError> {
2116    match params.get(key) {
2117        None => Err(ExecutorError::MissingParam(key)),
2118        Some(v) => {
2119            let n = v.as_u64().ok_or(ExecutorError::InvalidParam(key))?;
2120            u32::try_from(n).map_err(|_| ExecutorError::InvalidParam(key))
2121        }
2122    }
2123}
2124
2125/// Like [`require_u32`] but additionally rejects zero.
2126///
2127/// Used for rule numbers and similar 1-based indices where 0 is never valid.
2128fn require_positive_u32(params: &Value, key: &'static str) -> Result<u32, ExecutorError> {
2129    let n = require_u32(params, key)?;
2130    if n == 0 {
2131        return Err(ExecutorError::InvalidParam(key));
2132    }
2133    Ok(n)
2134}
2135
2136/// Returns a vec of owned strings from a JSON array, or an empty vec if the
2137/// key is absent or null. Returns [`ExecutorError::InvalidParam`] if the key
2138/// is present but not an array of strings.
2139fn str_array_or_empty(params: &Value, key: &'static str) -> Result<Vec<String>, ExecutorError> {
2140    match params.get(key) {
2141        None | Some(Value::Null) => Ok(vec![]),
2142        Some(Value::Array(arr)) => arr
2143            .iter()
2144            .map(|v| {
2145                v.as_str()
2146                    .map(String::from)
2147                    .ok_or(ExecutorError::InvalidParam(key))
2148            })
2149            .collect(),
2150        _ => Err(ExecutorError::InvalidParam(key)),
2151    }
2152}
2153
2154/// Reject kernel command-line arguments that could bypass security mechanisms
2155/// or drop to an unauthenticated root shell on next boot. Applies only to
2156/// arguments being *added* (`SetKernelArguments`'s `add`, `GrubSetKargs`'s
2157/// `append`) — removing an existing argument is always safe.
2158///
2159/// `param` names the request field being validated so the error points at the
2160/// caller's actual parameter (`"add"` for `SetKernelArguments`, `"append"` for
2161/// `GrubSetKargs`).
2162///
2163/// This is a *denylist* layered on top of the caller's charset validation —
2164/// both callers run their charset check first. In particular `GrubSetKargs`
2165/// runs [`validated_safe_arg`] (which already rejects `=` and `,`), so on that
2166/// path the load-bearing checks here are the bare runlevel shortcuts
2167/// (`single`/`s`/`1`).
2168///
2169/// Blocked (case-insensitive):
2170///
2171/// - `init=`           — replaces init, can give a root shell
2172/// - `selinux=0`       — disables SELinux
2173/// - `enforcing=0`     — sets SELinux to permissive
2174/// - `security=`       — overrides LSM module selection
2175/// - `apparmor=0`      — disables the AppArmor LSM (Ubuntu's default MAC)
2176/// - `systemd.unit=emergency` / `systemd.unit=rescue` / `systemd.unit=single`
2177///   — unprotected root shell
2178/// - `single` / `1` / `s` — single-user mode (root without password)
2179/// - `module_blacklist=` — can disable security-critical kernel modules
2180/// - `mitigations=off` — disables CPU speculative-execution vulnerability
2181///   mitigations (Spectre/Meltdown/MDS/etc.)
2182/// - `lockdown=`       — weakens or disables the kernel lockdown LSM
2183/// - `pti=off`         — disables Page Table Isolation (Meltdown mitigation)
2184/// - `nosmap` / `nosmep` — disable SMAP/SMEP, CPU features that block a large
2185///   class of kernel-exploitation techniques
2186/// - `systemd.debug_shell` — the same root shell as `systemd.unit=debug-shell`,
2187///   asked for by a different name
2188fn validated_safe_kernel_arg(arg: &str, param: &'static str) -> Result<(), ExecutorError> {
2189    const BLOCKED_PREFIXES: &[&str] = &[
2190        "init=",
2191        "selinux=0",
2192        "enforcing=0",
2193        "security=",
2194        "module_blacklist=",
2195        "apparmor=0",
2196        "mitigations=off",
2197        "lockdown=",
2198        "pti=off",
2199        // `systemd.unit=` is not the only way to ask for `debug-shell.service`.
2200        // systemd-debug-generator also honours `systemd.debug_shell`, which
2201        // pulls the unit into the boot transaction and spawns a root shell on
2202        // tty9 before anyone logs in — the identical end state the
2203        // `BLOCKED_UNIT_PREFIXES` screen below exists to prevent. Underscore is
2204        // the real spelling per systemd-debug-generator(8); `rd.` is the
2205        // initrd-honoured variant, and the hyphen forms are listed so a
2206        // near-miss cannot creep back.
2207        "systemd.debug_shell",
2208        "systemd.debug-shell",
2209        "rd.systemd.debug_shell",
2210        "rd.systemd.debug-shell",
2211    ];
2212    const BLOCKED_EXACT: &[&str] = &["single", "s", "1", "nosmap", "nosmep"];
2213    // Shared with `validated_activatable_unit`, deliberately: these two screens
2214    // encode the same idea from opposite directions — one refuses to START a
2215    // root-shell unit, the other refuses to BOOT into it — and keeping two lists
2216    // let them drift until `debug-shell` and `runlevel1` were blocked on one path
2217    // and reachable on the other.
2218    use crate::actions::validate::ROOT_SHELL_UNITS as BLOCKED_UNIT_PREFIXES;
2219
2220    let lower = arg.to_lowercase();
2221    // Strip optional value (e.g. "quiet=1" → "quiet") for exact matches.
2222    let base = lower.split('=').next().unwrap_or(&lower);
2223
2224    if BLOCKED_PREFIXES.iter().any(|p| lower.starts_with(p)) {
2225        return Err(ExecutorError::InvalidParam(param));
2226    }
2227    if BLOCKED_EXACT.iter().any(|e| lower == *e) {
2228        return Err(ExecutorError::InvalidParam(param));
2229    }
2230    // Block systemd.unit= pointing to emergency/rescue/single targets.
2231    if let Some(unit_val) = lower.strip_prefix("systemd.unit=") {
2232        if BLOCKED_UNIT_PREFIXES
2233            .iter()
2234            .any(|u| unit_val.starts_with(u))
2235        {
2236            return Err(ExecutorError::InvalidParam(param));
2237        }
2238    }
2239    // Guard against the base arg matching dangerous exact values even with =.
2240    if BLOCKED_EXACT.contains(&base) {
2241        return Err(ExecutorError::InvalidParam(param));
2242    }
2243    Ok(())
2244}
2245
2246/// Validate a kernel argument that is about to be **removed** from the boot line.
2247///
2248/// [`validated_safe_kernel_arg`] screens additions. Removal was left unscreened
2249/// on the premise that "removing a dangerous arg is always safe", which inverts
2250/// the risk: the dangerous move is removing a *protective* arg. Deleting
2251/// `module.sig_enforce=1` or `lockdown=confidentiality` reaches the same end
2252/// state as adding its weakening counterpart, which the add-path refuses — so
2253/// leaving `remove` open handed back every guarantee the add-path buys.
2254///
2255/// The prefixes below are the KSPP-recommended boot parameters plus the LSM
2256/// selectors; each is a protection the host loses the moment the token leaves
2257/// the boot line. `WEAKENING` is the escape hatch that keeps the screen from
2258/// collapsing into "no removals at all": an argument that is itself a downgrade
2259/// must stay removable, or SysKnife could never harden a host that already boots
2260/// with `mitigations=off`.
2261fn validated_safe_kernel_arg_removal(arg: &str, param: &'static str) -> Result<(), ExecutorError> {
2262    /// Removing one of these hardens the host, so removal stays allowed even
2263    /// though the token matches a protective prefix below.
2264    const WEAKENING: &[&str] = &[
2265        "selinux=0",
2266        "enforcing=0",
2267        "apparmor=0",
2268        "mitigations=off",
2269        "pti=off",
2270        "lockdown=none",
2271        "debugfs=on",
2272        "iommu=off",
2273        "intel_iommu=off",
2274        "module.sig_enforce=0",
2275        "init_on_alloc=0",
2276        "init_on_free=0",
2277        "randomize_kstack_offset=off",
2278        "page_alloc.shuffle=0",
2279    ];
2280    const PROTECTIVE_PREFIXES: &[&str] = &[
2281        "lockdown=",
2282        "module.sig_enforce=",
2283        "security=",
2284        "selinux=",
2285        "enforcing=",
2286        "apparmor=",
2287        "pti=",
2288        "mitigations=",
2289        "init_on_alloc=",
2290        "init_on_free=",
2291        "page_alloc.shuffle=",
2292        "randomize_kstack_offset=",
2293        "slub_debug=",
2294        "page_poison=",
2295        "vsyscall=",
2296        "debugfs=",
2297        "iommu=",
2298        "intel_iommu=",
2299        "amd_iommu=",
2300    ];
2301    const PROTECTIVE_EXACT: &[&str] = &["slab_nomerge", "nosmt", "kaslr"];
2302
2303    let lower = arg.to_lowercase();
2304    if WEAKENING.contains(&lower.as_str()) {
2305        return Ok(());
2306    }
2307    // Protective wins over the add-path inversion below. `security=` is refused
2308    // by BOTH screens: adding it picks an LSM, removing it drops the one in use.
2309    if PROTECTIVE_PREFIXES.iter().any(|p| lower.starts_with(p))
2310        || PROTECTIVE_EXACT.contains(&lower.as_str())
2311    {
2312        return Err(ExecutorError::InvalidParam(param));
2313    }
2314    // Everything else — ordinary boot arguments, and the add-path's own denylist
2315    // (`init=`, a bare `single`, an emergency `systemd.unit=`, all weakenings the
2316    // host is better off without) — stays removable.
2317    Ok(())
2318}
2319
2320/// Validate a `kill` signal against a strict allowlist, returning the canonical
2321/// signal name for `kill -s <name>`.
2322///
2323/// Only stop/reload signals are permitted (`TERM`, `KILL`, `HUP`, `INT`); this
2324/// blocks exotic or numeric signals and, combined with the caller's `pid >= 2`
2325/// check, keeps `SignalProcess` from becoming an arbitrary-signal primitive.
2326/// Accepts case-insensitive input with an optional `SIG` prefix.
2327fn validated_kill_signal(s: &str) -> Result<&'static str, ExecutorError> {
2328    let normalized = s.trim().to_ascii_uppercase();
2329    match normalized.strip_prefix("SIG").unwrap_or(&normalized) {
2330        "TERM" => Ok("TERM"),
2331        "KILL" => Ok("KILL"),
2332        "HUP" => Ok("HUP"),
2333        "INT" => Ok("INT"),
2334        _ => Err(ExecutorError::InvalidParam("signal")),
2335    }
2336}
2337
2338/// Return the rollback [`ActionSpec`] for `action_name`, or `None` if no
2339/// automatic rollback is defined.
2340///
2341/// Only the rpm-ostree deployment and layering actions support rollback —
2342/// they all revert via `rpm-ostree rollback`. All other actions either have
2343/// no sensible rollback or are low-risk enough that a rollback would be
2344/// net-harmful.
2345///
2346/// `RollbackDeployment` itself is excluded to prevent infinite recursion.
2347pub fn rollback_spec_for(action_name: &str) -> Option<ActionSpec> {
2348    match action_name {
2349        "UpdateSystem"
2350        | "InstallPackages"
2351        | "RemovePackages"
2352        | "RebaseSystem"
2353        | "SetKernelArguments"
2354        | "AddLayeredPackage"
2355        | "RemoveLayeredPackage"
2356        | "ReplaceLayeredPackage"
2357        | "ResetLayeredPackageOverride"
2358        | "RemoveBasePackage" => Some(ActionSpec {
2359            action_name: "RollbackDeployment",
2360            mechanism: ActionMechanism::Command {
2361                program: "rpm-ostree",
2362                args: vec!["rollback".to_string()],
2363            },
2364            risk_level: sysknife_types::RiskLevel::High,
2365            reboot_required: true,
2366            rollback_available: false,
2367        }),
2368        _ => None,
2369    }
2370}
2371
2372#[cfg(test)]
2373mod tests {
2374    use super::*;
2375    use serde_json::json;
2376    use sysknife_types::RiskLevel;
2377    use tempfile::tempdir;
2378
2379    // ── build_action_spec ─────────────────────────────────────────────────
2380
2381    #[test]
2382    fn build_spec_no_params_for_get_system_state() {
2383        let spec = build_action_spec("GetSystemState", &json!({})).unwrap();
2384        assert_eq!(spec.action_name, "GetSystemState");
2385        assert_eq!(spec.risk_level, RiskLevel::Low);
2386    }
2387
2388    #[test]
2389    fn build_spec_get_datetime_is_low_risk() {
2390        let spec = build_action_spec("GetDateTime", &json!({})).unwrap();
2391        assert_eq!(spec.action_name, "GetDateTime");
2392        assert_eq!(spec.risk_level, RiskLevel::Low);
2393        assert!(!spec.reboot_required);
2394    }
2395
2396    #[test]
2397    fn build_spec_unknown_action_returns_error() {
2398        let err = build_action_spec("NonExistent", &json!({})).unwrap_err();
2399        assert!(
2400            matches!(&err, ExecutorError::UnknownAction(n) if n == "NonExistent"),
2401            "expected UnknownAction, got: {err}"
2402        );
2403    }
2404
2405    #[test]
2406    fn build_spec_missing_param_for_install_flatpak() {
2407        // username is the first required param; its absence is reported first.
2408        let err = build_action_spec("InstallFlatpak", &json!({})).unwrap_err();
2409        assert!(
2410            matches!(err, ExecutorError::MissingParam("username")),
2411            "expected MissingParam(username), got: {err}"
2412        );
2413    }
2414
2415    /// LLMs trained on standard Linux tooling frequently produce `"user"` instead
2416    /// of `"username"`.  `resolve_username` accepts both keys so these actions
2417    /// never fail with a spurious MissingParam.
2418    #[test]
2419    fn build_spec_flatpak_accepts_user_alias() {
2420        let spec = build_action_spec("ListInstalledFlatpaks", &json!({ "user": "alice" })).unwrap();
2421        assert_eq!(spec.action_name, "ListInstalledFlatpaks");
2422    }
2423
2424    /// `resolve_username` prefers `"username"` when both keys are present.
2425    #[test]
2426    fn build_spec_resolve_username_prefers_explicit_username() {
2427        let spec = build_action_spec(
2428            "ListInstalledFlatpaks",
2429            &json!({ "username": "alice", "user": "bob" }),
2430        )
2431        .unwrap();
2432        // Verify it didn't error — the "alice" value passes validation.
2433        assert_eq!(spec.action_name, "ListInstalledFlatpaks");
2434    }
2435
2436    /// `remote` defaults to "flathub" when absent — eliminates the most common
2437    /// model omission without changing behaviour when the param is explicit.
2438    #[test]
2439    fn build_spec_install_flatpak_defaults_remote_to_flathub() {
2440        let spec = build_action_spec(
2441            "InstallFlatpak",
2442            &json!({ "username": "alice", "app_id": "org.mozilla.firefox" }),
2443        )
2444        .unwrap();
2445        assert_eq!(
2446            spec.mechanism,
2447            ActionMechanism::Command {
2448                program: "sudo",
2449                args: vec![
2450                    "runuser".to_string(),
2451                    "-u".to_string(),
2452                    "alice".to_string(),
2453                    "--".to_string(),
2454                    "flatpak".to_string(),
2455                    "install".to_string(),
2456                    "--user".to_string(),
2457                    "-y".to_string(),
2458                    "flathub".to_string(),
2459                    "org.mozilla.firefox".to_string(),
2460                ],
2461            }
2462        );
2463    }
2464
2465    #[test]
2466    fn build_spec_install_flatpak_injects_app_and_remote() {
2467        let spec = build_action_spec(
2468            "InstallFlatpak",
2469            &json!({
2470                "username": "alice",
2471                "app_id": "org.mozilla.firefox",
2472                "remote": "flathub"
2473            }),
2474        )
2475        .unwrap();
2476        assert_eq!(spec.action_name, "InstallFlatpak");
2477        assert_eq!(
2478            spec.mechanism,
2479            ActionMechanism::Command {
2480                program: "sudo",
2481                args: vec![
2482                    "runuser".to_string(),
2483                    "-u".to_string(),
2484                    "alice".to_string(),
2485                    "--".to_string(),
2486                    "flatpak".to_string(),
2487                    "install".to_string(),
2488                    "--user".to_string(),
2489                    "-y".to_string(),
2490                    "flathub".to_string(),
2491                    "org.mozilla.firefox".to_string(),
2492                ],
2493            }
2494        );
2495    }
2496
2497    #[test]
2498    fn build_spec_pin_deployment_injects_index() {
2499        let spec = build_action_spec("PinDeployment", &json!({ "index": 1 })).unwrap();
2500        assert_eq!(
2501            spec.mechanism,
2502            ActionMechanism::Command {
2503                program: "sudo",
2504                args: vec![
2505                    "ostree".to_string(),
2506                    "admin".to_string(),
2507                    "pin".to_string(),
2508                    "1".to_string()
2509                ],
2510            }
2511        );
2512    }
2513
2514    #[test]
2515    fn build_spec_unpin_deployment_includes_unpin_flag() {
2516        let spec = build_action_spec("UnpinDeployment", &json!({ "index": 2 })).unwrap();
2517        assert_eq!(
2518            spec.mechanism,
2519            ActionMechanism::Command {
2520                program: "sudo",
2521                args: vec![
2522                    "ostree".to_string(),
2523                    "admin".to_string(),
2524                    "pin".to_string(),
2525                    "--unpin".to_string(),
2526                    "2".to_string(),
2527                ],
2528            }
2529        );
2530    }
2531
2532    #[test]
2533    fn require_u32_rejects_overflow() {
2534        let err = build_action_spec("PinDeployment", &json!({ "index": u64::MAX })).unwrap_err();
2535        assert!(
2536            matches!(err, ExecutorError::InvalidParam("index")),
2537            "expected InvalidParam(index), got: {err}"
2538        );
2539    }
2540
2541    #[test]
2542    fn build_spec_rebase_system_injects_target_ref() {
2543        let spec = build_action_spec(
2544            "RebaseSystem",
2545            &json!({ "target_ref": "fedora/41/x86_64/silverblue" }),
2546        )
2547        .unwrap();
2548        assert_eq!(
2549            spec.mechanism,
2550            ActionMechanism::Command {
2551                program: "sudo",
2552                args: vec![
2553                    "rpm-ostree".to_string(),
2554                    "rebase".to_string(),
2555                    "fedora/41/x86_64/silverblue".to_string(),
2556                ],
2557            }
2558        );
2559    }
2560
2561    #[test]
2562    fn build_spec_set_kernel_arguments_appends_and_deletes() {
2563        let spec = build_action_spec(
2564            "SetKernelArguments",
2565            &json!({ "add": ["nomodeset"], "remove": ["quiet"] }),
2566        )
2567        .unwrap();
2568        assert_eq!(
2569            spec.mechanism,
2570            ActionMechanism::Command {
2571                program: "sudo",
2572                args: vec![
2573                    "rpm-ostree".to_string(),
2574                    "kargs".to_string(),
2575                    "--append=nomodeset".to_string(),
2576                    "--delete=quiet".to_string(),
2577                ],
2578            }
2579        );
2580    }
2581
2582    #[test]
2583    fn build_spec_set_kernel_arguments_with_empty_arrays() {
2584        let spec =
2585            build_action_spec("SetKernelArguments", &json!({ "add": [], "remove": [] })).unwrap();
2586        assert_eq!(
2587            spec.mechanism,
2588            ActionMechanism::Command {
2589                program: "sudo",
2590                args: vec!["rpm-ostree".to_string(), "kargs".to_string()],
2591            }
2592        );
2593    }
2594
2595    #[test]
2596    fn build_spec_set_kernel_arguments_defaults_when_keys_absent() {
2597        let spec = build_action_spec("SetKernelArguments", &json!({})).unwrap();
2598        assert_eq!(
2599            spec.mechanism,
2600            ActionMechanism::Command {
2601                program: "sudo",
2602                args: vec!["rpm-ostree".to_string(), "kargs".to_string()],
2603            }
2604        );
2605    }
2606
2607    // ── Critical-account denylist (DeleteUser/DeleteGroup/LockUserAccount) ──
2608
2609    #[test]
2610    fn delete_user_rejects_critical_account() {
2611        let err = build_action_spec("DeleteUser", &json!({ "username": "root" })).unwrap_err();
2612        assert!(
2613            matches!(err, ExecutorError::InvalidParam("username")),
2614            "expected InvalidParam(username), got: {err}"
2615        );
2616    }
2617
2618    #[test]
2619    fn delete_group_rejects_critical_group() {
2620        let err = build_action_spec("DeleteGroup", &json!({ "group": "sudo" })).unwrap_err();
2621        assert!(
2622            matches!(err, ExecutorError::InvalidParam("group")),
2623            "expected InvalidParam(group), got: {err}"
2624        );
2625    }
2626
2627    #[test]
2628    fn lock_user_account_rejects_critical_account() {
2629        let err = build_action_spec("LockUserAccount", &json!({ "username": "root" })).unwrap_err();
2630        assert!(
2631            matches!(err, ExecutorError::InvalidParam("username")),
2632            "expected InvalidParam(username), got: {err}"
2633        );
2634    }
2635
2636    #[test]
2637    fn delete_user_lock_user_account_and_delete_group_allow_normal_names() {
2638        assert!(build_action_spec("DeleteUser", &json!({ "username": "alice" })).is_ok());
2639        assert!(build_action_spec("LockUserAccount", &json!({ "username": "alice" })).is_ok());
2640        assert!(build_action_spec("DeleteGroup", &json!({ "group": "developers" })).is_ok());
2641    }
2642
2643    // ── execute_spec ──────────────────────────────────────────────────────
2644
2645    #[test]
2646    fn build_spec_add_package_repository_rejects_path_traversal() {
2647        let err = build_action_spec(
2648            "AddPackageRepository",
2649            &json!({ "repo_id": "../cron.d/evil", "repo_url": "https://evil.example/repo" }),
2650        )
2651        .unwrap_err();
2652        assert!(
2653            matches!(err, ExecutorError::InvalidParam("repo_id")),
2654            "expected InvalidParam(repo_id), got: {err}"
2655        );
2656    }
2657
2658    #[test]
2659    fn build_spec_add_package_repository_rejects_newline_in_url() {
2660        let err = build_action_spec(
2661            "AddPackageRepository",
2662            &json!({ "repo_id": "myrepo", "repo_url": "https://ok.example/\nbaseurl=evil" }),
2663        )
2664        .unwrap_err();
2665        assert!(
2666            matches!(err, ExecutorError::InvalidParam("repo_url")),
2667            "expected InvalidParam(repo_url), got: {err}"
2668        );
2669    }
2670
2671    #[test]
2672    fn build_spec_add_package_repository_accepts_valid_repo_id() {
2673        let spec = build_action_spec(
2674            "AddPackageRepository",
2675            &json!({ "repo_id": "my-repo_123", "repo_url": "https://ok.example/repo" }),
2676        )
2677        .unwrap();
2678        assert_eq!(spec.action_name, "AddPackageRepository");
2679    }
2680
2681    #[test]
2682    fn build_spec_remove_package_repository_rejects_path_traversal() {
2683        let err = build_action_spec(
2684            "RemovePackageRepository",
2685            &json!({ "repo_id": "../../etc/passwd" }),
2686        )
2687        .unwrap_err();
2688        assert!(
2689            matches!(err, ExecutorError::InvalidParam("repo_id")),
2690            "expected InvalidParam(repo_id), got: {err}"
2691        );
2692    }
2693
2694    #[tokio::test]
2695    async fn execute_spec_command_captures_stdout() {
2696        let spec = ActionSpec {
2697            action_name: "GetSystemState",
2698            mechanism: ActionMechanism::Command {
2699                program: "echo",
2700                args: vec!["hello".to_string()],
2701            },
2702            risk_level: RiskLevel::Low,
2703            reboot_required: false,
2704            rollback_available: false,
2705        };
2706        let out = execute_spec(&spec).await.unwrap();
2707        assert_eq!(out.stdout.trim(), "hello");
2708        assert_eq!(out.exit_code, 0);
2709    }
2710
2711    /// Regression guard for the live subprocess stdout relay. This coverage
2712    /// previously lived in the dispatcher (`stream_command_sends_job_progress_
2713    /// lines_during_execution`) and was lost when the streaming code moved here;
2714    /// The `ActionNotStopped` message is what an operator reads in the job
2715    /// summary, and the dispatcher keys the rollback veto off this variant, so
2716    /// its fields and wording are load-bearing. No integration test constructs
2717    /// it (the real path needs a root child), so pin it directly.
2718    #[test]
2719    fn action_not_stopped_names_the_group_and_the_timeout() {
2720        let err = ExecutorError::ActionNotStopped {
2721            program: "rpm-ostree".to_string(),
2722            pgid: 4242,
2723            timeout_secs: 7200,
2724        };
2725        let msg = err.to_string();
2726        assert!(msg.contains("4242"), "must name the pgid to inspect: {msg}");
2727        assert!(msg.contains("7200"), "must name the timeout: {msg}");
2728        assert!(
2729            msg.contains("could not be confirmed stopped"),
2730            "must say what happened: {msg}"
2731        );
2732        assert!(
2733            msg.contains("rollback was skipped"),
2734            "must say the rollback was skipped: {msg}"
2735        );
2736    }
2737
2738    /// A same-uid group is genuinely killable, so `kill_and_reap` must return the
2739    /// plain stopped-timeout `Io`, not `ActionNotStopped`. This pins the
2740    /// discrimination the variant exists for, and that the function returns
2741    /// promptly rather than hanging on the reap.
2742    #[tokio::test]
2743    async fn kill_and_reap_confirms_a_killable_group_stopped_and_returns_bounded() {
2744        let mut child = tokio::process::Command::new("sh")
2745            .args(["-c", "sleep 3600 & wait"])
2746            .process_group(0)
2747            .stdin(Stdio::null())
2748            .stdout(Stdio::null())
2749            .stderr(Stdio::null())
2750            .spawn()
2751            .expect("spawn");
2752        SUDO_INVOCATIONS.store(0, std::sync::atomic::Ordering::SeqCst);
2753        let started = tokio::time::Instant::now();
2754        let err = kill_and_reap(&mut child, "sh", &[], StopCause::Timeout).await;
2755        let elapsed = started.elapsed();
2756
2757        assert!(
2758            matches!(&err, ExecutorError::Io(e) if e.kind() == io::ErrorKind::TimedOut),
2759            "a killable group must report a plain stopped-timeout, got: {err:?}"
2760        );
2761        assert!(
2762            elapsed < Duration::from_secs(GROUP_TERM_GRACE.as_secs() + 3),
2763            "must return promptly, took {elapsed:?}"
2764        );
2765        // A same-uid group is killed by the daemon's own signals, so the
2766        // privileged escalation must NOT fire (a mutation that always escalates
2767        // would shell out to sudo and trip this).
2768        assert_eq!(
2769            SUDO_INVOCATIONS.load(std::sync::atomic::Ordering::SeqCst),
2770            0,
2771            "a killable group must not escalate to the privileged reaper"
2772        );
2773    }
2774
2775    /// Losing the ability to READ a privileged child must stop it, exactly as a
2776    /// timeout does. `lines()` fails with `InvalidData` on non-UTF-8 stdout —
2777    /// reachable from any action whose output carries a byte sequence that is not
2778    /// valid UTF-8 (a filename in a foreign encoding is enough). Returning that
2779    /// error without reaping leaves a root process group running while the
2780    /// executor reports the action failed, so the dispatcher's rollback starts a
2781    /// second privileged transaction on top of the first.
2782    #[tokio::test]
2783    async fn a_child_that_outlives_a_stdout_read_failure_is_stopped_not_orphaned() {
2784        let dir = tempfile::tempdir().expect("tempdir");
2785        let pgid_file = dir.path().join("pgid");
2786        // `process_group(0)` makes the shell its own group leader, so `$$` IS the
2787        // pgid. It prints one good line, then a lone \377 (never valid UTF-8),
2788        // then outlives the read failure unless the executor stops it.
2789        let script = format!(
2790            "echo $$ > {}; echo started; printf '\\377\\n'; sleep 3600",
2791            pgid_file.display()
2792        );
2793        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
2794        let err = execute_command_with_progress("sh", &["-c".to_string(), script], tx)
2795            .await
2796            .expect_err("non-UTF-8 stdout must fail the action");
2797        assert!(
2798            matches!(&err, ExecutorError::Io(e) if e.kind() == io::ErrorKind::InvalidData),
2799            "the read failure itself must be surfaced, got: {err:?}"
2800        );
2801
2802        let pgid: i32 = std::fs::read_to_string(&pgid_file)
2803            .expect("the shell must have recorded its pgid")
2804            .trim()
2805            .parse()
2806            .expect("pgid");
2807        assert!(
2808            probe_group(pgid).is_gone(),
2809            "process group {pgid} survived the read failure; \
2810             the privileged child was orphaned"
2811        );
2812    }
2813
2814    #[test]
2815    fn reap_command_cancels_rpm_ostree_but_group_kills_everything_else() {
2816        // rpm-ostree -> cancel (its work is in another cgroup, a signal can't reach it).
2817        assert_eq!(
2818            reap_command(
2819                99,
2820                "sudo",
2821                &["/usr/bin/rpm-ostree".to_string(), "upgrade".to_string()]
2822            ),
2823            vec!["-n", "/usr/bin/rpm-ostree", "cancel"]
2824        );
2825        // Everything else -> a root TERM to its own process group.
2826        assert_eq!(
2827            reap_command(
2828                99,
2829                "sudo",
2830                &[
2831                    "env".to_string(),
2832                    "apt-get".to_string(),
2833                    "install".to_string()
2834                ]
2835            ),
2836            root_group_kill_argv("TERM", 99)
2837        );
2838    }
2839
2840    #[test]
2841    fn root_group_kill_argv_targets_the_whole_group_non_interactively() {
2842        // sudo -n /usr/bin/kill -s KILL -- -<pgid>: non-interactive (NOPASSWD),
2843        // options terminated so the negative pgid is a group, not a flag.
2844        assert_eq!(
2845            root_group_kill_argv("KILL", 4242),
2846            vec!["-n", "/usr/bin/kill", "-s", "KILL", "--", "-4242"]
2847        );
2848        assert_eq!(
2849            root_group_kill_argv("TERM", 7)[3..].to_vec(),
2850            vec!["TERM", "--", "-7"]
2851        );
2852    }
2853
2854    #[test]
2855    fn is_rpm_ostree_action_detects_the_transaction_client_behind_sudo() {
2856        let sudo = |a: &[&str]| {
2857            is_rpm_ostree_action("sudo", &a.iter().map(|s| s.to_string()).collect::<Vec<_>>())
2858        };
2859        // rpm-ostree runs behind sudo, absolute or bare, and directly.
2860        assert!(sudo(&["/usr/bin/rpm-ostree", "upgrade"]));
2861        assert!(sudo(&[
2862            "rpm-ostree",
2863            "rebase",
2864            "fedora:fedora/40/x86_64/silverblue"
2865        ]));
2866        assert!(is_rpm_ostree_action("rpm-ostree", &["status".to_string()]));
2867        // Package managers whose work IS in the process group must NOT be
2868        // treated as rpm-ostree (they get the group kill, not `cancel`).
2869        assert!(!sudo(&[
2870            "env",
2871            "DEBIAN_FRONTEND=noninteractive",
2872            "apt-get",
2873            "install",
2874            "vim"
2875        ]));
2876        assert!(!sudo(&["/usr/bin/kill", "-s", "KILL", "--", "-1"]));
2877        assert!(!is_rpm_ostree_action("sudo", &[]));
2878        // Absolute path as the top-level program (no sudo wrapper).
2879        assert!(is_rpm_ostree_action(
2880            "/usr/bin/rpm-ostree",
2881            &["deploy".to_string()]
2882        ));
2883        // A path segment must match, not a substring (guards a future refactor
2884        // to `.contains()`).
2885        assert!(!is_rpm_ostree_action(
2886            "sudo",
2887            &["explain-rpm-ostree-usage".to_string()]
2888        ));
2889    }
2890
2891    /// restored at its owning layer. Proves `RealActionExecutor` forwards each
2892    /// stdout line over the mpsc channel as it arrives and reports the exit code.
2893    #[tokio::test]
2894    async fn real_executor_streams_each_stdout_line() {
2895        let spec = ActionSpec {
2896            action_name: "GetSystemState",
2897            mechanism: ActionMechanism::Command {
2898                program: "printf",
2899                args: vec!["line-one\\nline-two\\nline-three\\n".to_string()],
2900            },
2901            risk_level: RiskLevel::Low,
2902            reboot_required: false,
2903            rollback_available: false,
2904        };
2905        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2906        let out = RealActionExecutor
2907            .execute_with_progress(&spec, tx)
2908            .await
2909            .unwrap();
2910
2911        let mut lines = Vec::new();
2912        while let Ok(line) = rx.try_recv() {
2913            lines.push(line);
2914        }
2915        assert_eq!(lines, vec!["line-one", "line-two", "line-three"]);
2916        assert_eq!(out.exit_code, 0);
2917        assert!(out.stdout.contains("line-two"));
2918    }
2919
2920    #[tokio::test]
2921    async fn execute_spec_file_write_creates_file() {
2922        let dir = tempdir().unwrap();
2923        let path = dir.path().join("test.conf").to_string_lossy().into_owned();
2924        let spec = ActionSpec {
2925            action_name: "AddPackageRepository",
2926            mechanism: ActionMechanism::FileWrite {
2927                path: path.clone(),
2928                content: "[repo]\nbaseurl=https://example.test\n".to_string(),
2929            },
2930            risk_level: RiskLevel::Medium,
2931            reboot_required: false,
2932            rollback_available: true,
2933        };
2934        let out = execute_spec(&spec).await.unwrap();
2935        assert_eq!(out.exit_code, 0);
2936        assert_eq!(
2937            std::fs::read_to_string(&path).unwrap(),
2938            "[repo]\nbaseurl=https://example.test\n"
2939        );
2940    }
2941
2942    #[tokio::test]
2943    async fn execute_spec_file_patch_replaces_first_occurrence() {
2944        let dir = tempdir().unwrap();
2945        let path = dir.path().join("repo.conf").to_string_lossy().into_owned();
2946        std::fs::write(&path, "[myrepo]\nenabled=0\n").unwrap();
2947        let spec = ActionSpec {
2948            action_name: "EnablePackageRepository",
2949            mechanism: ActionMechanism::FilePatch {
2950                path: path.clone(),
2951                search: "enabled=0".to_string(),
2952                replace: "enabled=1".to_string(),
2953            },
2954            risk_level: RiskLevel::Medium,
2955            reboot_required: false,
2956            rollback_available: true,
2957        };
2958        execute_spec(&spec).await.unwrap();
2959        assert_eq!(
2960            std::fs::read_to_string(&path).unwrap(),
2961            "[myrepo]\nenabled=1\n"
2962        );
2963    }
2964
2965    #[tokio::test]
2966    async fn execute_spec_file_patch_returns_error_when_search_not_found() {
2967        let dir = tempdir().unwrap();
2968        let path = dir.path().join("repo.conf").to_string_lossy().into_owned();
2969        std::fs::write(&path, "[myrepo]\nenabled=1\n").unwrap();
2970        let spec = ActionSpec {
2971            action_name: "EnablePackageRepository",
2972            mechanism: ActionMechanism::FilePatch {
2973                path: path.clone(),
2974                search: "enabled=0".to_string(),
2975                replace: "enabled=1".to_string(),
2976            },
2977            risk_level: RiskLevel::Medium,
2978            reboot_required: false,
2979            rollback_available: true,
2980        };
2981        let out = execute_spec(&spec).await.unwrap();
2982        assert_eq!(out.exit_code, 1, "should fail when search string is absent");
2983        assert!(
2984            out.stderr.contains("search string not found in file"),
2985            "stderr should explain the failure: {}",
2986            out.stderr
2987        );
2988        // File should remain unchanged.
2989        assert_eq!(
2990            std::fs::read_to_string(&path).unwrap(),
2991            "[myrepo]\nenabled=1\n"
2992        );
2993    }
2994
2995    #[tokio::test]
2996    async fn execute_spec_file_patch_allows_empty_search_string() {
2997        // An empty search string triggers replacen's prepend behavior and should
2998        // not be rejected — the caller explicitly asked for a no-op search.
2999        let dir = tempdir().unwrap();
3000        let path = dir.path().join("file.txt").to_string_lossy().into_owned();
3001        std::fs::write(&path, "hello").unwrap();
3002        let spec = ActionSpec {
3003            action_name: "Test",
3004            mechanism: ActionMechanism::FilePatch {
3005                path: path.clone(),
3006                search: String::new(),
3007                replace: "prefix-".to_string(),
3008            },
3009            risk_level: RiskLevel::Low,
3010            reboot_required: false,
3011            rollback_available: false,
3012        };
3013        let out = execute_spec(&spec).await.unwrap();
3014        assert_eq!(out.exit_code, 0);
3015        assert_eq!(std::fs::read_to_string(&path).unwrap(), "prefix-hello");
3016    }
3017
3018    #[tokio::test]
3019    async fn execute_spec_file_delete_removes_file() {
3020        let dir = tempdir().unwrap();
3021        let path = dir.path().join("repo.conf").to_string_lossy().into_owned();
3022        std::fs::write(&path, "[myrepo]\n").unwrap();
3023        let spec = ActionSpec {
3024            action_name: "RemovePackageRepository",
3025            mechanism: ActionMechanism::FileDelete { path: path.clone() },
3026            risk_level: RiskLevel::Medium,
3027            reboot_required: false,
3028            rollback_available: true,
3029        };
3030        execute_spec(&spec).await.unwrap();
3031        assert!(!std::path::Path::new(&path).exists());
3032    }
3033
3034    #[tokio::test]
3035    async fn execute_spec_file_scan_lists_directory_entries() {
3036        let dir = tempdir().unwrap();
3037        std::fs::write(dir.path().join("a.repo"), "[a]\n").unwrap();
3038        std::fs::write(dir.path().join("b.repo"), "[b]\n").unwrap();
3039        let spec = ActionSpec {
3040            action_name: "ListPackageRepositories",
3041            mechanism: ActionMechanism::FileScan {
3042                path: dir.path().to_string_lossy().into_owned(),
3043            },
3044            risk_level: RiskLevel::Low,
3045            reboot_required: false,
3046            rollback_available: false,
3047        };
3048        let out = execute_spec(&spec).await.unwrap();
3049        assert!(
3050            out.stdout.contains("a.repo"),
3051            "expected a.repo in: {}",
3052            out.stdout
3053        );
3054        assert!(
3055            out.stdout.contains("b.repo"),
3056            "expected b.repo in: {}",
3057            out.stdout
3058        );
3059        assert_eq!(out.exit_code, 0);
3060    }
3061
3062    // ── rollback_spec_for ─────────────────────────────────────────────────────
3063
3064    #[test]
3065    fn rollback_spec_for_update_system_is_rpm_ostree_rollback() {
3066        let spec = rollback_spec_for("UpdateSystem").unwrap();
3067        assert_eq!(spec.action_name, "RollbackDeployment");
3068        assert!(
3069            matches!(
3070                &spec.mechanism,
3071                ActionMechanism::Command { program: "rpm-ostree", args }
3072                if args == &["rollback".to_string()]
3073            ),
3074            "expected rpm-ostree rollback, got: {:?}",
3075            spec.mechanism
3076        );
3077        assert!(!spec.rollback_available, "rollback spec must not recurse");
3078    }
3079
3080    #[test]
3081    fn rollback_spec_for_install_packages_is_rpm_ostree_rollback() {
3082        assert!(rollback_spec_for("InstallPackages").is_some());
3083    }
3084
3085    #[test]
3086    fn rollback_spec_for_remove_packages_is_rpm_ostree_rollback() {
3087        assert!(rollback_spec_for("RemovePackages").is_some());
3088    }
3089
3090    #[test]
3091    fn rollback_spec_for_rebase_system_is_rpm_ostree_rollback() {
3092        assert!(rollback_spec_for("RebaseSystem").is_some());
3093    }
3094
3095    #[test]
3096    fn rollback_spec_for_set_kernel_arguments_is_rpm_ostree_rollback() {
3097        assert!(rollback_spec_for("SetKernelArguments").is_some());
3098    }
3099
3100    #[test]
3101    fn rollback_spec_for_read_only_action_returns_none() {
3102        assert!(rollback_spec_for("GetSystemState").is_none());
3103        assert!(rollback_spec_for("ListUsers").is_none());
3104        assert!(rollback_spec_for("GetFirewallState").is_none());
3105    }
3106
3107    #[test]
3108    fn rollback_spec_for_non_rollbackable_actions_return_none() {
3109        assert!(rollback_spec_for("AddUserToGroup").is_none());
3110        assert!(rollback_spec_for("DeleteUser").is_none());
3111        assert!(rollback_spec_for("CleanupDeployments").is_none());
3112        // No infinite recursion — RollbackDeployment has no rollback of its own
3113        assert!(rollback_spec_for("RollbackDeployment").is_none());
3114    }
3115
3116    // ── validated_public_key ──────────────────────────────────────────────
3117
3118    #[test]
3119    fn public_key_accepts_valid_ed25519() {
3120        let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host";
3121        assert!(validated_public_key(key).is_ok());
3122    }
3123
3124    #[test]
3125    fn public_key_accepts_valid_rsa() {
3126        let key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCtest user@host";
3127        assert!(validated_public_key(key).is_ok());
3128    }
3129
3130    #[test]
3131    fn public_key_rejects_empty() {
3132        assert!(matches!(
3133            validated_public_key(""),
3134            Err(ExecutorError::InvalidParam("public_key"))
3135        ));
3136    }
3137
3138    #[test]
3139    fn public_key_rejects_unknown_prefix() {
3140        assert!(matches!(
3141            validated_public_key("sk-rsa AAAA... user@host"),
3142            Err(ExecutorError::InvalidParam("public_key"))
3143        ));
3144        assert!(matches!(
3145            validated_public_key("AAAAB3Nz... user@host"),
3146            Err(ExecutorError::InvalidParam("public_key"))
3147        ));
3148    }
3149
3150    #[test]
3151    fn public_key_rejects_single_quote() {
3152        let key = "ssh-ed25519 AAAA' $(rm -rf /) user@host";
3153        assert!(matches!(
3154            validated_public_key(key),
3155            Err(ExecutorError::InvalidParam("public_key"))
3156        ));
3157    }
3158
3159    /// The install/remove package actions must refuse a filesystem path, because
3160    /// `apt-get install /tmp/x.deb` / `rpm-ostree install /tmp/x.rpm` install a
3161    /// local file and run its scripts as root. `validate.rs` proves the validator
3162    /// refuses paths; only this proves each action arm actually calls it. Table
3163    /// driven so an arm added later that forgets the validator fails here, which
3164    /// is exactly the regression that shipped `InstallPackages`/`RemovePackages`
3165    /// on the generic safe-arg by mistake.
3166    #[test]
3167    fn package_actions_reject_a_local_file_target() {
3168        let reject: &[(&str, serde_json::Value)] = &[
3169            ("AptInstall", json!({"package": "/tmp/evil.deb"})),
3170            ("AptRemove", json!({"package": "/tmp/evil.deb"})),
3171            ("AptPurge", json!({"package": "./evil.deb"})),
3172            ("AptHold", json!({"package": "/tmp/evil.deb"})),
3173            ("AptUnhold", json!({"package": "/tmp/evil.deb"})),
3174            ("AddLayeredPackage", json!({"package": "/tmp/evil.rpm"})),
3175            ("RemoveLayeredPackage", json!({"package": "/tmp/evil.rpm"})),
3176            ("RemoveBasePackage", json!({"package": "/tmp/evil.rpm"})),
3177            (
3178                "ReplaceLayeredPackage",
3179                json!({"old": "/tmp/evil.rpm", "new": "nginx"}),
3180            ),
3181            (
3182                "ReplaceLayeredPackage",
3183                json!({"old": "nginx", "new": "/tmp/evil.rpm"}),
3184            ),
3185            ("InstallPackages", json!({"packages": ["/tmp/evil.rpm"]})),
3186            ("RemovePackages", json!({"packages": ["/tmp/evil.rpm"]})),
3187        ];
3188        for (action, params) in reject {
3189            assert!(
3190                matches!(
3191                    build_action_spec(action, params),
3192                    Err(ExecutorError::InvalidParam(_))
3193                ),
3194                "{action} must refuse a local-file package target: {params}"
3195            );
3196        }
3197        // Positive twin: real package specs must still build, or the test above
3198        // would pass for a validator that rejects everything.
3199        let accept: &[(&str, serde_json::Value)] = &[
3200            ("AptInstall", json!({"package": "nginx"})),
3201            ("AddLayeredPackage", json!({"package": "nginx=1.24.0-1"})),
3202            (
3203                "InstallPackages",
3204                json!({"packages": ["nginx", "python3-pip"]}),
3205            ),
3206        ];
3207        for (action, params) in accept {
3208            assert!(
3209                build_action_spec(action, params).is_ok(),
3210                "{action} must accept a real package spec: {params}"
3211            );
3212        }
3213    }
3214
3215    /// The activation verbs must refuse a root-shell unit through the reachable
3216    /// action, and `SetServiceEnabled` must gate only on `enabled: true`. Mutation
3217    /// testing showed reverting these call sites to the loose validator passed the
3218    /// whole suite, so the denylist was pinned only at the validator, not here.
3219    #[test]
3220    fn activating_actions_refuse_a_root_shell_unit() {
3221        for action in ["StartService", "RestartService", "UnmaskService"] {
3222            for unit in [
3223                "debug-shell.service",
3224                "emergency.target",
3225                "rescue.service",
3226                "runlevel1.target",
3227            ] {
3228                assert!(
3229                    matches!(
3230                        build_action_spec(action, &json!({"unit": unit})),
3231                        Err(ExecutorError::InvalidParam("unit"))
3232                    ),
3233                    "{action} must not activate {unit}"
3234                );
3235            }
3236            assert!(
3237                build_action_spec(action, &json!({"unit": "nginx.service"})).is_ok(),
3238                "{action} must still activate an ordinary unit"
3239            );
3240        }
3241        assert!(
3242            build_action_spec(
3243                "SetServiceEnabled",
3244                &json!({"unit": "debug-shell.service", "enabled": true})
3245            )
3246            .is_err(),
3247            "enabling a root-shell unit brings it up at boot and must be refused"
3248        );
3249        assert!(
3250            build_action_spec(
3251                "SetServiceEnabled",
3252                &json!({"unit": "debug-shell.service", "enabled": false})
3253            )
3254            .is_ok(),
3255            "disabling a root-shell unit is a mitigation and must stay reachable"
3256        );
3257        // The safe verbs must not have been tightened into the denylist, or an
3258        // operator loses the ability to stop or mask a running root shell.
3259        for action in ["StopService", "MaskService"] {
3260            assert!(
3261                build_action_spec(action, &json!({"unit": "debug-shell.service"})).is_ok(),
3262                "{action} on debug-shell is a mitigation and must stay allowed"
3263            );
3264        }
3265    }
3266
3267    #[test]
3268    fn authorized_keys_actions_reject_a_traversal_username() {
3269        // `actions/ssh.rs` builds `/home/{username}/.ssh/authorized_keys` by
3270        // interpolation, so the only thing keeping the path inside the user's
3271        // home is `validated_username` being called in these three match arms.
3272        // `validate.rs` tests the validator in isolation, and `ssh_key_ops.rs`
3273        // calls the action functions directly — neither proves the guard is
3274        // actually wired to the reachable actions.
3275        for action in [
3276            "GetAuthorizedKeys",
3277            "AddAuthorizedKey",
3278            "RemoveAuthorizedKey",
3279        ] {
3280            for bad in ["../../etc", "..", "root/../../etc"] {
3281                let err = build_action_spec(
3282                    action,
3283                    &json!({
3284                        "username": bad,
3285                        "public_key": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample u@h",
3286                    }),
3287                )
3288                .unwrap_err();
3289                assert!(
3290                    matches!(err, ExecutorError::InvalidParam("username")),
3291                    "{action} must reject username {bad:?}, got {err:?}"
3292                );
3293            }
3294        }
3295    }
3296
3297    #[test]
3298    fn ip_taking_actions_reject_a_malformed_address() {
3299        // `ExecutorError::InvalidIpAddress` was constructed by three actions
3300        // and reached by no test.
3301        let cases: [(&str, serde_json::Value); 3] = [
3302            (
3303                "ResolvectlSetDns",
3304                json!({ "interface": "eth0", "servers": ["not-an-ip"] }),
3305            ),
3306            (
3307                "Fail2banBanIp",
3308                json!({ "jail": "sshd", "ip": "999.1.1.1" }),
3309            ),
3310            (
3311                "Fail2banUnbanIp",
3312                json!({ "jail": "sshd", "ip": "1.2.3.4.5" }),
3313            ),
3314        ];
3315        for (action, params) in cases {
3316            let err = build_action_spec(action, &params).unwrap_err();
3317            assert!(
3318                matches!(err, ExecutorError::InvalidIpAddress { .. }),
3319                "{action} must reject a malformed IP, got {err:?}"
3320            );
3321        }
3322    }
3323
3324    #[test]
3325    fn public_key_rejects_pipe_metacharacter() {
3326        // '|' is a shell pipe and never appears in a valid key. (It was also
3327        // the sed address delimiter before the key ops were made regex-free;
3328        // the rejection stands on its own merits either way.)
3329        let key = "ssh-ed25519 AAAA|; rm -rf /etc user@host";
3330        assert!(matches!(
3331            validated_public_key(key),
3332            Err(ExecutorError::InvalidParam("public_key"))
3333        ));
3334    }
3335
3336    #[test]
3337    fn public_key_accepts_regex_metacharacters_so_consumers_must_not_use_regex() {
3338        // Deliberate and load-bearing: `.` is legal inside a key comment
3339        // (`alice@example.com`), so the validator cannot blocklist regex
3340        // metacharacters without rejecting valid keys. Any consumer that
3341        // interprets a key as a pattern is therefore the defect — see
3342        // `actions::ssh::REMOVE_KEY_SCRIPT`, which uses `grep -Fxv` for
3343        // exactly this reason.
3344        let key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample alice@example.com";
3345        assert!(validated_public_key(key).is_ok());
3346        // The wildcard-shaped payload passes validation too. It is safe only
3347        // because no consumer treats it as a pattern.
3348        assert!(validated_public_key("ssh-ed25519 .*").is_ok());
3349    }
3350
3351    #[test]
3352    fn public_key_rejects_shell_metacharacters() {
3353        for (metachar, desc) in [
3354            (';', "semicolon"),
3355            ('`', "backtick"),
3356            ('$', "dollar"),
3357            ('\\', "backslash"),
3358            ('&', "ampersand"),
3359        ] {
3360            let key = format!("ssh-ed25519 AAAA{metachar}injected user@host");
3361            assert!(
3362                matches!(
3363                    validated_public_key(&key),
3364                    Err(ExecutorError::InvalidParam("public_key"))
3365                ),
3366                "{desc} should be rejected"
3367            );
3368        }
3369    }
3370
3371    #[test]
3372    fn public_key_rejects_newline() {
3373        let key = "ssh-ed25519 AAAA\nmalicious: line user@host";
3374        assert!(matches!(
3375            validated_public_key(key),
3376            Err(ExecutorError::InvalidParam("public_key"))
3377        ));
3378        let key_cr = "ssh-ed25519 AAAA\rmalicious: line user@host";
3379        assert!(matches!(
3380            validated_public_key(key_cr),
3381            Err(ExecutorError::InvalidParam("public_key"))
3382        ));
3383    }
3384
3385    #[test]
3386    fn public_key_rejects_too_long() {
3387        // Build a key that exceeds MAX_LEN (8192 bytes)
3388        let long_payload = "A".repeat(8192);
3389        let key = format!("ssh-ed25519 {long_payload} user@host");
3390        assert!(matches!(
3391            validated_public_key(&key),
3392            Err(ExecutorError::InvalidParam("public_key"))
3393        ));
3394    }
3395
3396    // ── str_array_or_empty ────────────────────────────────────────────────
3397
3398    #[test]
3399    fn str_array_or_empty_rejects_non_string_element() {
3400        let params = json!({ "packages": ["vim", 42, "curl"] });
3401        assert!(matches!(
3402            str_array_or_empty(&params, "packages"),
3403            Err(ExecutorError::InvalidParam("packages"))
3404        ));
3405    }
3406
3407    #[test]
3408    fn str_array_or_empty_accepts_string_array() {
3409        let params = json!({ "packages": ["vim", "curl"] });
3410        assert_eq!(
3411            str_array_or_empty(&params, "packages").unwrap(),
3412            vec!["vim".to_string(), "curl".to_string()]
3413        );
3414    }
3415
3416    #[test]
3417    fn str_array_or_empty_returns_empty_when_key_absent() {
3418        let params = json!({});
3419        assert_eq!(
3420            str_array_or_empty(&params, "packages").unwrap(),
3421            Vec::<String>::new()
3422        );
3423    }
3424
3425    // ── validated_safe_kernel_arg ─────────────────────────────────────────
3426
3427    #[test]
3428    fn kernel_arg_allows_safe_args() {
3429        assert!(validated_safe_kernel_arg("quiet", "add").is_ok());
3430        assert!(validated_safe_kernel_arg("splash", "add").is_ok());
3431        assert!(validated_safe_kernel_arg("rd.driver.blacklist=nouveau", "add").is_ok());
3432        assert!(validated_safe_kernel_arg("console=ttyS0,115200", "add").is_ok());
3433    }
3434
3435    #[test]
3436    fn kernel_arg_blocks_init_override() {
3437        assert!(matches!(
3438            validated_safe_kernel_arg("init=/bin/sh", "add"),
3439            Err(ExecutorError::InvalidParam("add"))
3440        ));
3441        assert!(matches!(
3442            validated_safe_kernel_arg("INIT=/sbin/bash", "add"),
3443            Err(ExecutorError::InvalidParam("add"))
3444        ));
3445    }
3446
3447    #[test]
3448    fn kernel_arg_blocks_selinux_disable() {
3449        assert!(matches!(
3450            validated_safe_kernel_arg("selinux=0", "add"),
3451            Err(ExecutorError::InvalidParam("add"))
3452        ));
3453        assert!(matches!(
3454            validated_safe_kernel_arg("enforcing=0", "add"),
3455            Err(ExecutorError::InvalidParam("add"))
3456        ));
3457    }
3458
3459    #[test]
3460    fn kernel_arg_blocks_security_override() {
3461        assert!(matches!(
3462            validated_safe_kernel_arg("security=none", "add"),
3463            Err(ExecutorError::InvalidParam("add"))
3464        ));
3465    }
3466
3467    #[test]
3468    fn kernel_arg_blocks_module_blacklist() {
3469        assert!(matches!(
3470            validated_safe_kernel_arg("module_blacklist=dm_crypt", "add"),
3471            Err(ExecutorError::InvalidParam("add"))
3472        ));
3473    }
3474
3475    // ── validated_safe_kernel_arg_removal ─────────────────────────────────
3476    //
3477    // "Removing an argument is always safe" was the stated premise for exempting
3478    // `remove`/`delete` from any policy check. It is false: several arguments
3479    // protect the host by being PRESENT, so deleting one lands the same end state
3480    // as adding its weakening counterpart, which the add-path already refuses.
3481
3482    #[test]
3483    fn kernel_arg_removal_blocks_stripping_a_hardening_arg() {
3484        // KSPP-recommended boot parameters plus the LSM selectors. Each is a
3485        // protection the host loses the moment the token leaves the boot line.
3486        for arg in [
3487            "lockdown=confidentiality",
3488            "module.sig_enforce=1",
3489            "selinux=1",
3490            "enforcing=1",
3491            "apparmor=1",
3492            "security=selinux",
3493            "pti=on",
3494            "mitigations=auto,nosmt",
3495            "init_on_alloc=1",
3496            "init_on_free=1",
3497            "slab_nomerge",
3498            "page_alloc.shuffle=1",
3499            "randomize_kstack_offset=on",
3500            "slub_debug=FZP",
3501            "vsyscall=none",
3502            "debugfs=off",
3503            "iommu=force",
3504            "intel_iommu=on",
3505            "amd_iommu=force_isolation",
3506        ] {
3507            assert!(
3508                matches!(
3509                    validated_safe_kernel_arg_removal(arg, "remove"),
3510                    Err(ExecutorError::InvalidParam("remove"))
3511                ),
3512                "removing {arg} is a boot-security downgrade and must be refused"
3513            );
3514        }
3515    }
3516
3517    /// The screen must not turn into "no removals at all" — an argument that is
3518    /// itself a weakening (the add-path refuses it) has to stay removable, or
3519    /// SysKnife could never undo `mitigations=off` on a host that already has it.
3520    #[test]
3521    fn kernel_arg_removal_allows_undoing_a_weakening_arg() {
3522        for arg in [
3523            "mitigations=off",
3524            "selinux=0",
3525            "enforcing=0",
3526            "apparmor=0",
3527            "pti=off",
3528            "lockdown=none",
3529            "debugfs=on",
3530            "init=/bin/sh",
3531            "single",
3532        ] {
3533            assert!(
3534                validated_safe_kernel_arg_removal(arg, "remove").is_ok(),
3535                "{arg} weakens the host, so removing it must stay allowed"
3536            );
3537        }
3538    }
3539
3540    #[test]
3541    fn kernel_arg_removal_allows_ordinary_args() {
3542        for arg in [
3543            "quiet",
3544            "splash",
3545            "nomodeset",
3546            "console=ttyS0,115200",
3547            "rd.driver.blacklist=nouveau",
3548        ] {
3549            assert!(
3550                validated_safe_kernel_arg_removal(arg, "remove").is_ok(),
3551                "{arg} carries no boot-security meaning and must stay removable"
3552            );
3553        }
3554    }
3555
3556    #[test]
3557    fn kernel_arg_blocks_systemd_unit_emergency_rescue() {
3558        assert!(matches!(
3559            validated_safe_kernel_arg("systemd.unit=emergency.target", "add"),
3560            Err(ExecutorError::InvalidParam("add"))
3561        ));
3562        assert!(matches!(
3563            validated_safe_kernel_arg("systemd.unit=rescue.target", "add"),
3564            Err(ExecutorError::InvalidParam("add"))
3565        ));
3566        assert!(matches!(
3567            validated_safe_kernel_arg("systemd.unit=single.target", "add"),
3568            Err(ExecutorError::InvalidParam("add"))
3569        ));
3570    }
3571
3572    #[test]
3573    fn kernel_arg_blocks_apparmor_disable() {
3574        assert!(matches!(
3575            validated_safe_kernel_arg("apparmor=0", "add"),
3576            Err(ExecutorError::InvalidParam("add"))
3577        ));
3578    }
3579
3580    #[test]
3581    fn kernel_arg_blocks_mitigations_off() {
3582        assert!(matches!(
3583            validated_safe_kernel_arg("mitigations=off", "add"),
3584            Err(ExecutorError::InvalidParam("add"))
3585        ));
3586    }
3587
3588    #[test]
3589    fn kernel_arg_blocks_lockdown_override() {
3590        assert!(matches!(
3591            validated_safe_kernel_arg("lockdown=none", "add"),
3592            Err(ExecutorError::InvalidParam("add"))
3593        ));
3594    }
3595
3596    #[test]
3597    fn kernel_arg_blocks_pti_off() {
3598        assert!(matches!(
3599            validated_safe_kernel_arg("pti=off", "add"),
3600            Err(ExecutorError::InvalidParam("add"))
3601        ));
3602    }
3603
3604    #[test]
3605    fn kernel_arg_blocks_smap_smep_disable() {
3606        assert!(matches!(
3607            validated_safe_kernel_arg("nosmap", "add"),
3608            Err(ExecutorError::InvalidParam("add"))
3609        ));
3610        assert!(matches!(
3611            validated_safe_kernel_arg("nosmep", "add"),
3612            Err(ExecutorError::InvalidParam("add"))
3613        ));
3614    }
3615
3616    #[test]
3617    fn kernel_arg_blocks_single_user_shortcuts() {
3618        // Runlevel shortcuts that drop to a root shell.
3619        assert!(matches!(
3620            validated_safe_kernel_arg("single", "add"),
3621            Err(ExecutorError::InvalidParam("add"))
3622        ));
3623        assert!(matches!(
3624            validated_safe_kernel_arg("s", "add"),
3625            Err(ExecutorError::InvalidParam("add"))
3626        ));
3627        assert!(matches!(
3628            validated_safe_kernel_arg("1", "add"),
3629            Err(ExecutorError::InvalidParam("add"))
3630        ));
3631    }
3632
3633    #[test]
3634    fn signal_process_guardrails() {
3635        // Reject pid 0 (whole process group) and 1 (init/systemd).
3636        for bad_pid in [0, 1] {
3637            let err = build_action_spec("SignalProcess", &json!({ "pid": bad_pid })).unwrap_err();
3638            assert!(
3639                matches!(err, ExecutorError::InvalidParam("pid")),
3640                "pid {bad_pid} must be rejected, got {err:?}"
3641            );
3642        }
3643        // Reject a signal outside the allowlist.
3644        let err = build_action_spec("SignalProcess", &json!({ "pid": 4242, "signal": "STOP" }))
3645            .unwrap_err();
3646        assert!(
3647            matches!(err, ExecutorError::InvalidParam("signal")),
3648            "got {err:?}"
3649        );
3650        // Missing pid is a MissingParam.
3651        assert!(matches!(
3652            build_action_spec("SignalProcess", &json!({})).unwrap_err(),
3653            ExecutorError::MissingParam("pid")
3654        ));
3655        // A valid pid + signal builds, and accepts a numeric string + SIG prefix.
3656        let spec = build_action_spec(
3657            "SignalProcess",
3658            &json!({ "pid": "4242", "signal": "sigkill" }),
3659        )
3660        .unwrap();
3661        assert_eq!(spec.action_name, "SignalProcess");
3662        assert_eq!(
3663            spec.mechanism,
3664            ActionMechanism::Command {
3665                program: "sudo",
3666                args: vec![
3667                    "kill".to_string(),
3668                    "-s".to_string(),
3669                    "KILL".to_string(),
3670                    "4242".to_string()
3671                ],
3672            }
3673        );
3674        // Default signal is TERM when omitted.
3675        let spec = build_action_spec("SignalProcess", &json!({ "pid": 4242 })).unwrap();
3676        if let ActionMechanism::Command { args, .. } = spec.mechanism {
3677            assert_eq!(args, vec!["kill", "-s", "TERM", "4242"]);
3678        } else {
3679            panic!("expected Command mechanism");
3680        }
3681    }
3682
3683    #[test]
3684    fn create_scheduled_job_validates_name_command_schedule() {
3685        // A newline in the command would inject extra unit directives.
3686        assert!(matches!(
3687            build_action_spec(
3688                "CreateScheduledJob",
3689                &json!({ "name": "backup", "command": "/bin/true\nExecStartPre=/evil", "schedule": "daily" })
3690            )
3691            .unwrap_err(),
3692            ExecutorError::InvalidParam("command")
3693        ));
3694        // A path-like / dotted name is rejected (must be a safe unit stem).
3695        assert!(matches!(
3696            build_action_spec(
3697                "CreateScheduledJob",
3698                &json!({ "name": "../evil", "command": "/bin/true", "schedule": "daily" })
3699            )
3700            .unwrap_err(),
3701            ExecutorError::InvalidParam("name")
3702        ));
3703        // A schedule with shell metacharacters is rejected by the charset gate.
3704        assert!(matches!(
3705            build_action_spec(
3706                "CreateScheduledJob",
3707                &json!({ "name": "backup", "command": "/bin/true", "schedule": "daily; rm -rf /" })
3708            )
3709            .unwrap_err(),
3710            ExecutorError::InvalidParam("schedule")
3711        ));
3712        // A valid job routes through the scoped helper with the right argv.
3713        let spec = build_action_spec(
3714            "CreateScheduledJob",
3715            &json!({ "name": "nightly-backup", "command": "/usr/bin/backup --full", "schedule": "*-*-* 02:00:00" }),
3716        )
3717        .unwrap();
3718        assert_eq!(
3719            spec.mechanism,
3720            ActionMechanism::Command {
3721                program: "sudo",
3722                args: vec![
3723                    "/usr/lib/sysknife/scheduled-job-edit".to_string(),
3724                    "--name".to_string(),
3725                    "nightly-backup".to_string(),
3726                    "--command".to_string(),
3727                    "/usr/bin/backup --full".to_string(),
3728                    "--schedule".to_string(),
3729                    "*-*-* 02:00:00".to_string(),
3730                ],
3731            }
3732        );
3733    }
3734
3735    #[test]
3736    fn set_sshd_option_allowlist_guardrails() {
3737        // Non-allowlisted option rejected.
3738        assert!(matches!(
3739            build_action_spec(
3740                "SetSshdOption",
3741                &json!({ "option": "Ciphers", "value": "aes256-gcm@openssh.com" })
3742            )
3743            .unwrap_err(),
3744            ExecutorError::InvalidParam("option")
3745        ));
3746        // Allowlisted option, disallowed value.
3747        assert!(matches!(
3748            build_action_spec(
3749                "SetSshdOption",
3750                &json!({ "option": "PermitRootLogin", "value": "maybe" })
3751            )
3752            .unwrap_err(),
3753            ExecutorError::InvalidParam("value")
3754        ));
3755        // Valid combo routes through the scoped helper.
3756        let spec = build_action_spec(
3757            "SetSshdOption",
3758            &json!({ "option": "PasswordAuthentication", "value": "no" }),
3759        )
3760        .unwrap();
3761        assert_eq!(
3762            spec.mechanism,
3763            ActionMechanism::Command {
3764                program: "sudo",
3765                args: vec![
3766                    "/usr/lib/sysknife/sshd-option-edit".to_string(),
3767                    "--option".to_string(),
3768                    "PasswordAuthentication".to_string(),
3769                    "--value".to_string(),
3770                    "no".to_string(),
3771                ],
3772            }
3773        );
3774    }
3775
3776    #[test]
3777    fn configure_unattended_upgrades_toggles_helper_flag() {
3778        for (enabled, flag) in [(true, "--enable"), (false, "--disable")] {
3779            let spec = build_action_spec(
3780                "ConfigureUnattendedUpgrades",
3781                &json!({ "enabled": enabled }),
3782            )
3783            .unwrap();
3784            assert_eq!(
3785                spec.mechanism,
3786                ActionMechanism::Command {
3787                    program: "sudo",
3788                    args: vec![
3789                        "/usr/lib/sysknife/unattended-upgrades-edit".to_string(),
3790                        flag.to_string(),
3791                    ],
3792                }
3793            );
3794        }
3795        assert!(matches!(
3796            build_action_spec("ConfigureUnattendedUpgrades", &json!({})).unwrap_err(),
3797            ExecutorError::MissingParam("enabled")
3798        ));
3799    }
3800
3801    #[test]
3802    fn grub_set_kargs_append_blocks_single_user_shortcut() {
3803        // Regression: GrubSetKargs previously used only the charset validator,
3804        // which accepts the bare `single`/`s`/`1` runlevel shortcuts. The
3805        // kernel-arg denylist must apply to `append` too — booting into a
3806        // single-user root shell is exactly the SetKernelArguments threat.
3807        // Every BLOCKED_EXACT entry is valueless, so it passes the charset
3808        // check and this denylist call is the only thing stopping it — the
3809        // call is load-bearing here, not redundant with `validated_safe_arg`.
3810        for dangerous in ["single", "s", "1", "nosmap", "nosmep"] {
3811            let err = build_action_spec(
3812                "GrubSetKargs",
3813                &json!({ "append": [dangerous], "delete": [] }),
3814            )
3815            .unwrap_err();
3816            assert!(
3817                matches!(err, ExecutorError::InvalidParam("append")),
3818                "GrubSetKargs must reject append=[{dangerous:?}] via the denylist, got {err:?}"
3819            );
3820        }
3821        // A benign flag still builds successfully.
3822        assert!(build_action_spec(
3823            "GrubSetKargs",
3824            &json!({ "append": ["quiet"], "delete": [] })
3825        )
3826        .is_ok());
3827    }
3828
3829    #[test]
3830    fn kernel_arg_build_spec_rejects_dangerous_arg() {
3831        // End-to-end: build_action_spec must propagate the blocklist error.
3832        // This action does NOT apply the `validated_safe_arg` charset check,
3833        // so `init=/bin/bash` reaches `validated_safe_kernel_arg` and is
3834        // caught by BLOCKED_PREFIXES — the `=`-bearing half of that denylist
3835        // is live here even though GrubSetKargs never reaches it.
3836        let err = build_action_spec(
3837            "SetKernelArguments",
3838            &json!({ "add": ["init=/bin/bash"], "remove": [] }),
3839        )
3840        .unwrap_err();
3841        assert!(
3842            matches!(err, ExecutorError::InvalidParam("add")),
3843            "expected InvalidParam(add), got {err:?}"
3844        );
3845    }
3846
3847    #[test]
3848    fn grub_set_kargs_cannot_delete_a_protective_karg() {
3849        // A review flagged `delete: ["apparmor=1"]` as a way to strip AppArmor
3850        // because the kernel-arg denylist is not applied to `delete`. It is
3851        // not reachable: `delete` goes through `validated_safe_arg`, whose
3852        // charset excludes `=`, so any `key=value` token is refused before the
3853        // denylist would matter. Pinned here so a future widening of that
3854        // charset cannot silently open the hole.
3855        for karg in [
3856            "apparmor=1",
3857            "lockdown=confidentiality",
3858            "mitigations=auto",
3859            "pti=on",
3860            "selinux=1",
3861        ] {
3862            let err = build_action_spec("GrubSetKargs", &json!({ "append": [], "delete": [karg] }))
3863                .unwrap_err();
3864            assert!(
3865                matches!(err, ExecutorError::InvalidParam("delete")),
3866                "deleting {karg:?} must be refused, got {err:?}"
3867            );
3868        }
3869    }
3870
3871    /// Every action that claims `rollback_available: true` MUST have a
3872    /// corresponding entry in `rollback_spec_for()`; every action that claims
3873    /// `false` MUST NOT. This prevents the spec and the executor from
3874    /// drifting apart.
3875    #[test]
3876    fn rollback_available_matches_rollback_spec_for_all_actions() {
3877        // Iterate the FULL catalogue (`crate::actions::all_specs`), not a
3878        // hand-picked subset of families — a manually-chained list here once
3879        // silently omitted `ppa`, `netplan`, `grub`, and `ubuntu_pro`, which is
3880        // exactly how `AddPpa`/`RemovePpa`/`NetplanSet`/`GrubSetKargs`/
3881        // `ProAttach`/`ProDetach` were able to claim `rollback_available: true`
3882        // with no matching `rollback_spec_for` entry for years without this
3883        // test catching it.
3884        for spec in crate::actions::all_specs() {
3885            let has_rollback = rollback_spec_for(spec.action_name).is_some();
3886            assert_eq!(
3887                spec.rollback_available,
3888                has_rollback,
3889                "action {:?}: rollback_available={} but rollback_spec_for returns {}",
3890                spec.action_name,
3891                spec.rollback_available,
3892                if has_rollback { "Some" } else { "None" },
3893            );
3894        }
3895    }
3896
3897    // ── Risk level reclassification (NIST 800-53 / CIS Controls v8.1) ────────
3898    // These five actions were incorrectly classified Medium; they must be High.
3899    // T1136.001 (CreateUser), T1562.004 (ConfigureFirewall), T1562.001 (MaskService),
3900    // supply-chain vector (AddPackageRepository), T1557 path (SetDnsServers).
3901
3902    #[test]
3903    fn create_user_is_high_risk() {
3904        let spec = build_action_spec("CreateUser", &json!({ "username": "alice" })).unwrap();
3905        assert_eq!(
3906            spec.risk_level,
3907            RiskLevel::High,
3908            "CreateUser must be High (T1136.001 Persistence)"
3909        );
3910    }
3911
3912    #[test]
3913    fn configure_firewall_is_high_risk() {
3914        let spec = build_action_spec(
3915            "ConfigureFirewall",
3916            &json!({ "zone": "public", "service": "ssh", "enabled": true }),
3917        )
3918        .unwrap();
3919        assert_eq!(
3920            spec.risk_level,
3921            RiskLevel::High,
3922            "ConfigureFirewall must be High (T1562.004 Defense Evasion)"
3923        );
3924    }
3925
3926    #[test]
3927    fn mask_service_is_high_risk() {
3928        let spec = build_action_spec("MaskService", &json!({ "unit": "auditd.service" })).unwrap();
3929        assert_eq!(
3930            spec.risk_level,
3931            RiskLevel::High,
3932            "MaskService must be High (T1562.001 Impair Defenses)"
3933        );
3934    }
3935
3936    #[test]
3937    fn add_package_repository_is_high_risk() {
3938        let spec = build_action_spec(
3939            "AddPackageRepository",
3940            &json!({ "repo_id": "my-repo", "repo_url": "https://ok.example/repo" }),
3941        )
3942        .unwrap();
3943        assert_eq!(
3944            spec.risk_level,
3945            RiskLevel::High,
3946            "AddPackageRepository must be High (supply-chain vector)"
3947        );
3948    }
3949
3950    #[test]
3951    fn set_dns_servers_is_high_risk() {
3952        let spec = build_action_spec(
3953            "SetDnsServers",
3954            &json!({ "interface": "eth0", "servers": ["8.8.8.8"] }),
3955        )
3956        .unwrap();
3957        assert_eq!(
3958            spec.risk_level,
3959            RiskLevel::High,
3960            "SetDnsServers must be High (DNS hijacking / T1557)"
3961        );
3962    }
3963}