sysknife-daemon 0.21.0

Policy-enforced, audit-logged Linux action daemon for SysKnife
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use serde::{Deserialize, Serialize};
use std::io;

/// Snapshot of live system state collected by the daemon.
///
/// Field names mirror `sysknife_brain::CuratedState` so the shell can deserialize
/// the JSON representation without depending on this crate.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CollectedState {
    pub host_name: String,
    pub deployment: String,
    pub services: Vec<String>,
    pub flatpaks: Vec<String>,
    pub toolboxes: Vec<String>,
    pub layered_packages: Vec<String>,
    pub containers: Vec<String>,
    pub users: Vec<String>,
    /// A stable per-machine identity a client can compare against its own, so
    /// `audit verify` can tell whether the daemon it talked to is this machine or
    /// a forwarded/remote one (#146). It is a salted hash of `/etc/machine-id`,
    /// never the raw id (systemd treats the raw machine-id as confidential and
    /// warns against exposing it). `None` when `/etc/machine-id` is unreadable.
    #[serde(default)]
    pub machine_id_hash: Option<String>,
}

/// Domain-separated hash of the local `/etc/machine-id`, or `None` if it cannot
/// be read. Both the daemon (here) and the client compute this the same way, so
/// equal hashes mean the same machine without either side revealing the raw id.
pub fn machine_id_hash() -> Option<String> {
    let raw = std::fs::read_to_string("/etc/machine-id").ok()?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(hash_machine_id(trimmed))
}

/// The exact hashing both sides must agree on. Split out so it can be tested
/// deterministically without depending on the host's `/etc/machine-id`.
pub fn hash_machine_id(machine_id: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(b"sysknife-machine-id-v1\0");
    hasher.update(machine_id.as_bytes());
    hex::encode(hasher.finalize())
}

#[derive(Debug, thiserror::Error)]
pub enum CollectorError {
    #[error("command failed for {command}: {reason}")]
    CommandFailed {
        command: &'static str,
        reason: String,
    },
}

/// Abstraction over command execution, making state collection testable
/// without requiring system tools to be installed.
pub trait CommandRunner: Send + Sync {
    fn run(&self, program: &str, args: &[&str]) -> Result<String, io::Error>;
}

/// Production implementation that delegates to `std::process::Command`.
pub struct RealCommandRunner;

impl CommandRunner for RealCommandRunner {
    fn run(&self, program: &str, args: &[&str]) -> Result<String, io::Error> {
        let output = std::process::Command::new(program).args(args).output()?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(io::Error::other(format!(
                "{} exited with status {}: {}",
                program,
                output.status,
                stderr.trim()
            )));
        }
        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
    }
}

/// Run a best-effort state probe, returning the parsed value or its default.
///
/// A missing binary (`NotFound`) is expected on distros that don't ship the
/// tool (e.g. `rpm-ostree`/`toolbox` on Ubuntu), so it stays quiet. Any other
/// error means the tool exists but the probe broke — log it (instead of
/// silently swallowing) so an operator can tell "genuinely empty" from
/// "collection failed".
fn probe_or_warn<T: Default>(
    label: &str,
    result: Result<String, io::Error>,
    parse: impl FnOnce(&str) -> T,
) -> T {
    match result {
        Ok(s) => parse(&s),
        Err(e) => {
            if e.kind() != io::ErrorKind::NotFound {
                eprintln!("[sysknife-daemon] state: {label} probe failed ({e}); reporting empty");
            }
            T::default()
        }
    }
}

/// Collect a system state snapshot using the provided runner.
///
/// Only `host_name` is required. All other fields (`deployment`, `services`,
/// `flatpaks`, `toolboxes`) are best-effort and default to empty on failure so
/// the daemon works on non-Silverblue systems and in CI. The brain's safety
/// fence will reject irrelevant actions based on the curated state it receives.
pub fn collect_state(runner: &dyn CommandRunner) -> Result<CollectedState, CollectorError> {
    let host_name = runner
        .run("hostname", &[])
        .map(|s| s.trim().to_string())
        .map_err(|e| CollectorError::CommandFailed {
            command: "hostname",
            reason: e.to_string(),
        })?;

    // Call rpm-ostree once and reuse for both deployment and layered_packages.
    let rpm_ostree_output = probe_or_warn(
        "rpm-ostree",
        runner.run("rpm-ostree", &["status", "--booted", "--json"]),
        |s| s.trim().to_string(),
    );

    let deployment = parse_deployment_summary(&rpm_ostree_output);
    let layered_packages = parse_layered_packages(&rpm_ostree_output);

    let services = probe_or_warn(
        "systemctl",
        runner.run(
            "systemctl",
            &[
                "list-units",
                "--type=service",
                "--state=running",
                "--no-legend",
                "--no-pager",
                "--plain",
            ],
        ),
        parse_service_lines,
    );

    let flatpaks = probe_or_warn(
        "flatpak",
        runner.run("flatpak", &["list", "--columns=application"]),
        parse_lines,
    );

    let toolboxes = probe_or_warn(
        "toolbox",
        runner.run("toolbox", &["list", "--containers"]),
        parse_lines,
    );

    let containers = probe_or_warn(
        "podman",
        runner.run("podman", &["ps", "--format", "{{.Names}}"]),
        parse_lines,
    );

    let users = probe_or_warn(
        "getent",
        runner.run("getent", &["passwd", "--service", "files"]),
        parse_local_users,
    );

    Ok(CollectedState {
        host_name,
        deployment,
        services,
        flatpaks,
        toolboxes,
        layered_packages,
        containers,
        users,
        machine_id_hash: machine_id_hash(),
    })
}

/// Extract the first whitespace-delimited field from each non-empty line.
/// Suitable for systemctl's columnar output where the first field is the unit name.
fn parse_service_lines(output: &str) -> Vec<String> {
    output
        .lines()
        .filter_map(|l| l.split_whitespace().next())
        .map(String::from)
        .collect()
}

/// Return non-empty trimmed lines from command output.
fn parse_lines(output: &str) -> Vec<String> {
    output
        .lines()
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
        .collect()
}

/// Parse the booted deployment from `rpm-ostree status --booted --json` into a
/// human-readable summary like `"fedora/41/x86_64/silverblue (booted, v41.20260401.0)"`.
///
/// Returns `""` if parsing fails or the input is not valid JSON.
fn parse_deployment_summary(json_output: &str) -> String {
    let Ok(val) = serde_json::from_str::<serde_json::Value>(json_output) else {
        return String::new();
    };
    let booted = val
        .get("deployments")
        .and_then(|v| v.as_array())
        .and_then(|arr| arr.first());
    let Some(dep) = booted else {
        return String::new();
    };
    let origin = dep
        .get("origin")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");
    let is_booted = dep.get("booted").and_then(|v| v.as_bool()).unwrap_or(false);
    let version = dep.get("version").and_then(|v| v.as_str());

    let mut summary = origin.to_string();
    let mut tags = Vec::new();
    if is_booted {
        tags.push("booted".to_string());
    }
    if let Some(v) = version {
        tags.push(format!("v{v}"));
    }
    if !tags.is_empty() {
        summary.push_str(&format!(" ({})", tags.join(", ")));
    }
    summary
}

/// Extract layered package names from `rpm-ostree status --booted --json`.
///
/// The JSON contains `deployments[0].requested-packages` (user-requested layers)
/// and optionally `requested-local-packages`. We merge both lists.
fn parse_layered_packages(json_output: &str) -> Vec<String> {
    let Ok(val) = serde_json::from_str::<serde_json::Value>(json_output) else {
        return Vec::new();
    };
    let deployments = match val.get("deployments").and_then(|v| v.as_array()) {
        Some(arr) => arr,
        None => return Vec::new(),
    };
    let Some(booted) = deployments.first() else {
        return Vec::new();
    };
    let mut pkgs = Vec::new();
    for key in &["requested-packages", "requested-local-packages"] {
        if let Some(arr) = booted.get(*key).and_then(|v| v.as_array()) {
            for item in arr {
                if let Some(s) = item.as_str() {
                    if !s.is_empty() {
                        pkgs.push(s.to_string());
                    }
                }
            }
        }
    }
    pkgs
}

/// Extract local human users from `getent passwd` output.
///
/// Filters to uid >= 1000, excludes `nobody` and `nfsnobody`, and excludes
/// accounts whose login shell ends with `nologin` or `/false`.
fn parse_local_users(output: &str) -> Vec<String> {
    output
        .lines()
        .filter_map(|line| {
            let fields: Vec<&str> = line.split(':').collect();
            // passwd format: name:pwd:uid:gid:gecos:home:shell (7 fields)
            if fields.len() < 7 {
                return None;
            }
            let username = fields[0];
            let uid: u32 = fields[2].parse().ok()?;
            let shell = fields[6];
            if uid >= 1000
                && username != "nobody"
                && username != "nfsnobody"
                && !shell.ends_with("nologin")
                && !shell.ends_with("/false")
            {
                Some(username.to_string())
            } else {
                None
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    struct MockRunner {
        responses: HashMap<String, String>,
    }

    impl MockRunner {
        fn new(entries: &[(&str, &[&str], &str)]) -> Self {
            let responses = entries
                .iter()
                .map(|(program, args, output)| {
                    let key = std::iter::once(*program)
                        .chain(args.iter().copied())
                        .collect::<Vec<_>>()
                        .join(" ");
                    (key, output.to_string())
                })
                .collect();
            Self { responses }
        }
    }

    impl CommandRunner for MockRunner {
        fn run(&self, program: &str, args: &[&str]) -> Result<String, io::Error> {
            let key = std::iter::once(program)
                .chain(args.iter().copied())
                .collect::<Vec<_>>()
                .join(" ");
            Ok(self.responses.get(&key).cloned().unwrap_or_default())
        }
    }

    #[test]
    fn collect_state_parses_hostname_and_deployment() {
        let runner = MockRunner::new(&[
            ("hostname", &[], "silverblue-lab\n"),
            (
                "rpm-ostree",
                &["status", "--booted", "--json"],
                r#"{"deployments":[{"origin":"fedora/41/x86_64/silverblue","booted":true,"version":"41.20260401.0","requested-packages":["vim","htop"]}]}"#,
            ),
            (
                "systemctl",
                &[
                    "list-units",
                    "--type=service",
                    "--state=running",
                    "--no-legend",
                    "--no-pager",
                    "--plain",
                ],
                "sshd.service  loaded  active  running  OpenSSH server\n",
            ),
            (
                "flatpak",
                &["list", "--columns=application"],
                "org.gnome.Gedit\n",
            ),
            ("toolbox", &["list", "--containers"], "sysknife-dev\n"),
            (
                "podman",
                &["ps", "--format", "{{.Names}}"],
                "my-container\n",
            ),
            (
                "getent",
                &["passwd", "--service", "files"],
                "root:x:0:0:root:/root:/bin/bash\njane:x:1000:1000:Jane:/home/jane:/bin/bash\n",
            ),
        ]);

        let state = collect_state(&runner).unwrap();

        assert_eq!(state.host_name, "silverblue-lab");
        assert_eq!(
            state.deployment,
            "fedora/41/x86_64/silverblue (booted, v41.20260401.0)"
        );
        assert_eq!(state.services, vec!["sshd.service"]);
        assert_eq!(state.flatpaks, vec!["org.gnome.Gedit"]);
        assert_eq!(state.toolboxes, vec!["sysknife-dev"]);
        assert_eq!(state.layered_packages, vec!["vim", "htop"]);
        assert_eq!(state.containers, vec!["my-container"]);
        assert_eq!(state.users, vec!["jane"]);
    }

    #[test]
    fn collect_state_trims_hostname_whitespace() {
        let runner = MockRunner::new(&[
            ("hostname", &[], "  my-host  \n"),
            ("rpm-ostree", &["status", "--booted", "--json"], "{}"),
        ]);

        let state = collect_state(&runner).unwrap();
        assert_eq!(state.host_name, "my-host");
    }

    #[test]
    fn collect_state_defaults_to_empty_lists_on_optional_command_failure() {
        struct PartialRunner;
        impl CommandRunner for PartialRunner {
            fn run(&self, program: &str, _args: &[&str]) -> Result<String, io::Error> {
                match program {
                    "hostname" => Ok("host\n".to_string()),
                    "rpm-ostree" => Ok("{}".to_string()),
                    _ => Err(io::Error::new(io::ErrorKind::NotFound, "not found")),
                }
            }
        }

        let state = collect_state(&PartialRunner).unwrap();
        assert!(state.services.is_empty());
        assert!(state.flatpaks.is_empty());
        assert!(state.toolboxes.is_empty());
        assert!(state.layered_packages.is_empty());
        assert!(state.containers.is_empty());
        assert!(state.users.is_empty());
    }

    #[test]
    fn collect_state_returns_error_when_hostname_fails() {
        struct FailingRunner;
        impl CommandRunner for FailingRunner {
            fn run(&self, _program: &str, _args: &[&str]) -> Result<String, io::Error> {
                Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
            }
        }

        let result = collect_state(&FailingRunner);
        assert!(
            matches!(
                result,
                Err(CollectorError::CommandFailed {
                    command: "hostname",
                    ..
                })
            ),
            "expected CommandFailed(hostname), got: {result:?}"
        );
    }

    #[test]
    fn collect_state_returns_empty_deployment_when_rpm_ostree_missing() {
        // rpm-ostree is not available on all systems (e.g. Fedora Workstation,
        // Ubuntu, CI). A missing binary must produce an empty deployment string,
        // not an error, so the daemon stays functional on non-Silverblue hosts.
        struct NoRpmOstreeRunner;
        impl CommandRunner for NoRpmOstreeRunner {
            fn run(&self, program: &str, _args: &[&str]) -> Result<String, io::Error> {
                match program {
                    "hostname" => Ok("non-silverblue-host\n".to_string()),
                    _ => Err(io::Error::new(io::ErrorKind::NotFound, "not found")),
                }
            }
        }

        let state = collect_state(&NoRpmOstreeRunner).unwrap();
        assert_eq!(state.host_name, "non-silverblue-host");
        assert_eq!(
            state.deployment, "",
            "deployment must be empty, not an error"
        );
        assert!(state.services.is_empty());
        assert!(state.flatpaks.is_empty());
        assert!(state.toolboxes.is_empty());
        assert!(state.layered_packages.is_empty());
        assert!(state.containers.is_empty());
        assert!(state.users.is_empty());
    }

    #[test]
    fn collect_state_parses_multiple_services() {
        let runner = MockRunner::new(&[
            ("hostname", &[], "host\n"),
            ("rpm-ostree", &["status", "--booted", "--json"], "{}"),
            (
                "systemctl",
                &[
                    "list-units",
                    "--type=service",
                    "--state=running",
                    "--no-legend",
                    "--no-pager",
                    "--plain",
                ],
                "sshd.service  loaded  active  running  SSH\nNetworkManager.service  loaded  active  running  NM\n",
            ),
        ]);

        let state = collect_state(&runner).unwrap();
        assert_eq!(
            state.services,
            vec!["sshd.service", "NetworkManager.service"]
        );
    }

    #[test]
    fn collected_state_round_trips_through_json() {
        let state = CollectedState {
            host_name: "lab".to_string(),
            deployment: "{}".to_string(),
            services: vec!["sshd.service".to_string()],
            flatpaks: vec!["org.mozilla.firefox".to_string()],
            toolboxes: vec![],
            layered_packages: vec!["vim".to_string()],
            containers: vec!["dev-box".to_string()],
            users: vec!["alice".to_string()],
            machine_id_hash: Some("deadbeef".to_string()),
        };

        let json = serde_json::to_string(&state).unwrap();
        let restored: CollectedState = serde_json::from_str(&json).unwrap();
        assert_eq!(state, restored);
    }

    #[test]
    fn machine_id_hash_is_stable_domain_separated_and_hides_the_raw_id() {
        // Deterministic and dependent on the input.
        assert_eq!(hash_machine_id("abc"), hash_machine_id("abc"));
        assert_ne!(hash_machine_id("abc"), hash_machine_id("abd"));
        // 64 hex chars (sha256) and never the raw id.
        let h = hash_machine_id("0123456789abcdef0123456789abcdef");
        assert_eq!(h.len(), 64);
        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
        assert!(!h.contains("0123456789abcdef"));
    }

    #[test]
    fn parse_layered_packages_extracts_requested_packages() {
        let json = r#"{"deployments":[{"requested-packages":["vim","htop"],"requested-local-packages":["my-tool"]}]}"#;
        let pkgs = super::parse_layered_packages(json);
        assert_eq!(pkgs, vec!["vim", "htop", "my-tool"]);
    }

    #[test]
    fn parse_layered_packages_handles_empty_deployments() {
        let json = r#"{"deployments":[]}"#;
        assert!(super::parse_layered_packages(json).is_empty());
    }

    #[test]
    fn parse_layered_packages_handles_invalid_json() {
        assert!(super::parse_layered_packages("not json").is_empty());
    }

    #[test]
    fn parse_deployment_summary_extracts_origin_and_version() {
        let json = r#"{"deployments":[{"origin":"fedora/41/x86_64/silverblue","booted":true,"version":"41.20260401.0","requested-packages":[]}]}"#;
        assert_eq!(
            super::parse_deployment_summary(json),
            "fedora/41/x86_64/silverblue (booted, v41.20260401.0)"
        );
    }

    #[test]
    fn parse_deployment_summary_handles_missing_version() {
        let json = r#"{"deployments":[{"origin":"fedora/41/x86_64/silverblue","booted":true}]}"#;
        assert_eq!(
            super::parse_deployment_summary(json),
            "fedora/41/x86_64/silverblue (booted)"
        );
    }

    #[test]
    fn parse_deployment_summary_returns_empty_on_invalid_json() {
        assert_eq!(super::parse_deployment_summary("not json"), "");
        assert_eq!(super::parse_deployment_summary("{}"), "");
        assert_eq!(super::parse_deployment_summary(r#"{"deployments":[]}"#), "");
    }

    #[test]
    fn parse_local_users_filters_by_uid_and_excludes_system_accounts() {
        let passwd = "root:x:0:0:root:/root:/bin/bash\n\
                      daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n\
                      jane:x:1000:1000:Jane:/home/jane:/bin/bash\n\
                      bob:x:1001:1001:Bob:/home/bob:/bin/bash\n\
                      svcacct:x:1002:1002:Service Account:/home/svcacct:/usr/sbin/nologin\n\
                      blocked:x:1003:1003:Blocked:/home/blocked:/bin/false\n\
                      nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin\n\
                      nfsnobody:x:65534:65534:nfsnobody:/nonexistent:/usr/sbin/nologin\n";
        let users = super::parse_local_users(passwd);
        assert_eq!(users, vec!["jane", "bob"]);
    }

    #[test]
    fn parse_local_users_handles_empty_output() {
        assert!(super::parse_local_users("").is_empty());
    }
}