1use serde::{ser::Error as _, Deserialize, Deserializer, Serialize, Serializer};
15
16use crate::session::ModuleControlRequest;
17
18pub const OBSERVED_PEER_CAPABILITY: &str = "observed-peer/v1";
21
22pub const OPERATOR_APP_CAPABILITY: &str = "operator-app/v1";
26
27pub const PEER_BUILD_CAPABILITY: &str = "peer-build/v1";
30
31pub const CALLER_ATTESTATION_CAPABILITY: &str = "caller-attestation/v1";
33
34pub const MAX_ATTESTATION_INTEGER: u64 = (1_u64 << 53) - 1;
36
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40#[serde(rename_all = "snake_case")]
41#[non_exhaustive]
42pub enum CallerClaim {
43 Own,
44 Brokered,
45 Relay,
46 Legacy,
47 #[serde(other)]
48 Unknown,
49}
50
51#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
53#[serde(rename_all = "snake_case")]
54#[non_exhaustive]
55pub enum CallerOrigin {
56 Release,
57 Development,
58 #[serde(other)]
59 Other,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
66#[non_exhaustive]
67pub struct CallerAttestation {
68 pub incarnation: String,
69 #[serde(deserialize_with = "deserialize_attestation_integer")]
70 pub spawn: u64,
71 #[serde(deserialize_with = "deserialize_attestation_integer")]
72 pub authority_epoch: u64,
73 pub claim: CallerClaim,
74 pub first_party: bool,
75 pub origin: CallerOrigin,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub declaration: Option<serde_json::Map<String, serde_json::Value>>,
78 pub approved_declarations_digest: String,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub declaration_digest: Option<String>,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct CallerAttestationError {
86 field: &'static str,
87}
88
89impl CallerAttestationError {
90 pub fn field(&self) -> &'static str {
92 self.field
93 }
94}
95
96impl std::fmt::Display for CallerAttestationError {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 write!(f, "caller {} exceeds 2^53-1", self.field)
99 }
100}
101
102impl std::error::Error for CallerAttestationError {}
103
104impl CallerAttestation {
105 pub fn new(
123 incarnation: impl Into<String>,
124 spawn: u64,
125 authority_epoch: u64,
126 claim: CallerClaim,
127 first_party: bool,
128 origin: CallerOrigin,
129 approved_declarations_digest: impl Into<String>,
130 ) -> Result<Self, CallerAttestationError> {
131 for (field, value) in [("spawn", spawn), ("authority_epoch", authority_epoch)] {
132 if value > MAX_ATTESTATION_INTEGER {
133 return Err(CallerAttestationError { field });
134 }
135 }
136 Ok(Self {
137 incarnation: incarnation.into(),
138 spawn,
139 authority_epoch,
140 claim,
141 first_party,
142 origin,
143 declaration: None,
144 approved_declarations_digest: approved_declarations_digest.into(),
145 declaration_digest: None,
146 })
147 }
148
149 #[must_use]
152 pub fn with_declaration(
153 mut self,
154 declaration: serde_json::Map<String, serde_json::Value>,
155 digest: impl Into<String>,
156 ) -> Self {
157 self.declaration = Some(declaration);
158 self.declaration_digest = Some(digest.into());
159 self
160 }
161}
162
163fn deserialize_attestation_integer<'de, D: Deserializer<'de>>(decoder: D) -> Result<u64, D::Error> {
164 let value = u64::deserialize(decoder)?;
165 if value > MAX_ATTESTATION_INTEGER {
166 return Err(serde::de::Error::custom(
167 "attestation integer exceeds 2^53-1",
168 ));
169 }
170 Ok(value)
171}
172
173fn deserialize_caller<'de, D: Deserializer<'de>>(
174 decoder: D,
175) -> Result<Option<CallerAttestation>, D::Error> {
176 let Some(value) = Option::<serde_json::Value>::deserialize(decoder)? else {
177 return Ok(None);
178 };
179 for field in ["spawn", "authority_epoch"] {
182 if let Some(integer) = value.get(field) {
183 deserialize_attestation_integer(integer).map_err(serde::de::Error::custom)?;
184 }
185 }
186 if value.is_object()
187 && [
188 "incarnation",
189 "spawn",
190 "authority_epoch",
191 "claim",
192 "first_party",
193 "origin",
194 "approved_declarations_digest",
195 ]
196 .iter()
197 .any(|field| value.get(field).is_none())
198 {
199 return Ok(None);
200 }
201 serde_json::from_value(value)
202 .map(Some)
203 .map_err(serde::de::Error::custom)
204}
205
206#[derive(Debug, Clone, PartialEq, Eq)]
213#[non_exhaustive]
214pub enum ObservedPeerStatus {
215 Observed,
217 Unobserved,
220 Unknown(String),
223}
224
225impl Serialize for ObservedPeerStatus {
226 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
227 serializer.serialize_str(match self {
228 Self::Observed => "observed",
229 Self::Unobserved => "unobserved",
230 Self::Unknown(value) => value,
231 })
232 }
233}
234
235impl<'de> Deserialize<'de> for ObservedPeerStatus {
236 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
237 Ok(match String::deserialize(deserializer)?.as_str() {
238 "observed" => Self::Observed,
239 "unobserved" => Self::Unobserved,
240 value => Self::Unknown(value.to_owned()),
241 })
242 }
243}
244
245#[non_exhaustive]
252#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
253pub struct ObservedPeer {
254 pub status: ObservedPeerStatus,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub uid: Option<u32>,
258 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub sid: Option<String>,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub exe: Option<String>,
264 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub signing_id: Option<String>,
268}
269
270impl ObservedPeer {
271 pub fn unobserved() -> Self {
273 Self {
274 status: ObservedPeerStatus::Unobserved,
275 uid: None,
276 sid: None,
277 exe: None,
278 signing_id: None,
279 }
280 }
281
282 pub fn observed_uid(uid: u32) -> Self {
284 Self {
285 status: ObservedPeerStatus::Observed,
286 uid: Some(uid),
287 ..Self::unobserved()
288 }
289 }
290
291 pub fn observed_sid(sid: impl Into<String>) -> Self {
293 Self {
294 status: ObservedPeerStatus::Observed,
295 sid: Some(sid.into()),
296 ..Self::unobserved()
297 }
298 }
299
300 #[must_use]
302 pub fn with_exe(mut self, exe: Option<String>) -> Self {
303 self.exe = exe;
304 self
305 }
306
307 #[must_use]
309 pub fn with_signing_id(mut self, signing_id: Option<String>) -> Self {
310 self.signing_id = signing_id;
311 self
312 }
313}
314
315#[non_exhaustive]
322#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
323pub struct OperatorApp {
324 pub app: String,
326 pub pid: u32,
328}
329
330impl OperatorApp {
331 pub fn new(app: impl Into<String>, pid: u32) -> Self {
332 Self {
333 app: app.into(),
334 pid,
335 }
336 }
337}
338
339#[non_exhaustive]
345#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
346pub struct RouteBindPeer {
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub observed_peer: Option<ObservedPeer>,
350 #[serde(default, skip_serializing_if = "Option::is_none")]
353 pub operator_app: Option<OperatorApp>,
354 #[serde(
357 default,
358 skip_serializing_if = "Option::is_none",
359 deserialize_with = "deserialize_caller"
360 )]
361 pub caller: Option<CallerAttestation>,
362 #[serde(default, skip_serializing_if = "Option::is_none")]
367 pub peer_build: Option<String>,
368}
369
370impl RouteBindPeer {
371 pub fn new() -> Self {
373 Self::default()
374 }
375
376 #[must_use]
378 pub fn with_observed_peer(mut self, observed_peer: Option<ObservedPeer>) -> Self {
379 self.observed_peer = observed_peer;
380 self
381 }
382
383 #[must_use]
385 pub fn with_operator_app(mut self, operator_app: Option<OperatorApp>) -> Self {
386 self.operator_app = operator_app;
387 self
388 }
389
390 #[must_use]
392 pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
393 self.caller = caller;
394 self
395 }
396
397 #[must_use]
399 pub fn with_peer_build(mut self, peer_build: Option<String>) -> Self {
400 self.peer_build = peer_build;
401 self
402 }
403
404 pub fn is_empty(&self) -> bool {
406 self.observed_peer.is_none()
407 && self.operator_app.is_none()
408 && self.caller.is_none()
409 && self.peer_build.is_none()
410 }
411}
412
413pub fn encode_route_bind(
419 bind: &ModuleControlRequest,
420 peer: &RouteBindPeer,
421) -> serde_json::Result<Vec<u8>> {
422 if !matches!(bind, ModuleControlRequest::RouteBind { .. }) {
423 return Err(serde_json::Error::custom(
424 "peer keys can only be added to a route.bind request",
425 ));
426 }
427 if peer.is_empty() {
428 return serde_json::to_vec(bind);
429 }
430
431 #[derive(Serialize)]
432 struct WithPeer<'a> {
433 #[serde(flatten)]
434 bind: &'a ModuleControlRequest,
435 #[serde(flatten)]
436 peer: &'a RouteBindPeer,
437 }
438 serde_json::to_vec(&WithPeer { bind, peer })
439}