sysknife-cli 0.22.0

Approval-gated AI system administration CLI and MCP server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Distro-family routing guard for action names.
//!
//! Some actions in the SysKnife catalogue are distro-specific — they are only
//! meaningful on a particular package-manager family:
//!
//! - apt/dpkg and Debian's GRUB interface require a Debian-family distro.
//! - Ubuntu services, PPAs and the reboot sentinel require Ubuntu itself.
//! - Installable tools such as snap, ufw and netplan are planner preferences.
//! - rpm-ostree shaped actions (`RebaseSystem`, `AddLayeredPackage`, …) require
//!   a Fedora-family distro.
//!
//! [`check_action_distro`] returns a human-readable error when a plan step's
//! action name is incompatible with the detected distro.  It is called after
//! planning, before execution, so the user sees a clear message instead of a
//! cryptic daemon error.

use sysknife_core::distro::{DistroFamily, DistroId};

// ---------------------------------------------------------------------------
// Action families
// ---------------------------------------------------------------------------

// The canonical family lists are the single source of truth in
// `sysknife-core::action_family`; the daemon fence, this routing guard, and the
// brain prompt all reference the same constants so they cannot drift apart.
use sysknife_core::action_family::{
    action_matches_distro, action_requires_supported_host, DEBIAN_ONLY_ACTIONS,
    FEDORA_ONLY_ACTIONS, UBUNTU_ONLY_ACTIONS,
};

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Check whether `action_name` is compatible with `distro`.
///
/// Returns `Ok(())` when the action is generic (valid on all distros), or when
/// the action's required family matches `distro`'s family.
///
/// Returns `Err(String)` with a human-readable routing error when the action
/// is family-restricted and `distro` is from the wrong family.
///
/// When `distro` is `None` (detection failed), all actions are allowed — the
/// daemon will surface the real error at execution time.
pub fn check_action_distro(action_name: &str, distro: Option<&DistroId>) -> Result<(), String> {
    let distro = match distro {
        Some(d) => d,
        None => return Ok(()), // detection failed; let daemon handle it
    };

    let family = distro.family();
    if UBUNTU_ONLY_ACTIONS.contains(&action_name) && !action_matches_distro(action_name, distro) {
        return Err(format!(
            "{action_name} requires Ubuntu itself; current distro is {distro}"
        ));
    }
    if DEBIAN_ONLY_ACTIONS.contains(&action_name) && family != DistroFamily::Debian {
        return Err(format!(
            "{action_name} is only valid on Debian-family distros (apt/dpkg/GRUB); \
             current distro is {distro} ({family_name})",
            family_name = family_label(&family),
        ));
    }

    if FEDORA_ONLY_ACTIONS.contains(&action_name) && family != DistroFamily::Fedora {
        return Err(format!(
            "{action_name} is only valid on Fedora-family distros (rpm-ostree/dnf); \
             current distro is {distro} ({family_name})",
            family_name = family_label(&family),
        ));
    }

    // Host eligibility is wider than mechanism compatibility: portable tools
    // still cannot mutate an unsupported host. Conservatively withhold the
    // entire distro-policy set here, including its reads, before approval.
    if action_requires_supported_host(action_name) && !distro.is_supported() {
        return Err(format!(
            "{action_name} is disabled on unsupported distro {distro}; \
             see docs/distro-support.md"
        ));
    }

    Ok(())
}

fn family_label(f: &DistroFamily) -> &'static str {
    match f {
        DistroFamily::Fedora => "Fedora family",
        DistroFamily::Debian => "Debian family",
        DistroFamily::Other => "unknown family",
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use sysknife_core::distro::DistroId;

    // -----------------------------------------------------------------------
    // Fedora routing
    // -----------------------------------------------------------------------

    #[test]
    fn apt_install_on_fedora_returns_error() {
        let distro = DistroId::Fedora { version: 41 };
        let result = check_action_distro("AptInstall", Some(&distro));
        assert!(result.is_err());
        let msg = result.unwrap_err();
        assert!(
            msg.contains("Debian-family"),
            "error must mention Debian-family; got: {msg}"
        );
        assert!(
            msg.contains("Fedora 41"),
            "error must mention current distro; got: {msg}"
        );
    }

    #[test]
    fn snap_install_on_fedora_silverblue_is_not_hard_fenced() {
        let distro = DistroId::FedoraSilverblue { version: 41 };
        let result = check_action_distro("SnapInstall", Some(&distro));
        assert!(result.is_ok());
    }

    #[test]
    fn ufw_allow_on_fedora_is_not_hard_fenced() {
        let distro = DistroId::FedoraSilverblue { version: 41 };
        let result = check_action_distro("UfwAllow", Some(&distro));
        assert!(result.is_ok());
    }

    #[test]
    fn netplan_apply_on_fedora_is_not_hard_fenced() {
        let distro = DistroId::FedoraSilverblue { version: 41 };
        let result = check_action_distro("NetplanApply", Some(&distro));
        assert!(result.is_ok());
    }

    #[test]
    fn distrobox_create_on_fedora_is_not_hard_fenced() {
        let distro = DistroId::FedoraSilverblue { version: 41 };
        let result = check_action_distro("DistroboxCreate", Some(&distro));
        assert!(result.is_ok());
    }

    // -----------------------------------------------------------------------
    // Ubuntu routing
    // -----------------------------------------------------------------------

    #[test]
    fn apt_install_on_ubuntu_is_ok() {
        let distro = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        assert!(check_action_distro("AptInstall", Some(&distro)).is_ok());
    }

    #[test]
    fn apt_install_on_ubuntu_core_is_rejected() {
        let distro = DistroId::UbuntuCore {
            major: 24,
            minor: 4,
        };
        assert!(check_action_distro("AptInstall", Some(&distro)).is_err());
    }

    #[test]
    fn apt_install_on_unsupported_ubuntu_release_is_rejected() {
        // 18.04 is below the support floor: no longer receiving Ubuntu security
        // updates, so the routing guard still refuses it.
        let distro = DistroId::Ubuntu {
            major: 18,
            minor: 4,
        };
        assert!(check_action_distro("AptInstall", Some(&distro)).is_err());
    }

    #[test]
    fn apt_install_is_allowed_on_every_supported_ubuntu_release() {
        // The counterpart to the test above: interim releases and 20.04 are
        // supported, so routing must not treat the LTS cadence as a gate.
        for (major, minor) in [(20, 4), (22, 4), (24, 4), (25, 10), (26, 4), (26, 10)] {
            let distro = DistroId::Ubuntu { major, minor };
            assert!(
                check_action_distro("AptInstall", Some(&distro)).is_ok(),
                "AptInstall must route on Ubuntu {major}.{minor:02}"
            );
        }
    }

    #[test]
    fn portable_tools_require_supported_hosts_before_approval() {
        // Literal cases pin both portable families independently of the lists
        // being split. A supported host may use its non-default tools.
        for action in [
            "SnapInstall",
            "UfwEnable",
            "UfwAllow",
            "UfwLimit",
            "AppArmorEnforce",
            "Fail2banBanIp",
            "ConfigureFail2banJail",
            "ConfigureFirewall",
            "CreateToolbox",
            "AptUpdate",
        ] {
            for distro in [
                DistroId::Debian { version: Some(11) },
                DistroId::Debian { version: None },
                DistroId::Ubuntu {
                    major: 18,
                    minor: 4,
                },
                DistroId::Fedora { version: 41 },
                DistroId::Other {
                    id: "arch".into(),
                    version_id: None,
                    id_like: vec![],
                },
            ] {
                assert!(
                    check_action_distro(action, Some(&distro)).is_err(),
                    "{action} must be refused before approval on {distro}"
                );
            }
            for distro in [
                DistroId::Debian { version: Some(12) },
                DistroId::Debian { version: Some(13) },
                DistroId::Ubuntu {
                    major: 24,
                    minor: 4,
                },
                DistroId::FedoraSilverblue { version: 41 },
            ] {
                if action != "AptUpdate" || matches!(distro, DistroId::Debian { .. }) {
                    assert!(
                        check_action_distro(action, Some(&distro)).is_ok(),
                        "portable {action} must remain usable on {distro}"
                    );
                }
            }
        }
    }

    #[test]
    fn rebase_system_on_ubuntu_returns_error() {
        let distro = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        let result = check_action_distro("RebaseSystem", Some(&distro));
        assert!(result.is_err());
        let msg = result.unwrap_err();
        assert!(msg.contains("Fedora-family"), "got: {msg}");
        assert!(msg.contains("Ubuntu 24.04"), "got: {msg}");
    }

    #[test]
    fn add_layered_package_on_ubuntu_returns_error() {
        let distro = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        let result = check_action_distro("AddLayeredPackage", Some(&distro));
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // UnknownDistro / None passes through
    // -----------------------------------------------------------------------

    #[test]
    fn no_distro_allows_all_actions() {
        // When detection failed, we must not block execution.
        assert!(check_action_distro("AptInstall", None).is_ok());
        assert!(check_action_distro("RebaseSystem", None).is_ok());
        assert!(check_action_distro("GetSystemState", None).is_ok());
    }

    // -----------------------------------------------------------------------
    // Generic actions are allowed everywhere
    // -----------------------------------------------------------------------

    /// Silverblue, not plain Fedora: `GetSystemState` runs `rpm-ostree status`,
    /// which a dnf-based Fedora Workstation does not have — and plain Fedora is
    /// `is_supported() == false` besides. The old fixture used `Fedora`, so it
    /// asserted an rpm-ostree action was fine on a host without rpm-ostree.
    #[test]
    fn get_system_state_allowed_on_fedora_atomic() {
        let distro = DistroId::FedoraSilverblue { version: 41 };
        assert!(check_action_distro("GetSystemState", Some(&distro)).is_ok());
    }

    /// This pair used to assert that `GetSystemState` was "generic, allowed
    /// everywhere". It is not: it runs `rpm-ostree status --json`, so on an apt
    /// host it failed with `command not found` — *after* the operator had
    /// approved it. The routing guard now refuses it up front, and `GetHostState`
    /// is what Ubuntu answers the same question with (#181).
    #[test]
    fn get_system_state_is_refused_on_ubuntu_before_approval() {
        let distro = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        assert!(
            check_action_distro("GetSystemState", Some(&distro)).is_err(),
            "an rpm-ostree action must not reach an apt host's approval prompt"
        );
    }

    #[test]
    fn get_host_state_is_the_ubuntu_counterpart() {
        let ubuntu = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        assert!(check_action_distro("GetHostState", Some(&ubuntu)).is_ok());

        let fedora = DistroId::FedoraSilverblue { version: 41 };
        assert!(
            check_action_distro("GetHostState", Some(&fedora)).is_ok(),
            "hostnamectl is portable even when Fedora prefers deployment state"
        );
    }

    #[test]
    fn install_flatpak_allowed_on_fedora() {
        let distro = DistroId::Fedora { version: 41 };
        assert!(check_action_distro("InstallFlatpak", Some(&distro)).is_ok());
    }

    #[test]
    fn install_flatpak_allowed_on_ubuntu() {
        let distro = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        assert!(check_action_distro("InstallFlatpak", Some(&distro)).is_ok());
    }

    // -----------------------------------------------------------------------
    // All Debian-only actions reject Fedora
    // -----------------------------------------------------------------------

    #[test]
    fn all_debian_only_actions_rejected_on_fedora() {
        let distro = DistroId::Fedora { version: 41 };
        for action in super::DEBIAN_ONLY_ACTIONS {
            let result = check_action_distro(action, Some(&distro));
            assert!(
                result.is_err(),
                "{action} should be rejected on Fedora but was allowed"
            );
        }
    }

    #[test]
    fn ubuntu_only_actions_require_identity_and_eligibility() {
        let ubuntu = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        for action in UBUNTU_ONLY_ACTIONS {
            assert!(
                check_action_distro(action, Some(&ubuntu)).is_ok(),
                "{action}"
            );
            for distro in [
                DistroId::Debian { version: Some(13) },
                DistroId::FedoraSilverblue { version: 41 },
                DistroId::UbuntuCore {
                    major: 24,
                    minor: 4,
                },
                DistroId::Ubuntu {
                    major: 18,
                    minor: 4,
                },
            ] {
                assert!(
                    check_action_distro(action, Some(&distro)).is_err(),
                    "{action} on {distro}"
                );
            }
        }
    }

    #[test]
    fn all_fedora_only_actions_rejected_on_ubuntu() {
        let distro = DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        for action in super::FEDORA_ONLY_ACTIONS {
            let result = check_action_distro(action, Some(&distro));
            assert!(
                result.is_err(),
                "{action} should be rejected on Ubuntu but was allowed"
            );
        }
    }

    // -----------------------------------------------------------------------
    // Display impl for DistroId
    // -----------------------------------------------------------------------

    #[test]
    fn distro_id_display_fedora() {
        assert_eq!(format!("{}", DistroId::Fedora { version: 41 }), "Fedora 41");
    }

    #[test]
    fn distro_id_display_fedora_silverblue() {
        assert_eq!(
            format!("{}", DistroId::FedoraSilverblue { version: 41 }),
            "FedoraSilverblue 41"
        );
    }

    #[test]
    fn distro_id_display_ubuntu() {
        assert_eq!(
            format!(
                "{}",
                DistroId::Ubuntu {
                    major: 24,
                    minor: 4
                }
            ),
            "Ubuntu 24.04"
        );
    }

    #[test]
    fn distro_id_display_debian() {
        assert_eq!(
            format!("{}", DistroId::Debian { version: Some(12) }),
            "Debian 12"
        );
    }
}