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};
18use alloc::collections::BTreeMap as HashMap;
19
20#[derive(Debug, Clone)]
22#[non_exhaustive]
23pub enum PeerIdentity {
24 Network(SocketAddr),
26 Local(LocalPeer),
28 Unknown,
30}
31
32#[derive(Debug, Clone)]
35pub struct LocalPeer {
36 pub pid: Option<u32>,
37 pub uid: Option<u32>,
39 pub attestation: Attestation,
40}
41
42#[derive(Debug, Clone)]
47#[non_exhaustive]
48pub enum Attestation {
49 None,
51 Verified {
54 mechanism: &'static str,
57 subject: String,
59 },
60}
61
62impl Attestation {
63 pub fn is_verified(&self) -> bool {
65 matches!(self, Self::Verified { .. })
66 }
67}
68
69impl PeerIdentity {
70 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 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 pub fn attestation(&self) -> Option<&Attestation> {
95 match self {
96 Self::Local(peer) => Some(&peer.attestation),
97 _ => None,
98 }
99 }
100
101 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
133trait 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).clone_box()
171 }
172}
173
174#[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 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 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 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 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 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 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}