mur_common/
ssh_proxy_status.rs1use std::io;
9use std::path::{Path, PathBuf};
10
11use serde::{Deserialize, Serialize};
12
13pub const STATUS_FILE: &str = "ssh_proxy.json";
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum SshProxyState {
20 Off,
22 Boundary,
24 AuditOnly,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct SshProxyStatus {
31 pub state: SshProxyState,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub code: Option<String>,
36 pub explanation: String,
38 pub at_unix_ms: u64,
40}
41
42pub fn status_path(agent_home: &Path) -> PathBuf {
44 agent_home.join(STATUS_FILE)
45}
46
47pub 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
56pub 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 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}