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