Skip to main content

subc_protocol/
peer.rs

1//! Daemon-observed facts about the process on the other end of a route's
2//! opening connection, relayed to the target module on `route.bind`.
3//!
4//! These keys sit outside the exhaustive [`ModuleControlRequest::RouteBind`]
5//! variant so that adding them changes no Rust construction site. A daemon
6//! encodes a bind with [`encode_route_bind`], which appends them after the
7//! variant's own keys; a module decodes the same body twice, once as
8//! [`ModuleControlRequest`] and once as [`RouteBindPeer`].
9//!
10//! Each key is sent only to a target declaring its capability in
11//! `capabilities.provides`, and a target declaring none receives exactly
12//! the bytes it received before these keys existed.
13
14use serde::{ser::Error as _, Deserialize, Deserializer, Serialize, Serializer};
15
16use crate::session::ModuleControlRequest;
17
18/// Declaring this in `capabilities.provides` asks the daemon for
19/// [`RouteBindPeer::observed_peer`] on every `route.bind`.
20pub const OBSERVED_PEER_CAPABILITY: &str = "observed-peer/v1";
21
22/// Declaring this in `capabilities.provides` asks the daemon for
23/// [`RouteBindPeer::operator_app`] on a `route.bind` whose route was opened by
24/// a recognised operator app.
25pub const OPERATOR_APP_CAPABILITY: &str = "operator-app/v1";
26
27/// A target declares this to receive [`RouteBindPeer::caller`] on `route.bind`.
28pub const CALLER_ATTESTATION_CAPABILITY: &str = "caller-attestation/v1";
29
30/// Largest spawn or authority epoch exactly representable by all wire readers.
31pub const MAX_ATTESTATION_INTEGER: u64 = (1_u64 << 53) - 1;
32
33/// The purpose of the connection attested by the daemon. Only `Own` can grant
34/// automatic first-party access; unknown purposes must never be treated as own.
35#[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/// Evidence-backed program origin. Unknown strings establish no recognized origin.
48#[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/// Daemon-attested caller authority, captured once for this bind. Providers must
59/// require both `claim: own` and `first_party: true` before automatic grants.
60/// `declaration` is the approved entry for the receiving provider, not a request.
61#[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/// A caller identity that cannot round-trip exactly through every wire reader.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct CallerAttestationError {
82    field: &'static str,
83}
84
85impl CallerAttestationError {
86    /// The unsafe identity field: `spawn` or `authority_epoch`.
87    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    /// Constructs an attestation without a provider declaration. Both integer
102    /// identities must be representable exactly by JavaScript and Swift readers.
103    ///
104    /// External emitters can construct the non-exhaustive type and its enums:
105    ///
106    /// ```
107    /// use subc_protocol::peer::{CallerAttestation, CallerClaim, CallerOrigin, RouteBindPeer};
108    ///
109    /// let caller = CallerAttestation::new(
110    ///     "daemon", 1, 2, CallerClaim::Own, true, CallerOrigin::Release, "approved",
111    /// )?.with_declaration(serde_json::Map::new(), "entry-digest");
112    /// let peer = RouteBindPeer::new().with_caller(Some(caller));
113    /// let bytes = serde_json::to_vec(&peer)?;
114    /// let decoded: RouteBindPeer = serde_json::from_slice(&bytes)?;
115    /// assert_eq!(decoded, peer);
116    /// # Ok::<(), Box<dyn std::error::Error>>(())
117    /// ```
118    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    /// Adds the provider's approved entry and its digest together. The constructor
146    /// leaves both absent, so builders never fabricate one without the other.
147    #[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    // Check numeric bounds even on an incomplete object: rounding a future
176    // spawn or epoch must never turn it into a different authority identity.
177    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/// Whether the daemon could read the peer's identity from the kernel when it
203/// accepted the connection.
204///
205/// A value from a newer daemon decodes as [`ObservedPeerStatus::Unknown`],
206/// keeping its spelling. Readers must treat anything other than
207/// [`ObservedPeerStatus::Observed`] as carrying no peer facts.
208#[derive(Debug, Clone, PartialEq, Eq)]
209#[non_exhaustive]
210pub enum ObservedPeerStatus {
211    /// The daemon read the peer's user (and possibly more) at accept time.
212    Observed,
213    /// The connection offers no kernel peer identity (TCP, or a platform
214    /// without the primitive), or reading it failed.
215    Unobserved,
216    /// A status this crate does not know, kept with its spelling so it
217    /// re-encodes unchanged.
218    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/// What the daemon learned from the kernel about the process that opened the
242/// route, read once when its connection was accepted.
243///
244/// This is an observation, not an authorization: the route's principal is
245/// unchanged by it. `exe` is informational. `signing_id` is present only when
246/// the platform validated the process's code signature.
247#[non_exhaustive]
248#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
249pub struct ObservedPeer {
250    pub status: ObservedPeerStatus,
251    /// The peer's effective user id (macOS and Linux).
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub uid: Option<u32>,
254    /// The peer's user SID (Windows).
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub sid: Option<String>,
257    /// The peer's executable path, omitted when it could not be read.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub exe: Option<String>,
260    /// The peer's code-signing identifier, present only for validly signed
261    /// code on a platform that checks it.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub signing_id: Option<String>,
264}
265
266impl ObservedPeer {
267    /// A connection with no kernel peer identity: `{"status":"unobserved"}`.
268    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    /// An observed peer identified by its Unix user id.
279    pub fn observed_uid(uid: u32) -> Self {
280        Self {
281            status: ObservedPeerStatus::Observed,
282            uid: Some(uid),
283            ..Self::unobserved()
284        }
285    }
286
287    /// An observed peer identified by its Windows user SID.
288    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    /// Set or clear the executable path.
297    #[must_use]
298    pub fn with_exe(mut self, exe: Option<String>) -> Self {
299        self.exe = exe;
300        self
301    }
302
303    /// Set or clear the code-signing identifier.
304    #[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/// The daemon's statement that the route was opened over a connection it
312/// recognised, when the connection was made, as a verified operator app.
313///
314/// It reports a fact fixed at bind time and is never retracted on the route.
315/// It is not authority: a module still asks the daemon with `operator.confirm`
316/// before acting on the person's behalf, and the daemon decides.
317#[non_exhaustive]
318#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
319pub struct OperatorApp {
320    /// The app's identifier in the daemon's compiled app table.
321    pub app: String,
322    /// The app's process id when its connection was made.
323    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/// The `route.bind` keys carried beside [`ModuleControlRequest::RouteBind`].
336///
337/// Keys are absent unless the target declared the matching capability, and an
338/// absent key is omitted, never `null`. Decoding ignores every other key, so a
339/// module reads this from the same body it decodes as the bind.
340#[non_exhaustive]
341#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
342pub struct RouteBindPeer {
343    /// Sent only to a target declaring [`OBSERVED_PEER_CAPABILITY`].
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub observed_peer: Option<ObservedPeer>,
346    /// Sent only to a target declaring [`OPERATOR_APP_CAPABILITY`], and only
347    /// when the daemon recognised the opening connection as an operator app.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub operator_app: Option<OperatorApp>,
350    /// Sent only to targets declaring [`CALLER_ATTESTATION_CAPABILITY`]. An absent
351    /// or incomplete caller is treated as absent; unsafe integers are malformed.
352    #[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    /// No peer keys: the bind keeps its legacy bytes.
362    pub fn new() -> Self {
363        Self::default()
364    }
365
366    /// Set or clear `observed_peer`.
367    #[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    /// Set or clear `operator_app`.
374    #[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    /// Set or clear the caller for a target declaring `caller-attestation/v1`.
381    #[must_use]
382    pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
383        self.caller = caller;
384        self
385    }
386
387    /// Whether no peer key is present.
388    pub fn is_empty(&self) -> bool {
389        self.observed_peer.is_none() && self.operator_app.is_none() && self.caller.is_none()
390    }
391}
392
393/// Encodes a `route.bind` body with `peer`'s keys after the bind's own keys.
394///
395/// With an empty `peer` the bytes equal `serde_json::to_vec(bind)`. Fails for
396/// any request other than [`ModuleControlRequest::RouteBind`], because only a
397/// bind carries these keys.
398pub 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}