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}
13
14impl CallerIdentity {
15    /// Resolve the connecting process from an accepted stream. This best-effort
16    /// OS lookup is blocking and supplies descriptive information only.
17    pub fn lookup(accepted: &TcpStream) -> Self {
18        Self::lookup_with(accepted, loopback_socket_peer)
19    }
20
21    /// Resolve an endpoint pair captured from the daemon's accepted socket.
22    /// Like `lookup`, this walks OS process tables and must run off async workers.
23    pub(crate) fn lookup_endpoints(local: SocketAddr, peer: SocketAddr) -> Self {
24        Self::from_lookup_result(loopback_socket_peer(local, peer))
25    }
26
27    fn lookup_with(
28        accepted: &TcpStream,
29        lookup: impl FnOnce(SocketAddr, SocketAddr) -> Option<SocketPeer>,
30    ) -> Self {
31        Self::from_lookup_result(
32            accepted
33                .local_addr()
34                .ok()
35                .zip(accepted.peer_addr().ok())
36                .and_then(|(local, peer)| lookup(local, peer)),
37        )
38    }
39
40    fn from_lookup_result(resolved: Option<SocketPeer>) -> Self {
41        Self { resolved }
42    }
43
44    pub fn pid(&self) -> Option<u32> {
45        self.resolved.as_ref().map(|caller| caller.pid)
46    }
47
48    /// The executable key for caller cooldowns, or `None` when the connection
49    /// must be used as the fallback key instead.
50    pub fn executable(&self) -> Option<&Path> {
51        self.resolved
52            .as_ref()
53            .map(|caller| caller.executable.as_path())
54    }
55
56    /// An unbounded description. Prompt builders must still sanitize and limit
57    /// the executable path to their own text budget.
58    pub fn description(&self) -> String {
59        match &self.resolved {
60            Some(caller) => format!("pid {} ({})", caller.pid, caller.executable.display()),
61            None => "an unidentified local process".to_owned(),
62        }
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use std::path::PathBuf;
70
71    #[tokio::test]
72    async fn forced_lookup_failure_is_an_ordinary_unidentified_caller() {
73        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
74        let client = TcpStream::connect(listener.local_addr().unwrap())
75            .await
76            .unwrap();
77        let (accepted, _) = listener.accept().await.unwrap();
78        let caller = CallerIdentity::lookup_with(&accepted, |local, peer| {
79            assert_eq!(local, listener.local_addr().unwrap());
80            assert_eq!(peer, client.local_addr().unwrap());
81            None
82        });
83        assert_eq!(caller.description(), "an unidentified local process");
84        assert_eq!(caller.pid(), None);
85        assert_eq!(caller.executable(), None);
86        assert_eq!(caller, CallerIdentity::default());
87    }
88
89    #[test]
90    fn resolved_description_keeps_pid_and_executable() {
91        let caller = CallerIdentity::from_lookup_result(Some(SocketPeer {
92            pid: 4121,
93            executable: PathBuf::from("/bin/helper"),
94        }));
95        assert_eq!(caller.pid(), Some(4121));
96        assert_eq!(caller.executable(), Some(Path::new("/bin/helper")));
97        assert_eq!(caller.description(), "pid 4121 (/bin/helper)");
98    }
99}