Skip to main content

subc_daemon/
caller_identity.rs

1//! Caller descriptions from daemon-owned connection endpoints, never client
2//! claims. A missing OS lookup is an ordinary unidentified caller, not a refusal.
3
4use std::net::SocketAddr;
5use std::path::Path;
6use subc_os::socket_peer::{loopback_socket_peer, SocketPeer};
7use tokio::net::TcpStream;
8
9#[derive(Clone, Debug, Default, PartialEq, Eq)]
10pub struct CallerIdentity {
11    resolved: Option<SocketPeer>,
12    daemon_settings: bool,
13}
14
15impl CallerIdentity {
16    /// Resolve the connecting process from an accepted stream. This best-effort
17    /// OS lookup is blocking and supplies descriptive information only.
18    pub fn lookup(accepted: &TcpStream) -> Self {
19        Self::lookup_with(accepted, loopback_socket_peer)
20    }
21
22    /// Resolve an endpoint pair captured from the daemon's accepted socket.
23    /// Like `lookup`, this walks OS process tables and must run off async workers.
24    pub(crate) fn lookup_endpoints(local: SocketAddr, peer: SocketAddr) -> Self {
25        Self::from_lookup_result(loopback_socket_peer(local, peer))
26    }
27
28    fn lookup_with(
29        accepted: &TcpStream,
30        lookup: impl FnOnce(SocketAddr, SocketAddr) -> Option<SocketPeer>,
31    ) -> Self {
32        Self::from_lookup_result(
33            accepted
34                .local_addr()
35                .ok()
36                .zip(accepted.peer_addr().ok())
37                .and_then(|(local, peer)| lookup(local, peer)),
38        )
39    }
40
41    fn from_lookup_result(resolved: Option<SocketPeer>) -> Self {
42        Self {
43            resolved,
44            daemon_settings: false,
45        }
46    }
47
48    pub(crate) fn daemon_settings() -> Self {
49        Self {
50            resolved: None,
51            daemon_settings: true,
52        }
53    }
54
55    pub(crate) fn is_daemon_settings(&self) -> bool {
56        self.daemon_settings
57    }
58
59    pub fn pid(&self) -> Option<u32> {
60        self.resolved.as_ref().map(|caller| caller.pid)
61    }
62
63    /// The executable key for caller cooldowns, or `None` when the connection
64    /// must be used as the fallback key instead.
65    pub fn executable(&self) -> Option<&Path> {
66        self.resolved
67            .as_ref()
68            .map(|caller| caller.executable.as_path())
69    }
70
71    /// An unbounded description. Prompt builders must still sanitize and limit
72    /// the executable path to their own text budget.
73    pub fn description(&self) -> String {
74        if self.daemon_settings {
75            return "A settings file changed".into();
76        }
77        match &self.resolved {
78            Some(caller) => format!("pid {} ({})", caller.pid, caller.executable.display()),
79            None => "an unidentified local process".to_owned(),
80        }
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use std::path::PathBuf;
88
89    #[tokio::test]
90    async fn forced_lookup_failure_is_an_ordinary_unidentified_caller() {
91        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
92        let client = TcpStream::connect(listener.local_addr().unwrap())
93            .await
94            .unwrap();
95        let (accepted, _) = listener.accept().await.unwrap();
96        let caller = CallerIdentity::lookup_with(&accepted, |local, peer| {
97            assert_eq!(local, listener.local_addr().unwrap());
98            assert_eq!(peer, client.local_addr().unwrap());
99            None
100        });
101        assert_eq!(caller.description(), "an unidentified local process");
102        assert_eq!(caller.pid(), None);
103        assert_eq!(caller.executable(), None);
104        assert_eq!(caller, CallerIdentity::default());
105    }
106
107    #[test]
108    fn resolved_description_keeps_pid_and_executable() {
109        let caller = CallerIdentity::from_lookup_result(Some(SocketPeer {
110            pid: 4121,
111            executable: PathBuf::from("/bin/helper"),
112        }));
113        assert_eq!(caller.pid(), Some(4121));
114        assert_eq!(caller.executable(), Some(Path::new("/bin/helper")));
115        assert_eq!(caller.description(), "pid 4121 (/bin/helper)");
116    }
117}