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")]
34 pub code: Option<String>,
35 pub explanation: String,
37 pub at_unix_ms: u64,
39}
40
41pub fn status_path(agent_home: &Path) -> PathBuf {
43 agent_home.join(STATUS_FILE)
44}
45
46pub 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
55pub 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 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}