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