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    /// Present only on a bind to the vault, for a module on a stamped install.
82    /// See [`SettingsCredentials`].
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub settings_credentials: Option<SettingsCredentials>,
85}
86
87/// The vault references a module's approved settings name, attested on a
88/// `route.bind` to the vault so it can serve exactly those keys to that module.
89///
90/// `refs` lists every `vault_ref` under an `x-ck-kind: credential_ref` value in
91/// the module's approved effective settings, without duplicates and sorted
92/// bytewise. `generation` is the configuration store's approved revision they
93/// were read from; it only rises, and two attestations with the same generation
94/// carry the same `refs`. The daemon leaves the member out on an install whose
95/// settings are not approved (an unstamped install), so its absence means "no
96/// approved settings", never "no keys"; an empty `refs` means "no keys".
97#[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    /// Sorts and deduplicates `refs`. Refuses a generation above 2^53-1, which
107    /// JavaScript and Swift readers could not represent exactly.
108    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/// A caller identity that cannot round-trip exactly through every wire reader.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct CallerAttestationError {
127    field: &'static str,
128}
129
130impl CallerAttestationError {
131    /// The unsafe identity field: `spawn`, `authority_epoch` or `generation`.
132    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    /// Constructs an attestation without a provider declaration. Both integer
147    /// identities must be representable exactly by JavaScript and Swift readers.
148    ///
149    /// External emitters can construct the non-exhaustive type and its enums:
150    ///
151    /// ```
152    /// use subc_protocol::peer::{CallerAttestation, CallerClaim, CallerOrigin, RouteBindPeer};
153    ///
154    /// let caller = CallerAttestation::new(
155    ///     "daemon", 1, 2, CallerClaim::Own, true, CallerOrigin::Release, "approved",
156    /// )?.with_declaration(serde_json::Map::new(), "entry-digest");
157    /// let peer = RouteBindPeer::new().with_caller(Some(caller));
158    /// let bytes = serde_json::to_vec(&peer)?;
159    /// let decoded: RouteBindPeer = serde_json::from_slice(&bytes)?;
160    /// assert_eq!(decoded, peer);
161    /// # Ok::<(), Box<dyn std::error::Error>>(())
162    /// ```
163    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    /// Adds the provider's approved entry and its digest together. The constructor
192    /// leaves both absent, so builders never fabricate one without the other.
193    #[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    /// Adds the vault references the module's approved settings name.
205    #[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    // Check numeric bounds even on an incomplete object: rounding a future
229    // spawn or epoch must never turn it into a different authority identity.
230    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/// Whether the daemon could read the peer's identity from the kernel when it
256/// accepted the connection.
257///
258/// A value from a newer daemon decodes as [`ObservedPeerStatus::Unknown`],
259/// keeping its spelling. Readers must treat anything other than
260/// [`ObservedPeerStatus::Observed`] as carrying no peer facts.
261#[derive(Debug, Clone, PartialEq, Eq)]
262#[non_exhaustive]
263pub enum ObservedPeerStatus {
264    /// The daemon read the peer's user (and possibly more) at accept time.
265    Observed,
266    /// The connection offers no kernel peer identity (TCP, or a platform
267    /// without the primitive), or reading it failed.
268    Unobserved,
269    /// A status this crate does not know, kept with its spelling so it
270    /// re-encodes unchanged.
271    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/// What the daemon learned from the kernel about the process that opened the
295/// route, read once when its connection was accepted.
296///
297/// This is an observation, not an authorization: the route's principal is
298/// unchanged by it. `exe` is informational. `signing_id` is present only when
299/// the platform validated the process's code signature.
300#[non_exhaustive]
301#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
302pub struct ObservedPeer {
303    pub status: ObservedPeerStatus,
304    /// The peer's effective user id (macOS and Linux).
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub uid: Option<u32>,
307    /// The peer's user SID (Windows).
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub sid: Option<String>,
310    /// The peer's executable path, omitted when it could not be read.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub exe: Option<String>,
313    /// The peer's code-signing identifier, present only for validly signed
314    /// code on a platform that checks it.
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub signing_id: Option<String>,
317}
318
319impl ObservedPeer {
320    /// A connection with no kernel peer identity: `{"status":"unobserved"}`.
321    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    /// An observed peer identified by its Unix user id.
332    pub fn observed_uid(uid: u32) -> Self {
333        Self {
334            status: ObservedPeerStatus::Observed,
335            uid: Some(uid),
336            ..Self::unobserved()
337        }
338    }
339
340    /// An observed peer identified by its Windows user SID.
341    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    /// Set or clear the executable path.
350    #[must_use]
351    pub fn with_exe(mut self, exe: Option<String>) -> Self {
352        self.exe = exe;
353        self
354    }
355
356    /// Set or clear the code-signing identifier.
357    #[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/// The daemon's statement that the route was opened over a connection it
365/// recognised, when the connection was made, as a verified operator app.
366///
367/// It reports a fact fixed at bind time and is never retracted on the route.
368/// It is not authority: a module still asks the daemon with `operator.confirm`
369/// before acting on the person's behalf, and the daemon decides.
370#[non_exhaustive]
371#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
372pub struct OperatorApp {
373    /// The app's identifier in the daemon's compiled app table.
374    pub app: String,
375    /// The app's process id when its connection was made.
376    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/// The `route.bind` keys carried beside [`ModuleControlRequest::RouteBind`].
389///
390/// Keys are absent unless the target declared the matching capability, and an
391/// absent key is omitted, never `null`. Decoding ignores every other key, so a
392/// module reads this from the same body it decodes as the bind.
393#[non_exhaustive]
394#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
395pub struct RouteBindPeer {
396    /// Sent only to a target declaring [`OBSERVED_PEER_CAPABILITY`].
397    #[serde(default, skip_serializing_if = "Option::is_none")]
398    pub observed_peer: Option<ObservedPeer>,
399    /// Sent only to a target declaring [`OPERATOR_APP_CAPABILITY`], and only
400    /// when the daemon recognised the opening connection as an operator app.
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub operator_app: Option<OperatorApp>,
403    /// Sent only to targets declaring [`CALLER_ATTESTATION_CAPABILITY`]. An absent
404    /// or incomplete caller is treated as absent; unsafe integers are malformed.
405    #[serde(
406        default,
407        skip_serializing_if = "Option::is_none",
408        deserialize_with = "deserialize_caller"
409    )]
410    pub caller: Option<CallerAttestation>,
411    /// Sent only to a target declaring [`PEER_BUILD_CAPABILITY`], only when
412    /// the opener is `reserved:callosum` and its build claim was exactly
413    /// `production`. The daemon sends only `production`, never another value
414    /// or `null`; otherwise the key is absent.
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub peer_build: Option<String>,
417}
418
419impl RouteBindPeer {
420    /// No peer keys: the bind keeps its legacy bytes.
421    pub fn new() -> Self {
422        Self::default()
423    }
424
425    /// Set or clear `observed_peer`.
426    #[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    /// Set or clear `operator_app`.
433    #[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    /// Set or clear the caller for a target declaring `caller-attestation/v1`.
440    #[must_use]
441    pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
442        self.caller = caller;
443        self
444    }
445
446    /// Set or clear `peer_build`.
447    #[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    /// Whether no peer key is present.
454    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
462/// Encodes a `route.bind` body with `peer`'s keys after the bind's own keys.
463///
464/// With an empty `peer` the bytes equal `serde_json::to_vec(bind)`. Fails for
465/// any request other than [`ModuleControlRequest::RouteBind`], because only a
466/// bind carries these keys.
467pub 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}