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 neither 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/// Whether the daemon could read the peer's identity from the kernel when it
28/// accepted the connection.
29///
30/// A value from a newer daemon decodes as [`ObservedPeerStatus::Unknown`],
31/// keeping its spelling. Readers must treat anything other than
32/// [`ObservedPeerStatus::Observed`] as carrying no peer facts.
33#[derive(Debug, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum ObservedPeerStatus {
36 /// The daemon read the peer's user (and possibly more) at accept time.
37 Observed,
38 /// The connection offers no kernel peer identity (TCP, or a platform
39 /// without the primitive), or reading it failed.
40 Unobserved,
41 /// A status this crate does not know, kept with its spelling so it
42 /// re-encodes unchanged.
43 Unknown(String),
44}
45
46impl Serialize for ObservedPeerStatus {
47 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
48 serializer.serialize_str(match self {
49 Self::Observed => "observed",
50 Self::Unobserved => "unobserved",
51 Self::Unknown(value) => value,
52 })
53 }
54}
55
56impl<'de> Deserialize<'de> for ObservedPeerStatus {
57 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
58 Ok(match String::deserialize(deserializer)?.as_str() {
59 "observed" => Self::Observed,
60 "unobserved" => Self::Unobserved,
61 value => Self::Unknown(value.to_owned()),
62 })
63 }
64}
65
66/// What the daemon learned from the kernel about the process that opened the
67/// route, read once when its connection was accepted.
68///
69/// This is an observation, not an authorization: the route's principal is
70/// unchanged by it. `exe` is informational. `signing_id` is present only when
71/// the platform validated the process's code signature.
72#[non_exhaustive]
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
74pub struct ObservedPeer {
75 pub status: ObservedPeerStatus,
76 /// The peer's effective user id (macOS and Linux).
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub uid: Option<u32>,
79 /// The peer's user SID (Windows).
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub sid: Option<String>,
82 /// The peer's executable path, omitted when it could not be read.
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub exe: Option<String>,
85 /// The peer's code-signing identifier, present only for validly signed
86 /// code on a platform that checks it.
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub signing_id: Option<String>,
89}
90
91impl ObservedPeer {
92 /// A connection with no kernel peer identity: `{"status":"unobserved"}`.
93 pub fn unobserved() -> Self {
94 Self {
95 status: ObservedPeerStatus::Unobserved,
96 uid: None,
97 sid: None,
98 exe: None,
99 signing_id: None,
100 }
101 }
102
103 /// An observed peer identified by its Unix user id.
104 pub fn observed_uid(uid: u32) -> Self {
105 Self {
106 status: ObservedPeerStatus::Observed,
107 uid: Some(uid),
108 ..Self::unobserved()
109 }
110 }
111
112 /// An observed peer identified by its Windows user SID.
113 pub fn observed_sid(sid: impl Into<String>) -> Self {
114 Self {
115 status: ObservedPeerStatus::Observed,
116 sid: Some(sid.into()),
117 ..Self::unobserved()
118 }
119 }
120
121 /// Set or clear the executable path.
122 #[must_use]
123 pub fn with_exe(mut self, exe: Option<String>) -> Self {
124 self.exe = exe;
125 self
126 }
127
128 /// Set or clear the code-signing identifier.
129 #[must_use]
130 pub fn with_signing_id(mut self, signing_id: Option<String>) -> Self {
131 self.signing_id = signing_id;
132 self
133 }
134}
135
136/// The daemon's statement that the route was opened over a connection it
137/// recognised, when the connection was made, as a verified operator app.
138///
139/// It reports a fact fixed at bind time and is never retracted on the route.
140/// It is not authority: a module still asks the daemon with `operator.confirm`
141/// before acting on the person's behalf, and the daemon decides.
142#[non_exhaustive]
143#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
144pub struct OperatorApp {
145 /// The app's identifier in the daemon's compiled app table.
146 pub app: String,
147 /// The app's process id when its connection was made.
148 pub pid: u32,
149}
150
151impl OperatorApp {
152 pub fn new(app: impl Into<String>, pid: u32) -> Self {
153 Self {
154 app: app.into(),
155 pid,
156 }
157 }
158}
159
160/// The `route.bind` keys carried beside [`ModuleControlRequest::RouteBind`].
161///
162/// Both are absent unless the target declared the matching capability, and an
163/// absent key is omitted, never `null`. Decoding ignores every other key, so a
164/// module reads this from the same body it decodes as the bind.
165#[non_exhaustive]
166#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
167pub struct RouteBindPeer {
168 /// Sent only to a target declaring [`OBSERVED_PEER_CAPABILITY`].
169 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub observed_peer: Option<ObservedPeer>,
171 /// Sent only to a target declaring [`OPERATOR_APP_CAPABILITY`], and only
172 /// when the daemon recognised the opening connection as an operator app.
173 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub operator_app: Option<OperatorApp>,
175}
176
177impl RouteBindPeer {
178 /// No peer keys: the bind keeps its legacy bytes.
179 pub fn new() -> Self {
180 Self::default()
181 }
182
183 /// Set or clear `observed_peer`.
184 #[must_use]
185 pub fn with_observed_peer(mut self, observed_peer: Option<ObservedPeer>) -> Self {
186 self.observed_peer = observed_peer;
187 self
188 }
189
190 /// Set or clear `operator_app`.
191 #[must_use]
192 pub fn with_operator_app(mut self, operator_app: Option<OperatorApp>) -> Self {
193 self.operator_app = operator_app;
194 self
195 }
196
197 /// Whether neither key is present.
198 pub fn is_empty(&self) -> bool {
199 self.observed_peer.is_none() && self.operator_app.is_none()
200 }
201}
202
203/// Encodes a `route.bind` body with `peer`'s keys after the bind's own keys.
204///
205/// With an empty `peer` the bytes equal `serde_json::to_vec(bind)`. Fails for
206/// any request other than [`ModuleControlRequest::RouteBind`], because only a
207/// bind carries these keys.
208pub fn encode_route_bind(
209 bind: &ModuleControlRequest,
210 peer: &RouteBindPeer,
211) -> serde_json::Result<Vec<u8>> {
212 if !matches!(bind, ModuleControlRequest::RouteBind { .. }) {
213 return Err(serde_json::Error::custom(
214 "peer keys can only be added to a route.bind request",
215 ));
216 }
217 if peer.is_empty() {
218 return serde_json::to_vec(bind);
219 }
220
221 #[derive(Serialize)]
222 struct WithPeer<'a> {
223 #[serde(flatten)]
224 bind: &'a ModuleControlRequest,
225 #[serde(flatten)]
226 peer: &'a RouteBindPeer,
227 }
228 serde_json::to_vec(&WithPeer { bind, peer })
229}