Skip to main content

mur_common/
ssh_proxy_refusals.rs

1//! Recent ssh-agent proxy refusals, shared by the runtime (writer) and
2//! `mur agent status` (reader).
3//!
4//! The ssh-agent protocol has no error text: every refusal reaches the ssh
5//! client as a bare `SSH_AGENT_FAILURE`. This file is where the user finds
6//! the actual reason (spec ยง"Refusals must be diagnosable outside the ssh
7//! client").
8
9use std::io::{self, Write};
10
11use fs2::FileExt;
12use std::path::{Path, PathBuf};
13
14use serde::{Deserialize, Serialize};
15
16/// File under the agent's home holding the most recent refusals.
17pub const REFUSALS_FILE: &str = "ssh_proxy_refusals.json";
18
19/// How many refusals are kept and shown by `mur agent status`.
20pub const RECENT_REFUSALS: usize = 5;
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct SshRefusal {
24    /// Stable reason code (`RefusalCode::as_str` in the runtime).
25    pub code: String,
26    /// The full human message, as logged and posted to the channel.
27    pub message: String,
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub key_fp: Option<String>,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub host_key_fp: Option<String>,
32    pub at_unix_ms: u64,
33}
34
35pub fn refusals_path(agent_home: &Path) -> PathBuf {
36    agent_home.join(REFUSALS_FILE)
37}
38
39/// Most recent first. Absent or garbled reads as empty.
40pub fn read(agent_home: &Path) -> Vec<SshRefusal> {
41    std::fs::read(refusals_path(agent_home))
42        .ok()
43        .and_then(|b| serde_json::from_slice(&b).ok())
44        .unwrap_or_default()
45}
46
47/// Prepend `r`, keep [`RECENT_REFUSALS`], and atomically replace the file.
48/// A stable sidecar lock serializes the entire read-modify-write across threads
49/// and processes. Never remove the lock file: waiters may hold its inode open.
50pub fn record(agent_home: &Path, r: SshRefusal) -> io::Result<()> {
51    let path = refusals_path(agent_home);
52    let lock = std::fs::OpenOptions::new()
53        .read(true)
54        .write(true)
55        .create(true)
56        .truncate(false)
57        .open(path.with_extension("json.lock"))?;
58    lock.lock_exclusive()?;
59    // Closing `lock` releases it on every return path, including errors.
60    let mut all = read(agent_home);
61    all.insert(0, r);
62    all.truncate(RECENT_REFUSALS);
63    let mut tmp = tempfile::NamedTempFile::new_in(agent_home)?;
64    tmp.write_all(&serde_json::to_vec_pretty(&all).map_err(io::Error::other)?)?;
65    tmp.persist(&path).map_err(|e| e.error)?;
66    Ok(())
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    fn r(i: u64) -> SshRefusal {
74        SshRefusal {
75            code: "key_not_allowed".into(),
76            message: format!("m{i}"),
77            key_fp: None,
78            host_key_fp: None,
79            at_unix_ms: i,
80        }
81    }
82
83    #[test]
84    fn keeps_the_newest_n_most_recent_first() {
85        let tmp = tempfile::tempdir().unwrap();
86        assert!(read(tmp.path()).is_empty());
87        for i in 0..(RECENT_REFUSALS as u64 + 2) {
88            record(tmp.path(), r(i)).unwrap();
89        }
90        let got = read(tmp.path());
91        assert_eq!(got.len(), RECENT_REFUSALS);
92        assert_eq!(got[0].at_unix_ms, RECENT_REFUSALS as u64 + 1);
93    }
94
95    /// Concurrent writers must not lose each other's records or trip over a
96    /// shared temp file (each `record` is its own read-modify-rename).
97    #[test]
98    fn concurrent_records_are_all_kept() {
99        let tmp = tempfile::tempdir().unwrap();
100        let home = tmp.path().to_path_buf();
101        let n = RECENT_REFUSALS as u64;
102        let barrier = std::sync::Arc::new(std::sync::Barrier::new(n as usize));
103        let handles: Vec<_> = (0..n)
104            .map(|i| {
105                let (home, barrier) = (home.clone(), barrier.clone());
106                std::thread::spawn(move || {
107                    barrier.wait();
108                    record(&home, r(i))
109                })
110            })
111            .collect();
112        for h in handles {
113            h.join().unwrap().unwrap();
114        }
115        let mut got: Vec<u64> = read(&home).iter().map(|x| x.at_unix_ms).collect();
116        got.sort_unstable();
117        assert_eq!(got, (0..n).collect::<Vec<_>>());
118        let leftovers: Vec<_> = std::fs::read_dir(&home)
119            .unwrap()
120            .filter_map(|e| e.ok())
121            .map(|e| e.file_name().to_string_lossy().into_owned())
122            .filter(|n| n.contains(".tmp"))
123            .collect();
124        assert!(leftovers.is_empty(), "temp files left: {leftovers:?}");
125    }
126
127    #[test]
128    fn garbled_file_reads_as_empty() {
129        let tmp = tempfile::tempdir().unwrap();
130        std::fs::write(refusals_path(tmp.path()), "[nope").unwrap();
131        assert!(read(tmp.path()).is_empty());
132    }
133}