subc-protocol 0.37.0

Shared wire contract for subc <-> modules: the 21-byte envelope, the Frame (header + opaque body), channel-0 control bodies, route.bind/RouteTarget session shapes, and the capability manifest. Single source of truth, depended on by subc-core and AFT.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Daemon-observed facts about the process on the other end of a route's
//! opening connection, relayed to the target module on `route.bind`.
//!
//! These keys sit outside the exhaustive [`ModuleControlRequest::RouteBind`]
//! variant so that adding them changes no Rust construction site. A daemon
//! encodes a bind with [`encode_route_bind`], which appends them after the
//! variant's own keys; a module decodes the same body twice, once as
//! [`ModuleControlRequest`] and once as [`RouteBindPeer`].
//!
//! Each key is sent only to a target declaring its capability in
//! `capabilities.provides`, and a target declaring none receives exactly
//! the bytes it received before these keys existed.

use serde::{ser::Error as _, Deserialize, Deserializer, Serialize, Serializer};

use crate::session::ModuleControlRequest;

/// Declaring this in `capabilities.provides` asks the daemon for
/// [`RouteBindPeer::observed_peer`] on every `route.bind`.
pub const OBSERVED_PEER_CAPABILITY: &str = "observed-peer/v1";

/// Declaring this in `capabilities.provides` asks the daemon for
/// [`RouteBindPeer::operator_app`] on a `route.bind` whose route was opened by
/// a recognised operator app.
pub const OPERATOR_APP_CAPABILITY: &str = "operator-app/v1";

/// A target declares this to receive [`RouteBindPeer::caller`] on `route.bind`.
pub const CALLER_ATTESTATION_CAPABILITY: &str = "caller-attestation/v1";

/// Largest spawn or authority epoch exactly representable by all wire readers.
pub const MAX_ATTESTATION_INTEGER: u64 = (1_u64 << 53) - 1;

/// The purpose of the connection attested by the daemon. Only `Own` can grant
/// automatic first-party access; unknown purposes must never be treated as own.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CallerClaim {
    Own,
    Brokered,
    Relay,
    Legacy,
    #[serde(other)]
    Unknown,
}

/// Evidence-backed program origin. Unknown strings establish no recognized origin.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CallerOrigin {
    Release,
    Development,
    #[serde(other)]
    Other,
}

/// Daemon-attested caller authority, captured once for this bind. Providers must
/// require both `claim: own` and `first_party: true` before automatic grants.
/// `declaration` is the approved entry for the receiving provider, not a request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct CallerAttestation {
    pub incarnation: String,
    #[serde(deserialize_with = "deserialize_attestation_integer")]
    pub spawn: u64,
    #[serde(deserialize_with = "deserialize_attestation_integer")]
    pub authority_epoch: u64,
    pub claim: CallerClaim,
    pub first_party: bool,
    pub origin: CallerOrigin,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declaration: Option<serde_json::Map<String, serde_json::Value>>,
    pub approved_declarations_digest: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declaration_digest: Option<String>,
}

/// A caller identity that cannot round-trip exactly through every wire reader.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallerAttestationError {
    field: &'static str,
}

impl CallerAttestationError {
    /// The unsafe identity field: `spawn` or `authority_epoch`.
    pub fn field(&self) -> &'static str {
        self.field
    }
}

impl std::fmt::Display for CallerAttestationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "caller {} exceeds 2^53-1", self.field)
    }
}

impl std::error::Error for CallerAttestationError {}

impl CallerAttestation {
    /// Constructs an attestation without a provider declaration. Both integer
    /// identities must be representable exactly by JavaScript and Swift readers.
    ///
    /// External emitters can construct the non-exhaustive type and its enums:
    ///
    /// ```
    /// use subc_protocol::peer::{CallerAttestation, CallerClaim, CallerOrigin, RouteBindPeer};
    ///
    /// let caller = CallerAttestation::new(
    ///     "daemon", 1, 2, CallerClaim::Own, true, CallerOrigin::Release, "approved",
    /// )?.with_declaration(serde_json::Map::new(), "entry-digest");
    /// let peer = RouteBindPeer::new().with_caller(Some(caller));
    /// let bytes = serde_json::to_vec(&peer)?;
    /// let decoded: RouteBindPeer = serde_json::from_slice(&bytes)?;
    /// assert_eq!(decoded, peer);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(
        incarnation: impl Into<String>,
        spawn: u64,
        authority_epoch: u64,
        claim: CallerClaim,
        first_party: bool,
        origin: CallerOrigin,
        approved_declarations_digest: impl Into<String>,
    ) -> Result<Self, CallerAttestationError> {
        for (field, value) in [("spawn", spawn), ("authority_epoch", authority_epoch)] {
            if value > MAX_ATTESTATION_INTEGER {
                return Err(CallerAttestationError { field });
            }
        }
        Ok(Self {
            incarnation: incarnation.into(),
            spawn,
            authority_epoch,
            claim,
            first_party,
            origin,
            declaration: None,
            approved_declarations_digest: approved_declarations_digest.into(),
            declaration_digest: None,
        })
    }

    /// Adds the provider's approved entry and its digest together. The constructor
    /// leaves both absent, so builders never fabricate one without the other.
    #[must_use]
    pub fn with_declaration(
        mut self,
        declaration: serde_json::Map<String, serde_json::Value>,
        digest: impl Into<String>,
    ) -> Self {
        self.declaration = Some(declaration);
        self.declaration_digest = Some(digest.into());
        self
    }
}

fn deserialize_attestation_integer<'de, D: Deserializer<'de>>(decoder: D) -> Result<u64, D::Error> {
    let value = u64::deserialize(decoder)?;
    if value > MAX_ATTESTATION_INTEGER {
        return Err(serde::de::Error::custom(
            "attestation integer exceeds 2^53-1",
        ));
    }
    Ok(value)
}

fn deserialize_caller<'de, D: Deserializer<'de>>(
    decoder: D,
) -> Result<Option<CallerAttestation>, D::Error> {
    let Some(value) = Option::<serde_json::Value>::deserialize(decoder)? else {
        return Ok(None);
    };
    // Check numeric bounds even on an incomplete object: rounding a future
    // spawn or epoch must never turn it into a different authority identity.
    for field in ["spawn", "authority_epoch"] {
        if let Some(integer) = value.get(field) {
            deserialize_attestation_integer(integer).map_err(serde::de::Error::custom)?;
        }
    }
    if value.is_object()
        && [
            "incarnation",
            "spawn",
            "authority_epoch",
            "claim",
            "first_party",
            "origin",
            "approved_declarations_digest",
        ]
        .iter()
        .any(|field| value.get(field).is_none())
    {
        return Ok(None);
    }
    serde_json::from_value(value)
        .map(Some)
        .map_err(serde::de::Error::custom)
}

/// Whether the daemon could read the peer's identity from the kernel when it
/// accepted the connection.
///
/// A value from a newer daemon decodes as [`ObservedPeerStatus::Unknown`],
/// keeping its spelling. Readers must treat anything other than
/// [`ObservedPeerStatus::Observed`] as carrying no peer facts.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ObservedPeerStatus {
    /// The daemon read the peer's user (and possibly more) at accept time.
    Observed,
    /// The connection offers no kernel peer identity (TCP, or a platform
    /// without the primitive), or reading it failed.
    Unobserved,
    /// A status this crate does not know, kept with its spelling so it
    /// re-encodes unchanged.
    Unknown(String),
}

impl Serialize for ObservedPeerStatus {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(match self {
            Self::Observed => "observed",
            Self::Unobserved => "unobserved",
            Self::Unknown(value) => value,
        })
    }
}

impl<'de> Deserialize<'de> for ObservedPeerStatus {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match String::deserialize(deserializer)?.as_str() {
            "observed" => Self::Observed,
            "unobserved" => Self::Unobserved,
            value => Self::Unknown(value.to_owned()),
        })
    }
}

/// What the daemon learned from the kernel about the process that opened the
/// route, read once when its connection was accepted.
///
/// This is an observation, not an authorization: the route's principal is
/// unchanged by it. `exe` is informational. `signing_id` is present only when
/// the platform validated the process's code signature.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ObservedPeer {
    pub status: ObservedPeerStatus,
    /// The peer's effective user id (macOS and Linux).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uid: Option<u32>,
    /// The peer's user SID (Windows).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sid: Option<String>,
    /// The peer's executable path, omitted when it could not be read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exe: Option<String>,
    /// The peer's code-signing identifier, present only for validly signed
    /// code on a platform that checks it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signing_id: Option<String>,
}

impl ObservedPeer {
    /// A connection with no kernel peer identity: `{"status":"unobserved"}`.
    pub fn unobserved() -> Self {
        Self {
            status: ObservedPeerStatus::Unobserved,
            uid: None,
            sid: None,
            exe: None,
            signing_id: None,
        }
    }

    /// An observed peer identified by its Unix user id.
    pub fn observed_uid(uid: u32) -> Self {
        Self {
            status: ObservedPeerStatus::Observed,
            uid: Some(uid),
            ..Self::unobserved()
        }
    }

    /// An observed peer identified by its Windows user SID.
    pub fn observed_sid(sid: impl Into<String>) -> Self {
        Self {
            status: ObservedPeerStatus::Observed,
            sid: Some(sid.into()),
            ..Self::unobserved()
        }
    }

    /// Set or clear the executable path.
    #[must_use]
    pub fn with_exe(mut self, exe: Option<String>) -> Self {
        self.exe = exe;
        self
    }

    /// Set or clear the code-signing identifier.
    #[must_use]
    pub fn with_signing_id(mut self, signing_id: Option<String>) -> Self {
        self.signing_id = signing_id;
        self
    }
}

/// The daemon's statement that the route was opened over a connection it
/// recognised, when the connection was made, as a verified operator app.
///
/// It reports a fact fixed at bind time and is never retracted on the route.
/// It is not authority: a module still asks the daemon with `operator.confirm`
/// before acting on the person's behalf, and the daemon decides.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct OperatorApp {
    /// The app's identifier in the daemon's compiled app table.
    pub app: String,
    /// The app's process id when its connection was made.
    pub pid: u32,
}

impl OperatorApp {
    pub fn new(app: impl Into<String>, pid: u32) -> Self {
        Self {
            app: app.into(),
            pid,
        }
    }
}

/// The `route.bind` keys carried beside [`ModuleControlRequest::RouteBind`].
///
/// Keys are absent unless the target declared the matching capability, and an
/// absent key is omitted, never `null`. Decoding ignores every other key, so a
/// module reads this from the same body it decodes as the bind.
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct RouteBindPeer {
    /// Sent only to a target declaring [`OBSERVED_PEER_CAPABILITY`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_peer: Option<ObservedPeer>,
    /// Sent only to a target declaring [`OPERATOR_APP_CAPABILITY`], and only
    /// when the daemon recognised the opening connection as an operator app.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operator_app: Option<OperatorApp>,
    /// Sent only to targets declaring [`CALLER_ATTESTATION_CAPABILITY`]. An absent
    /// or incomplete caller is treated as absent; unsafe integers are malformed.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_caller"
    )]
    pub caller: Option<CallerAttestation>,
}

impl RouteBindPeer {
    /// No peer keys: the bind keeps its legacy bytes.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set or clear `observed_peer`.
    #[must_use]
    pub fn with_observed_peer(mut self, observed_peer: Option<ObservedPeer>) -> Self {
        self.observed_peer = observed_peer;
        self
    }

    /// Set or clear `operator_app`.
    #[must_use]
    pub fn with_operator_app(mut self, operator_app: Option<OperatorApp>) -> Self {
        self.operator_app = operator_app;
        self
    }

    /// Set or clear the caller for a target declaring `caller-attestation/v1`.
    #[must_use]
    pub fn with_caller(mut self, caller: Option<CallerAttestation>) -> Self {
        self.caller = caller;
        self
    }

    /// Whether no peer key is present.
    pub fn is_empty(&self) -> bool {
        self.observed_peer.is_none() && self.operator_app.is_none() && self.caller.is_none()
    }
}

/// Encodes a `route.bind` body with `peer`'s keys after the bind's own keys.
///
/// With an empty `peer` the bytes equal `serde_json::to_vec(bind)`. Fails for
/// any request other than [`ModuleControlRequest::RouteBind`], because only a
/// bind carries these keys.
pub fn encode_route_bind(
    bind: &ModuleControlRequest,
    peer: &RouteBindPeer,
) -> serde_json::Result<Vec<u8>> {
    if !matches!(bind, ModuleControlRequest::RouteBind { .. }) {
        return Err(serde_json::Error::custom(
            "peer keys can only be added to a route.bind request",
        ));
    }
    if peer.is_empty() {
        return serde_json::to_vec(bind);
    }

    #[derive(Serialize)]
    struct WithPeer<'a> {
        #[serde(flatten)]
        bind: &'a ModuleControlRequest,
        #[serde(flatten)]
        peer: &'a RouteBindPeer,
    }
    serde_json::to_vec(&WithPeer { bind, peer })
}