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 (`AuditReason::as_str`) for `AuditOnly`, else `None`.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub code: Option<String>,
35    /// One line a human can act on.
36    pub explanation: String,
37    /// When the runtime classified, as unix milliseconds.
38    pub at_unix_ms: u64,
39}
40
41/// Where the status for the agent living at `agent_home` is stored.
42pub fn status_path(agent_home: &Path) -> PathBuf {
43    agent_home.join(STATUS_FILE)
44}
45
46/// Persist `status` (temp file + rename, so a reader never sees half of it).
47pub fn write(agent_home: &Path, status: &SshProxyStatus) -> io::Result<()> {
48    let path = status_path(agent_home);
49    let tmp = path.with_extension("json.tmp");
50    let body = serde_json::to_vec_pretty(status).map_err(io::Error::other)?;
51    std::fs::write(&tmp, body)?;
52    std::fs::rename(&tmp, &path)
53}
54
55/// The recorded status, or `None` when absent or unreadable. A garbled file
56/// reads as absent: `status` then says nothing rather than something false.
57pub fn read(agent_home: &Path) -> Option<SshProxyStatus> {
58    let bytes = std::fs::read(status_path(agent_home)).ok()?;
59    serde_json::from_slice(&bytes).ok()
60}
61
62impl SshProxyStatus {
63    /// `off`, `boundary`, or `audit-only (<code>)`. The one rendering of the
64    /// value, shared by `mur agent status` and the start notice on the
65    /// agent's channel so the two can never word it differently.
66    pub fn label(&self) -> String {
67        match self.state {
68            SshProxyState::Off => "off".to_string(),
69            SshProxyState::Boundary => "boundary".to_string(),
70            SshProxyState::AuditOnly => {
71                format!("audit-only ({})", self.code.as_deref().unwrap_or("unknown"))
72            }
73        }
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn round_trips_each_state() {
83        let tmp = tempfile::tempdir().unwrap();
84        assert!(read(tmp.path()).is_none());
85        for (state, code) in [
86            (SshProxyState::Off, None),
87            (SshProxyState::Boundary, None),
88            (
89                SshProxyState::AuditOnly,
90                Some("probe_reachable".to_string()),
91            ),
92        ] {
93            let s = SshProxyStatus {
94                state,
95                code,
96                explanation: "why".into(),
97                at_unix_ms: 9,
98            };
99            write(tmp.path(), &s).unwrap();
100            assert_eq!(read(tmp.path()), Some(s));
101        }
102    }
103
104    #[test]
105    fn garbled_file_reads_as_absent() {
106        let tmp = tempfile::tempdir().unwrap();
107        std::fs::write(status_path(tmp.path()), "{nope").unwrap();
108        assert!(read(tmp.path()).is_none());
109    }
110}