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 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub settings_credentials: Option<SettingsCredentials>,
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
98#[non_exhaustive]
99pub struct SettingsCredentials {
100 #[serde(deserialize_with = "deserialize_attestation_integer")]
101 pub generation: u64,
102 pub refs: Vec<String>,
103}
104
105impl SettingsCredentials {
106 pub fn new<R: Into<String>>(
109 generation: u64,
110 refs: impl IntoIterator<Item = R>,
111 ) -> Result<Self, CallerAttestationError> {
112 if generation > MAX_ATTESTATION_INTEGER {
113 return Err(CallerAttestationError {
114 field: "generation",
115 });
116 }
117 let mut refs: Vec<String> = refs.into_iter().map(Into::into).collect();
118 refs.sort();
119 refs.dedup();
120 Ok(Self { generation, refs })
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct CallerAttestationError {
127 field: &'static str,
128}
129
130impl CallerAttestationError {
131 pub fn field(&self) -> &'static str {
133 self.field
134 }
135}
136
137impl std::fmt::Display for CallerAttestationError {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 write!(f, "caller {} exceeds 2^53-1", self.field)
140 }
141}
142
143impl std::error::Error for CallerAttestationError {}
144
145impl CallerAttestation {
146 pub fn new(
164 incarnation: impl Into<String>,
165 spawn: u64,
166 authority_epoch: u64,
167 claim: CallerClaim,
168 first_party: bool,
169 origin: CallerOrigin,
170 approved_declarations_digest: impl Into<String>,
171 ) -> Result<Self, CallerAttestationError> {
172 for (field, value) in [("spawn", spawn), ("authority_epoch", authority_epoch)] {
173 if value > MAX_ATTESTATION_INTEGER {
174 return Err(CallerAttestationError { field });
175 }
176 }
177 Ok(Self {
178 incarnation: incarnation.into(),
179 spawn,
180 authority_epoch,
181 claim,
182 first_party,
183 origin,
184 declaration: None,
185 approved_declarations_digest: approved_declarations_digest.into(),
186 declaration_digest: None,
187 settings_credentials: None,
188 })
189 }
190
191 #[must_use]
194 pub fn with_declaration(
195 mut self,
196 declaration: serde_json::Map<String, serde_json::Value>,
197 digest: impl Into<String>,
198 ) -> Self {
199 self.declaration = Some(declaration);
200 self.declaration_digest = Some(digest.into());
201 self
202 }
203
204 #[must_use]
206 pub fn with_settings_credentials(mut self, credentials: SettingsCredentials) -> Self {
207 self.settings_credentials = Some(credentials);
208 self
209 }
210}
211
212fn deserialize_attestation_integer<'de, D: Deserializer<'de>>(decoder: D) -> Result<u64, D::Error> {
213 let value = u64::deserialize(decoder)?;
214 if value > MAX_ATTESTATION_INTEGER {
215 return Err(serde::de::Error::custom(
216 "attestation integer exceeds 2^53-1",
217 ));
218 }
219 Ok(value)
220}
221
222fn deserialize_caller<'de, D: Deserializer<'de>>(
223 decoder: D,
224) -> Result<Option<CallerAttestation>, D::Error> {
225 let Some(value) = Option::<serde_json::Value>::deserialize(decoder)? else {
226 return Ok(None);
227 };
228 for field in ["spawn", "authority_epoch"] {
231 if let Some(integer) = value.get(field) {
232 deserialize_attestation_integer(integer).map_err(serde::de::Error::custom)?;
233 }
234 }
235 if value.is_object()
236 && [
237 "incarnation",
238 "spawn",
239 "authority_epoch",
240 "claim",
241 "first_party",
242 "origin",
243 "approved_declarations_digest",
244 ]
245 .iter()
246 .any(|field| value.get(field).is_none())
247 {
248 return Ok(None);
249 }
250 serde_json::from_value(value)
251 .map(Some)
252 .map_err(serde::de::Error::custom)
253}
254
255#[derive(Debug, Clone, PartialEq, Eq)]
262#[non_exhaustive]
263pub enum ObservedPeerStatus {
264 Observed,
266 Unobserved,
269 Unknown(String),
272}
273
274impl Serialize for ObservedPeerStatus {
275 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
276 serializer.serialize_str(match self {
277 Self::Observed => "observed",
278 Self::Unobserved => "unobserved",
279 Self::Unknown(value) => value,
280 })
281 }
282}
283
284impl<'de> Deserialize<'de> for ObservedPeerStatus {
285 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
286 Ok(match String::deserialize(deserializer)?.as_str() {
287 "observed" => Self::Observed,
288 "unobserved" => Self::Unobserved,
289 value => Self::Unknown(value.to_owned()),
290 })
291 }
292}
293
294#[non_exhaustive]
301#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
302pub struct ObservedPeer {
303 pub status: ObservedPeerStatus,
304 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub uid: Option<u32>,
307 #[serde(default, skip_serializing_if = "Option::is_none")]
309 pub sid: Option<String>,
310 #[serde(default, skip_serializing_if = "Option::is_none")]
312 pub exe: Option<String>,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub signing_id: Option<String>,
317}
318
319impl ObservedPeer {
320 pub fn unobserved() -> Self {
322 Self {
323 status: ObservedPeerStatus::Unobserved,
324 uid: None,
325 sid: None,
326 exe: None,
327 signing_id: None,
328 }
329 }
330
331 pub fn observed_uid(uid: u32) -> Self {
333 Self {
334 status: ObservedPeerStatus::Observed,
335 uid: Some(uid),
336 ..Self::unobserved()
337 }
338 }
339
340 pub fn observed_sid(sid: impl Into<String>) -> Self {
342 Self {
343 status: ObservedPeerStatus::Observed,
344 sid: Some(sid.into()),
345 ..Self::unobserved()
346 }
347 }
348
349 #[must_use]
351 pub fn with_exe(mut self, exe: Option<String>) -> Self {
352 self.exe = exe;
353 self
354 }
355
356 #[must_use]
358 pub fn with_signing_id(mut self, signing_id: Option<String>) -> Self {
359 self.signing_id = signing_id;
360 self
361 }
362}
363
364#[non_exhaustive]
371#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
372pub struct OperatorApp {
373 pub app: String,
375 pub pid: u32,
377}
378
379impl OperatorApp {
380 pub fn new(app: impl Into<String>, pid: u32) -> Self {
381 Self {
382 app: app.into(),
383 pid,
384 }
385 }
386}
387
388#[non_exhaustive]
394#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
395pub struct RouteBindPeer {
396 #[serde(default, skip_serializing_if = "Option::is_none")]
398 pub observed_peer: Option<ObservedPeer>,
399 #[serde(default, skip_serializing_if = "Option::is_none")]
402 pub operator_app: Option<OperatorApp>,
403 #[serde(
406 default,
407 skip_serializing_if = "Option::is_none",
408 deserialize_with = "deserialize_caller"
409 )]
410 pub caller: Option<CallerAttestation>,
411 #[serde(default, skip_serializing_if = "Option::is_none")]
416 pub peer_build: Option<String>,
417}
418
419impl RouteBindPeer {
420 pub fn new() -> Self {
422 Self::default()
423 }
424
425 #[must_use]
427 pub fn with_observed_peer(mut self, observed_peer: Option<ObservedPeer>) -> Self {
428 self.observed_peer = observed_peer;
429 self
430 }
431
432 #[must_use]
434 pub fn with_operator_app(mut self, operator_app: Option<OperatorApp>) -> Self {
435 self.operator_app = operator_app;
436 self
437 }
438
439 #[must_use]
441 pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
442 self.caller = caller;
443 self
444 }
445
446 #[must_use]
448 pub fn with_peer_build(mut self, peer_build: Option<String>) -> Self {
449 self.peer_build = peer_build;
450 self
451 }
452
453 pub fn is_empty(&self) -> bool {
455 self.observed_peer.is_none()
456 && self.operator_app.is_none()
457 && self.caller.is_none()
458 && self.peer_build.is_none()
459 }
460}
461
462pub fn encode_route_bind(
468 bind: &ModuleControlRequest,
469 peer: &RouteBindPeer,
470) -> serde_json::Result<Vec<u8>> {
471 if !matches!(bind, ModuleControlRequest::RouteBind { .. }) {
472 return Err(serde_json::Error::custom(
473 "peer keys can only be added to a route.bind request",
474 ));
475 }
476 if peer.is_empty() {
477 return serde_json::to_vec(bind);
478 }
479
480 #[derive(Serialize)]
481 struct WithPeer<'a> {
482 #[serde(flatten)]
483 bind: &'a ModuleControlRequest,
484 #[serde(flatten)]
485 peer: &'a RouteBindPeer,
486 }
487 serde_json::to_vec(&WithPeer { bind, peer })
488}