Skip to main content

mur_common/
start_refusal.rs

1//! A runtime that refuses to start, and the record it leaves behind (#2015).
2//!
3//! The per-agent runtime deliberately refuses to start on a profile it cannot
4//! trust (`entitlements_unpinned`, `entitlements_pin`, `profile_invalid`).
5//! Exiting `1` and letting the service manager respawn it turned that refusal
6//! into an endless crash loop with the reason buried in an append-forever log.
7//!
8//! A refusal now exits with [`EXIT_CODE`] — which the systemd unit lists in
9//! `RestartPreventExitStatus=` — and, before exiting, writes a
10//! [`StartRefusal`] to `<agent_home>/`[`MARKER_FILE`] so `mur agent status` /
11//! `mur agent start` can say *why* without anyone reading a log.
12//!
13//! The runtime writes the marker; the CLI reads it and `perm reseal` clears it.
14//! Both sides share this one definition so the file name, exit code, and shape
15//! cannot drift.
16
17use std::io;
18use std::path::{Path, PathBuf};
19
20use serde::{Deserialize, Serialize};
21
22/// Exit status of a runtime that refused to start. `78` is `EX_CONFIG`
23/// (sysexits.h): "something was found in an unconfigured or misconfigured
24/// state" — which is exactly a profile that failed its integrity check.
25pub const EXIT_CODE: i32 = 78;
26
27/// File under the agent's home holding the last refusal.
28pub const MARKER_FILE: &str = "start_refused.json";
29
30/// Why the last start was refused.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct StartRefusal {
33    /// Machine-readable code, e.g. `entitlements_unpinned`.
34    pub code: String,
35    /// The full human-readable refusal, including the remedy.
36    pub message: String,
37    /// When it was refused, as unix milliseconds. Lets a `start` that began
38    /// later tell this refusal from an older one it has since outlived.
39    pub at_unix_ms: u64,
40}
41
42impl StartRefusal {
43    /// Build a refusal from the runtime's `error[<code>]: <message>` line.
44    /// A line without that shape keeps the whole text under `unknown`.
45    pub fn from_line(line: &str, at_unix_ms: u64) -> Self {
46        let (code, message) = parse_line(line);
47        Self {
48            code,
49            message,
50            at_unix_ms,
51        }
52    }
53
54    /// `true` for refusals that `mur agent perm reseal` resolves.
55    pub fn is_entitlements(&self) -> bool {
56        self.code.starts_with("entitlements_")
57    }
58}
59
60/// Split `error[code]: message` into `(code, message)`; the message is the
61/// full original line so nothing the runtime said is lost.
62fn parse_line(line: &str) -> (String, String) {
63    let line = line.trim();
64    let code = line
65        .strip_prefix("error[")
66        .and_then(|rest| rest.split_once(']'))
67        .map(|(code, _)| code)
68        .filter(|c| !c.is_empty())
69        .unwrap_or("unknown");
70    (code.to_string(), line.to_string())
71}
72
73/// Where the marker for the agent living at `agent_home` is stored.
74pub fn marker_path(agent_home: &Path) -> PathBuf {
75    agent_home.join(MARKER_FILE)
76}
77
78/// Persist `refusal` (temp file + rename, so a reader never sees half of it).
79pub fn write(agent_home: &Path, refusal: &StartRefusal) -> io::Result<()> {
80    let path = marker_path(agent_home);
81    let tmp = path.with_extension("json.tmp");
82    let body = serde_json::to_vec_pretty(refusal).map_err(io::Error::other)?;
83    std::fs::write(&tmp, body)?;
84    std::fs::rename(&tmp, &path)
85}
86
87/// The recorded refusal, or `None` when absent or unreadable. A garbled
88/// marker is treated as absent: it must never make a healthy agent look
89/// refused.
90pub fn read(agent_home: &Path) -> Option<StartRefusal> {
91    let bytes = std::fs::read(marker_path(agent_home)).ok()?;
92    serde_json::from_slice(&bytes).ok()
93}
94
95/// Remove the marker. Returns whether one was there.
96pub fn clear(agent_home: &Path) -> bool {
97    std::fs::remove_file(marker_path(agent_home)).is_ok()
98}
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103
104    #[test]
105    fn parses_code_out_of_the_runtime_line() {
106        let r = StartRefusal::from_line(
107            "error[entitlements_unpinned]: bob's profile.yaml entitlements changed",
108            7,
109        );
110        assert_eq!(r.code, "entitlements_unpinned");
111        assert!(r.message.starts_with("error[entitlements_unpinned]:"));
112        assert!(r.is_entitlements());
113        assert_eq!(r.at_unix_ms, 7);
114    }
115
116    #[test]
117    fn unshaped_line_is_unknown_but_keeps_its_text() {
118        let r = StartRefusal::from_line("something odd", 1);
119        assert_eq!(r.code, "unknown");
120        assert_eq!(r.message, "something odd");
121        assert!(!r.is_entitlements());
122    }
123
124    #[test]
125    fn round_trips_and_clears() {
126        let tmp = tempfile::tempdir().unwrap();
127        assert!(read(tmp.path()).is_none());
128        let r = StartRefusal::from_line("error[profile_invalid]: bad yaml", 42);
129        write(tmp.path(), &r).unwrap();
130        assert_eq!(read(tmp.path()), Some(r));
131        assert!(clear(tmp.path()));
132        assert!(read(tmp.path()).is_none());
133        assert!(!clear(tmp.path()), "second clear finds nothing");
134    }
135
136    #[test]
137    fn garbled_marker_reads_as_absent() {
138        let tmp = tempfile::tempdir().unwrap();
139        std::fs::write(marker_path(tmp.path()), "{not json").unwrap();
140        assert!(read(tmp.path()).is_none());
141    }
142}