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 CALLER_ATTESTATION_CAPABILITY: &str = "caller-attestation/v1";
29
30pub const MAX_ATTESTATION_INTEGER: u64 = (1_u64 << 53) - 1;
32
33#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
36#[serde(rename_all = "snake_case")]
37#[non_exhaustive]
38pub enum CallerClaim {
39 Own,
40 Brokered,
41 Relay,
42 Legacy,
43 #[serde(other)]
44 Unknown,
45}
46
47#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
49#[serde(rename_all = "snake_case")]
50#[non_exhaustive]
51pub enum CallerOrigin {
52 Release,
53 Development,
54 #[serde(other)]
55 Other,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
62#[non_exhaustive]
63pub struct CallerAttestation {
64 pub incarnation: String,
65 #[serde(deserialize_with = "deserialize_attestation_integer")]
66 pub spawn: u64,
67 #[serde(deserialize_with = "deserialize_attestation_integer")]
68 pub authority_epoch: u64,
69 pub claim: CallerClaim,
70 pub first_party: bool,
71 pub origin: CallerOrigin,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub declaration: Option<serde_json::Map<String, serde_json::Value>>,
74 pub approved_declarations_digest: String,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub declaration_digest: Option<String>,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct CallerAttestationError {
82 field: &'static str,
83}
84
85impl CallerAttestationError {
86 pub fn field(&self) -> &'static str {
88 self.field
89 }
90}
91
92impl std::fmt::Display for CallerAttestationError {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 write!(f, "caller {} exceeds 2^53-1", self.field)
95 }
96}
97
98impl std::error::Error for CallerAttestationError {}
99
100impl CallerAttestation {
101 pub fn new(
119 incarnation: impl Into<String>,
120 spawn: u64,
121 authority_epoch: u64,
122 claim: CallerClaim,
123 first_party: bool,
124 origin: CallerOrigin,
125 approved_declarations_digest: impl Into<String>,
126 ) -> Result<Self, CallerAttestationError> {
127 for (field, value) in [("spawn", spawn), ("authority_epoch", authority_epoch)] {
128 if value > MAX_ATTESTATION_INTEGER {
129 return Err(CallerAttestationError { field });
130 }
131 }
132 Ok(Self {
133 incarnation: incarnation.into(),
134 spawn,
135 authority_epoch,
136 claim,
137 first_party,
138 origin,
139 declaration: None,
140 approved_declarations_digest: approved_declarations_digest.into(),
141 declaration_digest: None,
142 })
143 }
144
145 #[must_use]
148 pub fn with_declaration(
149 mut self,
150 declaration: serde_json::Map<String, serde_json::Value>,
151 digest: impl Into<String>,
152 ) -> Self {
153 self.declaration = Some(declaration);
154 self.declaration_digest = Some(digest.into());
155 self
156 }
157}
158
159fn deserialize_attestation_integer<'de, D: Deserializer<'de>>(decoder: D) -> Result<u64, D::Error> {
160 let value = u64::deserialize(decoder)?;
161 if value > MAX_ATTESTATION_INTEGER {
162 return Err(serde::de::Error::custom(
163 "attestation integer exceeds 2^53-1",
164 ));
165 }
166 Ok(value)
167}
168
169fn deserialize_caller<'de, D: Deserializer<'de>>(
170 decoder: D,
171) -> Result<Option<CallerAttestation>, D::Error> {
172 let Some(value) = Option::<serde_json::Value>::deserialize(decoder)? else {
173 return Ok(None);
174 };
175 for field in ["spawn", "authority_epoch"] {
178 if let Some(integer) = value.get(field) {
179 deserialize_attestation_integer(integer).map_err(serde::de::Error::custom)?;
180 }
181 }
182 if value.is_object()
183 && [
184 "incarnation",
185 "spawn",
186 "authority_epoch",
187 "claim",
188 "first_party",
189 "origin",
190 "approved_declarations_digest",
191 ]
192 .iter()
193 .any(|field| value.get(field).is_none())
194 {
195 return Ok(None);
196 }
197 serde_json::from_value(value)
198 .map(Some)
199 .map_err(serde::de::Error::custom)
200}
201
202#[derive(Debug, Clone, PartialEq, Eq)]
209#[non_exhaustive]
210pub enum ObservedPeerStatus {
211 Observed,
213 Unobserved,
216 Unknown(String),
219}
220
221impl Serialize for ObservedPeerStatus {
222 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
223 serializer.serialize_str(match self {
224 Self::Observed => "observed",
225 Self::Unobserved => "unobserved",
226 Self::Unknown(value) => value,
227 })
228 }
229}
230
231impl<'de> Deserialize<'de> for ObservedPeerStatus {
232 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
233 Ok(match String::deserialize(deserializer)?.as_str() {
234 "observed" => Self::Observed,
235 "unobserved" => Self::Unobserved,
236 value => Self::Unknown(value.to_owned()),
237 })
238 }
239}
240
241#[non_exhaustive]
248#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
249pub struct ObservedPeer {
250 pub status: ObservedPeerStatus,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub uid: Option<u32>,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub sid: Option<String>,
257 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub exe: Option<String>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub signing_id: Option<String>,
264}
265
266impl ObservedPeer {
267 pub fn unobserved() -> Self {
269 Self {
270 status: ObservedPeerStatus::Unobserved,
271 uid: None,
272 sid: None,
273 exe: None,
274 signing_id: None,
275 }
276 }
277
278 pub fn observed_uid(uid: u32) -> Self {
280 Self {
281 status: ObservedPeerStatus::Observed,
282 uid: Some(uid),
283 ..Self::unobserved()
284 }
285 }
286
287 pub fn observed_sid(sid: impl Into<String>) -> Self {
289 Self {
290 status: ObservedPeerStatus::Observed,
291 sid: Some(sid.into()),
292 ..Self::unobserved()
293 }
294 }
295
296 #[must_use]
298 pub fn with_exe(mut self, exe: Option<String>) -> Self {
299 self.exe = exe;
300 self
301 }
302
303 #[must_use]
305 pub fn with_signing_id(mut self, signing_id: Option<String>) -> Self {
306 self.signing_id = signing_id;
307 self
308 }
309}
310
311#[non_exhaustive]
318#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
319pub struct OperatorApp {
320 pub app: String,
322 pub pid: u32,
324}
325
326impl OperatorApp {
327 pub fn new(app: impl Into<String>, pid: u32) -> Self {
328 Self {
329 app: app.into(),
330 pid,
331 }
332 }
333}
334
335#[non_exhaustive]
341#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
342pub struct RouteBindPeer {
343 #[serde(default, skip_serializing_if = "Option::is_none")]
345 pub observed_peer: Option<ObservedPeer>,
346 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub operator_app: Option<OperatorApp>,
350 #[serde(
353 default,
354 skip_serializing_if = "Option::is_none",
355 deserialize_with = "deserialize_caller"
356 )]
357 pub caller: Option<CallerAttestation>,
358}
359
360impl RouteBindPeer {
361 pub fn new() -> Self {
363 Self::default()
364 }
365
366 #[must_use]
368 pub fn with_observed_peer(mut self, observed_peer: Option<ObservedPeer>) -> Self {
369 self.observed_peer = observed_peer;
370 self
371 }
372
373 #[must_use]
375 pub fn with_operator_app(mut self, operator_app: Option<OperatorApp>) -> Self {
376 self.operator_app = operator_app;
377 self
378 }
379
380 #[must_use]
382 pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
383 self.caller = caller;
384 self
385 }
386
387 pub fn is_empty(&self) -> bool {
389 self.observed_peer.is_none() && self.operator_app.is_none() && self.caller.is_none()
390 }
391}
392
393pub fn encode_route_bind(
399 bind: &ModuleControlRequest,
400 peer: &RouteBindPeer,
401) -> serde_json::Result<Vec<u8>> {
402 if !matches!(bind, ModuleControlRequest::RouteBind { .. }) {
403 return Err(serde_json::Error::custom(
404 "peer keys can only be added to a route.bind request",
405 ));
406 }
407 if peer.is_empty() {
408 return serde_json::to_vec(bind);
409 }
410
411 #[derive(Serialize)]
412 struct WithPeer<'a> {
413 #[serde(flatten)]
414 bind: &'a ModuleControlRequest,
415 #[serde(flatten)]
416 peer: &'a RouteBindPeer,
417 }
418 serde_json::to_vec(&WithPeer { bind, peer })
419}