Skip to main content

endpoint_libs/libs/
peer.rs

1//! Peer identity for a connection, independent of transport.
2//!
3//! Before 2.0 a connection's peer was a bare `SocketAddr`, which only makes sense for
4//! TCP/TLS. Local transports (Unix sockets, Windows named pipes, macOS XPC) identify
5//! peers by process and by *code identity* — a codesign requirement, an executable
6//! digest, a SID — and that has to survive all the way into the request context so
7//! authorization and logging can see it.
8//!
9//! [`PeerIdentity`] is `#[non_exhaustive]`: new transports may add variants without a
10//! breaking release.
11
12use alloc::borrow::ToOwned;
13use alloc::boxed::Box;
14use alloc::format;
15use alloc::string::{String, ToString};
16use core::any::{Any, TypeId};
17use core::net::{IpAddr, Ipv4Addr, SocketAddr};
18use alloc::collections::BTreeMap as HashMap;
19
20/// Who is on the other end of a connection.
21#[derive(Debug, Clone)]
22#[non_exhaustive]
23pub enum PeerIdentity {
24    /// A TCP/TLS network peer — the pre-2.0 behaviour.
25    Network(SocketAddr),
26    /// A same-machine peer reached over a local transport.
27    Local(LocalPeer),
28    /// Transport could not determine a peer (in-process tests, exotic transports).
29    Unknown,
30}
31
32/// A same-machine peer: OS-level process identity plus whatever code identity the
33/// transport was able to verify.
34#[derive(Debug, Clone)]
35pub struct LocalPeer {
36    pub pid: Option<u32>,
37    /// Effective uid. Unix only — always `None` on Windows.
38    pub uid: Option<u32>,
39    pub attestation: Attestation,
40}
41
42/// Whether — and how — the transport verified the peer's *code* identity.
43///
44/// This is deliberately separate from `pid`/`uid`: knowing which process connected is
45/// not the same as knowing it runs the binary you expect.
46#[derive(Debug, Clone)]
47#[non_exhaustive]
48pub enum Attestation {
49    /// The transport did not verify code identity. Treat the peer as untrusted.
50    None,
51    /// The OS or the transport verified code identity before the connection was
52    /// handed over.
53    Verified {
54        /// How it was verified, e.g. `"xpc-codesign-requirement"`,
55        /// `"pidfd-exe-sha256"`, `"pipe-sid-dacl"`.
56        mechanism: &'static str,
57        /// What matched: the requirement string, digest, or SID.
58        subject: String,
59    },
60}
61
62impl Attestation {
63    /// True only for [`Attestation::Verified`].
64    pub fn is_verified(&self) -> bool {
65        matches!(self, Self::Verified { .. })
66    }
67}
68
69impl PeerIdentity {
70    /// Best-effort IP for logging and for the pre-2.0 `ip_addr` field.
71    ///
72    /// Local and unknown peers report loopback — they have no IP, and loopback is
73    /// both truthful about locality and safe for code that only formats this value.
74    pub fn ip_addr(&self) -> IpAddr {
75        match self {
76            Self::Network(addr) => addr.ip(),
77            Self::Local(_) | Self::Unknown => IpAddr::V4(Ipv4Addr::LOCALHOST),
78        }
79    }
80
81    /// The socket address for network peers; a loopback placeholder otherwise.
82    ///
83    /// Provided for the deprecated `WsConnection::address` accessor. Prefer matching
84    /// on the enum.
85    pub fn socket_addr(&self) -> SocketAddr {
86        match self {
87            Self::Network(addr) => *addr,
88            Self::Local(_) | Self::Unknown => SocketAddr::from(([127, 0, 0, 1], 0)),
89        }
90    }
91
92    /// Attestation for local peers; `None` for network peers (TLS client certs are
93    /// not modelled here).
94    pub fn attestation(&self) -> Option<&Attestation> {
95        match self {
96            Self::Local(peer) => Some(&peer.attestation),
97            _ => None,
98        }
99    }
100
101    /// Compact one-line form for logs: `1.2.3.4:5678`, `local(pid=42,xpc-codesign-requirement)`.
102    pub fn display(&self) -> String {
103        match self {
104            Self::Network(addr) => addr.to_string(),
105            Self::Local(peer) => {
106                let pid = peer
107                    .pid
108                    .map_or_else(|| "?".to_owned(), |pid| pid.to_string());
109                match &peer.attestation {
110                    Attestation::Verified { mechanism, .. } => {
111                        format!("local(pid={pid},{mechanism})")
112                    }
113                    Attestation::None => format!("local(pid={pid},unattested)"),
114                }
115            }
116            Self::Unknown => "unknown".to_owned(),
117        }
118    }
119}
120
121impl core::fmt::Display for PeerIdentity {
122    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
123        f.write_str(&self.display())
124    }
125}
126
127impl From<SocketAddr> for PeerIdentity {
128    fn from(addr: SocketAddr) -> Self {
129        Self::Network(addr)
130    }
131}
132
133// ---------------------------------------------------------------------------
134// Extensions
135// ---------------------------------------------------------------------------
136
137/// Object-safe `Any` that can also clone itself.
138///
139/// `RequestContext` derives `Clone` and consumers rely on that, so a plain
140/// `Box<dyn Any>` map cannot live inside it. Requiring `Clone` on stored values (the
141/// same trade `http::Extensions` makes) keeps the containing types cloneable.
142trait CloneAny: Any + Send + Sync {
143    fn clone_box(&self) -> Box<dyn CloneAny>;
144    fn as_any(&self) -> &dyn Any;
145    fn as_any_mut(&mut self) -> &mut dyn Any;
146    fn into_any(self: Box<Self>) -> Box<dyn Any>;
147}
148
149impl<T: Any + Send + Sync + Clone> CloneAny for T {
150    fn clone_box(&self) -> Box<dyn CloneAny> {
151        Box::new(self.clone())
152    }
153    fn as_any(&self) -> &dyn Any {
154        self
155    }
156    fn as_any_mut(&mut self) -> &mut dyn Any {
157        self
158    }
159    fn into_any(self: Box<Self>) -> Box<dyn Any> {
160        self
161    }
162}
163
164impl Clone for Box<dyn CloneAny> {
165    fn clone(&self) -> Self {
166        // `(**self)` is load-bearing. `Box<dyn CloneAny>` satisfies the blanket impl's
167        // bounds, so `self.clone_box()` would resolve to the box's own `clone_box`,
168        // which calls `clone` — infinite recursion and a stack overflow. Deref to the
169        // trait object so the inner value's `clone_box` runs instead.
170        (**self).clone_box()
171    }
172}
173
174/// A type-keyed map for attaching arbitrary data to a connection or request.
175///
176/// Modelled on `http::Extensions`, implemented here to avoid the dependency. Used to
177/// carry attestation on a connection and verified mission-token claims on a request,
178/// without either concept leaking into this crate's core types.
179///
180/// Stored values must be `Clone` so that the containing `RequestContext` stays
181/// `Clone`.
182#[derive(Default, Clone)]
183pub struct Extensions {
184    map: HashMap<TypeId, Box<dyn CloneAny>>,
185}
186
187impl Extensions {
188    pub fn new() -> Self {
189        Self::default()
190    }
191
192    /// Insert a value, returning the previous one of the same type, if any.
193    pub fn insert<T: Clone + Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
194        self.map
195            .insert(TypeId::of::<T>(), Box::new(value))
196            .and_then(|prev| prev.into_any().downcast().ok().map(|boxed| *boxed))
197    }
198
199    pub fn get<T: Clone + Send + Sync + 'static>(&self) -> Option<&T> {
200        // `(**boxed)` is load-bearing: `Box<dyn CloneAny>` itself satisfies
201        // `Any + Send + Sync + Clone`, so it matches the blanket impl below and
202        // `boxed.as_any()` would resolve to the *box's* impl — yielding a `dyn Any`
203        // whose concrete type is the box, which never downcasts to `T`.
204        self.map
205            .get(&TypeId::of::<T>())
206            .and_then(|boxed| (**boxed).as_any().downcast_ref())
207    }
208
209    pub fn get_mut<T: Clone + Send + Sync + 'static>(&mut self) -> Option<&mut T> {
210        // See the note in `get` — the explicit deref is required here too.
211        self.map
212            .get_mut(&TypeId::of::<T>())
213            .and_then(|boxed| (**boxed).as_any_mut().downcast_mut())
214    }
215
216    pub fn remove<T: Clone + Send + Sync + 'static>(&mut self) -> Option<T> {
217        self.map
218            .remove(&TypeId::of::<T>())
219            .and_then(|boxed| boxed.into_any().downcast().ok().map(|b| *b))
220    }
221
222    pub fn contains<T: Clone + Send + Sync + 'static>(&self) -> bool {
223        self.map.contains_key(&TypeId::of::<T>())
224    }
225
226    pub fn is_empty(&self) -> bool {
227        self.map.is_empty()
228    }
229
230    pub fn len(&self) -> usize {
231        self.map.len()
232    }
233}
234
235impl core::fmt::Debug for Extensions {
236    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
237        // Values are `dyn Any` and cannot be formatted; report the count so logs
238        // still show whether anything was attached.
239        f.debug_struct("Extensions")
240            .field("len", &self.map.len())
241            .finish()
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn network_peer_reports_its_own_ip() {
251        let addr: SocketAddr = "203.0.113.7:9000".parse().unwrap();
252        let peer = PeerIdentity::Network(addr);
253        assert_eq!(peer.ip_addr(), addr.ip());
254        assert_eq!(peer.socket_addr(), addr);
255        assert_eq!(peer.display(), "203.0.113.7:9000");
256        assert!(peer.attestation().is_none());
257    }
258
259    #[test]
260    fn local_peer_reports_loopback_and_keeps_attestation() {
261        let peer = PeerIdentity::Local(LocalPeer {
262            pid: Some(42),
263            uid: Some(501),
264            attestation: Attestation::Verified {
265                mechanism: "xpc-codesign-requirement",
266                subject: "identifier agentone".to_owned(),
267            },
268        });
269        assert_eq!(peer.ip_addr(), IpAddr::V4(Ipv4Addr::LOCALHOST));
270        assert!(peer.attestation().unwrap().is_verified());
271        assert_eq!(peer.display(), "local(pid=42,xpc-codesign-requirement)");
272    }
273
274    #[test]
275    fn unattested_local_peer_is_visible_as_such() {
276        let peer = PeerIdentity::Local(LocalPeer {
277            pid: None,
278            uid: None,
279            attestation: Attestation::None,
280        });
281        assert!(!peer.attestation().unwrap().is_verified());
282        assert_eq!(peer.display(), "local(pid=?,unattested)");
283    }
284
285    #[test]
286    fn extensions_survive_a_clone() {
287        #[derive(Debug, Clone, PartialEq)]
288        struct Claims(&'static str);
289
290        let mut ext = Extensions::new();
291        ext.insert(Claims("mission-1"));
292        // RequestContext derives Clone; extensions must come along intact.
293        let copy = ext.clone();
294        assert_eq!(copy.get::<Claims>(), Some(&Claims("mission-1")));
295    }
296
297    #[test]
298    fn extensions_round_trip_by_type() {
299        #[derive(Debug, Clone, PartialEq)]
300        struct Claims(&'static str);
301
302        let mut ext = Extensions::new();
303        assert!(ext.is_empty());
304        assert!(ext.get::<Claims>().is_none());
305
306        assert!(ext.insert(Claims("mission-1")).is_none());
307        assert_eq!(ext.get::<Claims>(), Some(&Claims("mission-1")));
308        assert!(ext.contains::<Claims>());
309
310        // Re-inserting returns the previous value rather than silently dropping it.
311        let prev = ext.insert(Claims("mission-2"));
312        assert_eq!(prev, Some(Claims("mission-1")));
313        assert_eq!(ext.get::<Claims>(), Some(&Claims("mission-2")));
314
315        assert_eq!(ext.remove::<Claims>(), Some(Claims("mission-2")));
316        assert!(ext.is_empty());
317    }
318}