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::peer_build`] on a
28/// `route.bind` opened by an attested production phone session.
29pub const PEER_BUILD_CAPABILITY: &str = "peer-build/v1";
30
31/// A target declares this to receive [`RouteBindPeer::caller`] on `route.bind`.
32pub const CALLER_ATTESTATION_CAPABILITY: &str = "caller-attestation/v1";
33
34/// Largest spawn or authority epoch exactly representable by all wire readers.
35pub const MAX_ATTESTATION_INTEGER: u64 = (1_u64 << 53) - 1;
36
37/// The purpose of the connection attested by the daemon. Only `Own` can grant
38/// automatic first-party access; unknown purposes must never be treated as own.
39#[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/// Evidence-backed program origin. Unknown strings establish no recognized origin.
52#[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/// Daemon-attested caller authority, captured once for this bind. Providers must
63/// require both `claim: own` and `first_party: true` before automatic grants.
64/// `declaration` is the approved entry for the receiving provider, not a request.
65#[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/// A caller identity that cannot round-trip exactly through every wire reader.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct CallerAttestationError {
86    field: &'static str,
87}
88
89impl CallerAttestationError {
90    /// The unsafe identity field: `spawn` or `authority_epoch`.
91    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    /// Constructs an attestation without a provider declaration. Both integer
106    /// identities must be representable exactly by JavaScript and Swift readers.
107    ///
108    /// External emitters can construct the non-exhaustive type and its enums:
109    ///
110    /// ```
111    /// use subc_protocol::peer::{CallerAttestation, CallerClaim, CallerOrigin, RouteBindPeer};
112    ///
113    /// let caller = CallerAttestation::new(
114    ///     "daemon", 1, 2, CallerClaim::Own, true, CallerOrigin::Release, "approved",
115    /// )?.with_declaration(serde_json::Map::new(), "entry-digest");
116    /// let peer = RouteBindPeer::new().with_caller(Some(caller));
117    /// let bytes = serde_json::to_vec(&peer)?;
118    /// let decoded: RouteBindPeer = serde_json::from_slice(&bytes)?;
119    /// assert_eq!(decoded, peer);
120    /// # Ok::<(), Box<dyn std::error::Error>>(())
121    /// ```
122    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    /// Adds the provider's approved entry and its digest together. The constructor
150    /// leaves both absent, so builders never fabricate one without the other.
151    #[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    // Check numeric bounds even on an incomplete object: rounding a future
180    // spawn or epoch must never turn it into a different authority identity.
181    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/// Whether the daemon could read the peer's identity from the kernel when it
207/// accepted the connection.
208///
209/// A value from a newer daemon decodes as [`ObservedPeerStatus::Unknown`],
210/// keeping its spelling. Readers must treat anything other than
211/// [`ObservedPeerStatus::Observed`] as carrying no peer facts.
212#[derive(Debug, Clone, PartialEq, Eq)]
213#[non_exhaustive]
214pub enum ObservedPeerStatus {
215    /// The daemon read the peer's user (and possibly more) at accept time.
216    Observed,
217    /// The connection offers no kernel peer identity (TCP, or a platform
218    /// without the primitive), or reading it failed.
219    Unobserved,
220    /// A status this crate does not know, kept with its spelling so it
221    /// re-encodes unchanged.
222    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/// What the daemon learned from the kernel about the process that opened the
246/// route, read once when its connection was accepted.
247///
248/// This is an observation, not an authorization: the route's principal is
249/// unchanged by it. `exe` is informational. `signing_id` is present only when
250/// the platform validated the process's code signature.
251#[non_exhaustive]
252#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
253pub struct ObservedPeer {
254    pub status: ObservedPeerStatus,
255    /// The peer's effective user id (macOS and Linux).
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub uid: Option<u32>,
258    /// The peer's user SID (Windows).
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub sid: Option<String>,
261    /// The peer's executable path, omitted when it could not be read.
262    #[serde(default, skip_serializing_if = "Option::is_none")]
263    pub exe: Option<String>,
264    /// The peer's code-signing identifier, present only for validly signed
265    /// code on a platform that checks it.
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub signing_id: Option<String>,
268}
269
270impl ObservedPeer {
271    /// A connection with no kernel peer identity: `{"status":"unobserved"}`.
272    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    /// An observed peer identified by its Unix user id.
283    pub fn observed_uid(uid: u32) -> Self {
284        Self {
285            status: ObservedPeerStatus::Observed,
286            uid: Some(uid),
287            ..Self::unobserved()
288        }
289    }
290
291    /// An observed peer identified by its Windows user SID.
292    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    /// Set or clear the executable path.
301    #[must_use]
302    pub fn with_exe(mut self, exe: Option<String>) -> Self {
303        self.exe = exe;
304        self
305    }
306
307    /// Set or clear the code-signing identifier.
308    #[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/// The daemon's statement that the route was opened over a connection it
316/// recognised, when the connection was made, as a verified operator app.
317///
318/// It reports a fact fixed at bind time and is never retracted on the route.
319/// It is not authority: a module still asks the daemon with `operator.confirm`
320/// before acting on the person's behalf, and the daemon decides.
321#[non_exhaustive]
322#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
323pub struct OperatorApp {
324    /// The app's identifier in the daemon's compiled app table.
325    pub app: String,
326    /// The app's process id when its connection was made.
327    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/// The `route.bind` keys carried beside [`ModuleControlRequest::RouteBind`].
340///
341/// Keys are absent unless the target declared the matching capability, and an
342/// absent key is omitted, never `null`. Decoding ignores every other key, so a
343/// module reads this from the same body it decodes as the bind.
344#[non_exhaustive]
345#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
346pub struct RouteBindPeer {
347    /// Sent only to a target declaring [`OBSERVED_PEER_CAPABILITY`].
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub observed_peer: Option<ObservedPeer>,
350    /// Sent only to a target declaring [`OPERATOR_APP_CAPABILITY`], and only
351    /// when the daemon recognised the opening connection as an operator app.
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub operator_app: Option<OperatorApp>,
354    /// Sent only to targets declaring [`CALLER_ATTESTATION_CAPABILITY`]. An absent
355    /// or incomplete caller is treated as absent; unsafe integers are malformed.
356    #[serde(
357        default,
358        skip_serializing_if = "Option::is_none",
359        deserialize_with = "deserialize_caller"
360    )]
361    pub caller: Option<CallerAttestation>,
362    /// Sent only to a target declaring [`PEER_BUILD_CAPABILITY`], only when
363    /// the opener is `reserved:callosum` and its build claim was exactly
364    /// `production`. The daemon sends only `production`, never another value
365    /// or `null`; otherwise the key is absent.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub peer_build: Option<String>,
368}
369
370impl RouteBindPeer {
371    /// No peer keys: the bind keeps its legacy bytes.
372    pub fn new() -> Self {
373        Self::default()
374    }
375
376    /// Set or clear `observed_peer`.
377    #[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    /// Set or clear `operator_app`.
384    #[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    /// Set or clear the caller for a target declaring `caller-attestation/v1`.
391    #[must_use]
392    pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
393        self.caller = caller;
394        self
395    }
396
397    /// Set or clear `peer_build`.
398    #[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    /// Whether no peer key is present.
405    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
413/// Encodes a `route.bind` body with `peer`'s keys after the bind's own keys.
414///
415/// With an empty `peer` the bytes equal `serde_json::to_vec(bind)`. Fails for
416/// any request other than [`ModuleControlRequest::RouteBind`], because only a
417/// bind carries these keys.
418pub 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}