endpoint_libs/libs/
peer.rs1use 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#[derive(Debug, Clone)]
25#[non_exhaustive]
26pub enum PeerIdentity {
27 Network(SocketAddr),
29 Local(LocalPeer),
31 Unknown,
33}
34
35#[derive(Debug, Clone)]
38pub struct LocalPeer {
39 pub pid: Option<u32>,
40 pub uid: Option<u32>,
42 pub attestation: Attestation,
43}
44
45#[derive(Debug, Clone)]
50#[non_exhaustive]
51pub enum Attestation {
52 None,
54 Verified {
57 mechanism: &'static str,
60 subject: String,
62 },
63}
64
65impl Attestation {
66 pub fn is_verified(&self) -> bool {
68 matches!(self, Self::Verified { .. })
69 }
70}
71
72impl PeerIdentity {
73 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 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 pub fn attestation(&self) -> Option<&Attestation> {
98 match self {
99 Self::Local(peer) => Some(&peer.attestation),
100 _ => None,
101 }
102 }
103
104 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
136trait 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).clone_box()
174 }
175}
176
177#[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 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 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 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 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 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 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}