Skip to main content

mur_common/
ssh_proxy_status.rs

1//! What the runtime concluded about the ssh-agent proxy at its last start.
2//!
3//! The runtime classifies every start (boundary vs audit-only, see
4//! `mur-agent-runtime/src/sandbox/ssh_bypass.rs`) and writes the result to
5//! `<agent_home>/`[`STATUS_FILE`]; `mur agent status` reads it. Both sides
6//! share this one definition so the file name and shape cannot drift.
7
8use std::io;
9use std::path::{Path, PathBuf};
10
11use serde::{Deserialize, Serialize};
12
13/// File under the agent's home holding the last classification.
14pub const STATUS_FILE: &str = "ssh_proxy.json";
15
16/// The three things MUR may say about the proxy for one agent.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum SshProxyState {
20    /// The agent holds no `entitlements.ssh` keys: there is nothing to claim.
21    Off,
22    /// The agent's own sandbox refuses `connect(2)` to the upstream socket.
23    Boundary,
24    /// The agent can reach the upstream itself; the proxy only binds an agent
25    /// that cooperates.
26    AuditOnly,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct SshProxyStatus {
31    pub state: SshProxyState,
32    /// Stable reason code: why it is `AuditOnly` (`AuditReason::as_str`), or
33    /// why the proxy did not start despite `entitlements.ssh` keys (`Off`).
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub code: Option<String>,
36    /// One line a human can act on.
37    pub explanation: String,
38    /// When the runtime classified, as unix milliseconds.
39    pub at_unix_ms: u64,
40}
41
42/// Where the status for the agent living at `agent_home` is stored.
43pub fn status_path(agent_home: &Path) -> PathBuf {
44    agent_home.join(STATUS_FILE)
45}
46
47/// Persist `status` (temp file + rename, so a reader never sees half of it).
48pub fn write(agent_home: &Path, status: &SshProxyStatus) -> io::Result<()> {
49    let path = status_path(agent_home);
50    let tmp = path.with_extension("json.tmp");
51    let body = serde_json::to_vec_pretty(status).map_err(io::Error::other)?;
52    std::fs::write(&tmp, body)?;
53    std::fs::rename(&tmp, &path)
54}
55
56/// The recorded status, or `None` when absent or unreadable. A garbled file
57/// reads as absent: `status` then says nothing rather than something false.
58pub fn read(agent_home: &Path) -> Option<SshProxyStatus> {
59    let bytes = std::fs::read(status_path(agent_home)).ok()?;
60    serde_json::from_slice(&bytes).ok()
61}
62
63impl SshProxyStatus {
64    /// `off`, `off (<code>)`, `boundary`, or `audit-only (<code>)`. The one rendering of the
65    /// value, shared by `mur agent status` and the start notice on the
66    /// agent's channel so the two can never word it differently.
67    pub fn label(&self) -> String {
68        match self.state {
69            SshProxyState::Off => match &self.code {
70                Some(c) => format!("off ({c})"),
71                None => "off".to_string(),
72            },
73            SshProxyState::Boundary => "boundary".to_string(),
74            SshProxyState::AuditOnly => {
75                format!("audit-only ({})", self.code.as_deref().unwrap_or("unknown"))
76            }
77        }
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    #[test]
86    fn round_trips_each_state() {
87        let tmp = tempfile::tempdir().unwrap();
88        assert!(read(tmp.path()).is_none());
89        for (state, code) in [
90            (SshProxyState::Off, None),
91            (SshProxyState::Boundary, None),
92            (
93                SshProxyState::AuditOnly,
94                Some("probe_reachable".to_string()),
95            ),
96        ] {
97            let s = SshProxyStatus {
98                state,
99                code,
100                explanation: "why".into(),
101                at_unix_ms: 9,
102            };
103            write(tmp.path(), &s).unwrap();
104            assert_eq!(read(tmp.path()), Some(s));
105        }
106    }
107
108    #[test]
109    fn off_names_its_reason_when_it_has_one() {
110        let mut s = SshProxyStatus {
111            state: SshProxyState::Off,
112            code: None,
113            explanation: "why".into(),
114            at_unix_ms: 0,
115        };
116        assert_eq!(s.label(), "off");
117        s.code = Some("socket_path_too_long".into());
118        assert_eq!(s.label(), "off (socket_path_too_long)");
119    }
120
121    #[test]
122    fn garbled_file_reads_as_absent() {
123        let tmp = tempfile::tempdir().unwrap();
124        std::fs::write(status_path(tmp.path()), "{nope").unwrap();
125        assert!(read(tmp.path()).is_none());
126    }
127}