subc_protocol/scope.rs
1//! Scope records: owned identity records the daemon holds for sessions.
2//!
3//! A scope is identified by `(owner, ref)`. The owner is the module whose own
4//! registered connection synced it, never a value in the request, and the
5//! `ref` is an opaque string unique within that owner only. The design is
6//! `docs/designs/daemon-scopes.md`; the wire shapes here are the owner-facing
7//! half of it (`scope.sync`, `scope.describe`).
8//!
9//! Every record type refuses unknown fields. A field this daemon does not know
10//! may be one that narrows authority in a later version (a carrier's target
11//! list, say), and silently dropping it would widen what the scope grants, so
12//! an owner sending one is told its body is malformed instead.
13
14use serde::{Deserialize, Serialize};
15
16use crate::Principal;
17
18// Scope principals are authority-bearing input: an unrecognized constraint must
19// not silently widen a grant. Principal elsewhere is a forward-compatible caller
20// fact, so keep its general decoder lenient and enforce this only on scope input.
21#[derive(Deserialize)]
22#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
23enum ScopePrincipal {
24 Reserved { module_id: String },
25 Direct {},
26 Unverified {},
27}
28
29impl From<ScopePrincipal> for Principal {
30 fn from(value: ScopePrincipal) -> Self {
31 match value {
32 ScopePrincipal::Reserved { module_id } => Self::Reserved { module_id },
33 ScopePrincipal::Direct {} => Self::Direct,
34 ScopePrincipal::Unverified {} => Self::Unverified,
35 }
36 }
37}
38
39fn deserialize_scope_principal<'de, D: serde::Deserializer<'de>>(
40 deserializer: D,
41) -> Result<Principal, D::Error> {
42 ScopePrincipal::deserialize(deserializer).map(Into::into)
43}
44
45fn deserialize_scope_principals<'de, D: serde::Deserializer<'de>>(
46 deserializer: D,
47) -> Result<Vec<Principal>, D::Error> {
48 Vec::<ScopePrincipal>::deserialize(deserializer)
49 .map(|principals| principals.into_iter().map(Into::into).collect())
50}
51
52/// The `server.describe` capability a daemon advertises when it admits routes
53/// under scopes. A carrier that needs a scoped route and does not see it fails
54/// the call (`scope_unsupported`) instead of opening an unscoped route.
55pub const CAP_SCOPES_V1: &str = "scopes/v1";
56
57/// The `server.describe` capability a daemon advertises when it checks a
58/// `route.open`'s `role_versions` and forwards them on the module's bind. A
59/// daemon without it drops the field silently, so a consumer that relies on
60/// the provider seeing its role versions checks for this first.
61pub const CAP_ROUTE_ROLE_VERSIONS_V1: &str = "route-role-versions/v1";
62
63/// Module-to-subc op that registers an owner's full scope set.
64pub const SCOPE_SYNC_OP: &str = "scope.sync";
65/// Module-to-subc op that reads one scope's current state.
66pub const SCOPE_DESCRIBE_OP: &str = "scope.describe";
67
68/// Most live scopes one owner may hold. A sync naming more is refused whole.
69pub const MAX_LIVE_SCOPES_PER_OWNER: usize = 10_000;
70/// Most bytes one scope's `attributes` may take, measured as compact JSON. A
71/// sync carrying a larger record is refused whole.
72pub const MAX_SCOPE_ATTRIBUTE_BYTES: usize = 4 * 1024;
73/// Most ended scopes the daemon remembers per owner. The oldest is forgotten
74/// first, and reaching the bound never refuses a sync.
75pub const MAX_SCOPE_TOMBSTONES_PER_OWNER: usize = 1_000;
76/// Most modules one targeted carrier entry may list.
77pub const MAX_CARRIER_TARGETS: usize = 16;
78
79/// What a scope stands for. Closed, and fixed for the life of one
80/// `scope_epoch`: a different kind needs a new epoch, which ends the old scope.
81#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
82#[serde(rename_all = "snake_case")]
83pub enum ScopeKind {
84 Head,
85 Worker,
86 Ephemeral,
87}
88
89/// A link from a scope to another scope, pinned to that scope's session by its
90/// epoch.
91#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
92#[serde(deny_unknown_fields)]
93pub struct ScopeParent {
94 #[serde(deserialize_with = "deserialize_scope_principal")]
95 pub owner: Principal,
96 #[serde(rename = "ref")]
97 pub scope_ref: String,
98 pub scope_epoch: u64,
99}
100
101/// Who, besides the owner, may open routes under a scope.
102///
103/// `targets` absent means the carrier may open to any module. Present, it
104/// names the only module ids the carrier may open to, and must hold between 1
105/// and [`MAX_CARRIER_TARGETS`] entries: an empty list is refused rather than
106/// read as either "none" or "all".
107#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
108#[serde(deny_unknown_fields)]
109pub struct ScopeCarrier {
110 #[serde(deserialize_with = "deserialize_scope_principal")]
111 pub principal: Principal,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub targets: Option<Vec<String>>,
114}
115
116/// The attributes the daemon stamps without interpreting. They bear authority,
117/// so only an owner module named in the daemon config's `scope_authority_owners`
118/// list (by default the module that owns agent sessions) may set them; a scope
119/// owned by any other module must leave them empty.
120#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
121#[serde(deny_unknown_fields)]
122pub struct ScopeAttributes {
123 /// The agent the scope's session belongs to. Identity, never permission.
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub agent_id: Option<String>,
126 /// Whether a provider may act as `agent_id`. Refused without `agent_id`.
127 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
128 pub delegates: bool,
129 /// This scope belongs to the named flow, an automated workflow run on an
130 /// agent's behalf. Set only by an authority owner (see above), validated
131 /// with [`validate_flow_id`], and stamped verbatim. It needs neither
132 /// `agent_id` nor `delegates`. Providers treat a module other than the
133 /// owner that opens a route under a flow scope as the flow's carrier.
134 ///
135 /// Like an `agent_id` change, changing this within the same scope epoch is
136 /// accepted: the scope's content version increases (the number providers
137 /// compare to notice a change), and every route under the scope is closed
138 /// with the reason `scope_delegation_changed`, so no live route keeps the
139 /// old identity.
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub flow_id: Option<String>,
142}
143
144impl ScopeAttributes {
145 pub fn is_empty(&self) -> bool {
146 self.agent_id.is_none() && !self.delegates && self.flow_id.is_none()
147 }
148}
149
150/// Check a flow id using the shared opaque-token rule: 1–256 printable,
151/// non-space ASCII bytes. Errors name `flow_id`. Scope refs remain opaque and
152/// are not subject to this token rule.
153pub fn validate_flow_id(flow_id: &str) -> Result<(), crate::tool_call::OpaqueFieldError> {
154 crate::tool_call::validate_opaque_field("flow_id", flow_id)
155}
156
157/// One scope as its owner registers it in `scope.sync`.
158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
159#[serde(deny_unknown_fields)]
160pub struct ScopeRecord {
161 #[serde(rename = "ref")]
162 pub scope_ref: String,
163 /// Owner-supplied session number. The owner keeps it with its own record of
164 /// the session, re-sends the same value for the same session after any
165 /// restart, and uses a higher one when it reuses the ref for a new session.
166 pub scope_epoch: u64,
167 pub kind: ScopeKind,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub parent: Option<ScopeParent>,
170 /// Principals, other than the owner, allowed to register child scopes under
171 /// this one. Listing a principal here grants it nothing else.
172 #[serde(
173 default,
174 skip_serializing_if = "Vec::is_empty",
175 deserialize_with = "deserialize_scope_principals"
176 )]
177 pub child_owners: Vec<Principal>,
178 #[serde(default, skip_serializing_if = "Vec::is_empty")]
179 pub carriers: Vec<ScopeCarrier>,
180 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
181 pub attributes: ScopeAttributes,
182}
183
184/// The scope a `route.open` asks to be admitted under.
185///
186/// `scope_epoch` is optional on the wire only so that leaving it out is
187/// refused by name (`scope_epoch_required`) rather than as a malformed body:
188/// every opener must name it, the owner included.
189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
190#[serde(deny_unknown_fields)]
191pub struct ScopeSelector {
192 #[serde(deserialize_with = "deserialize_scope_principal")]
193 pub owner: Principal,
194 #[serde(rename = "ref")]
195 pub scope_ref: String,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub scope_epoch: Option<u64>,
198}
199
200/// The state of a scope's parent link.
201#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
202#[serde(rename_all = "snake_case")]
203pub enum ParentState {
204 /// The parent is live at the named epoch and the link was permitted.
205 Linked,
206 /// The parent's owner has not synced in this daemon incarnation, so the
207 /// link is unverified and grants nothing yet.
208 Pending,
209 /// The parent is gone or live at another epoch, or the link was refused
210 /// when the parent's owner synced. Final for this link.
211 Ended,
212}
213
214/// What a `scope.sync` did with one record.
215#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
216#[serde(rename_all = "snake_case")]
217pub enum ScopeRecordOutcome {
218 /// The ref was not live before; the scope was created.
219 Created,
220 /// The ref was live at a lower epoch; that scope ended and this one began.
221 Replaced,
222 /// The ref was live at this epoch and its content changed.
223 Updated,
224 /// The ref was live at this epoch with identical content; its `version`
225 /// did not move.
226 Unchanged,
227 /// The record was refused on its own merits (`code` says why) and the ref
228 /// keeps whatever state it had before this sync.
229 Refused,
230}
231
232/// The per-record result in a `scope.sync` reply, in request order.
233#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
234pub struct ScopeRecordResult {
235 #[serde(rename = "ref")]
236 pub scope_ref: String,
237 /// The epoch the record named, which for a refusal may differ from the
238 /// epoch still held.
239 pub scope_epoch: u64,
240 pub outcome: ScopeRecordOutcome,
241 /// The refusal code when `outcome` is `refused`.
242 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub code: Option<String>,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
245 pub message: Option<String>,
246 /// The daemon's content counter for the scope held under this ref after
247 /// the sync; absent when no scope is live under it.
248 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub version: Option<u64>,
250 /// The parent link's state after the sync, for a scope with a parent.
251 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub parent_state: Option<ParentState>,
253}
254
255/// A scope of the syncing owner that the sync ended, by removal or by a
256/// higher epoch for the same ref.
257#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
258pub struct ScopeEnded {
259 #[serde(rename = "ref")]
260 pub scope_ref: String,
261 pub scope_epoch: u64,
262}
263
264/// `scope.describe`'s answer about one `(owner, ref)`.
265#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
266#[serde(rename_all = "snake_case")]
267pub enum ScopeStatus {
268 Live,
269 /// Ended in this daemon incarnation, and still remembered.
270 Ended,
271 /// Neither live nor remembered as ended. With `owner_synced` true the scope
272 /// is gone: an owner's first sync of an incarnation is its full set. With
273 /// `owner_synced` false and `owner_configured` true the owner has not
274 /// re-synced since a daemon restart, so a reader waits. With
275 /// `owner_configured` false the owner will never sync.
276 NotLive,
277}
278
279/// The fields the daemon stamps for a live scope.
280#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
281pub struct ScopeStamp {
282 pub owner: Principal,
283 #[serde(rename = "ref")]
284 pub scope_ref: String,
285 pub scope_epoch: u64,
286 pub kind: ScopeKind,
287 #[serde(default, skip_serializing_if = "Option::is_none")]
288 pub parent: Option<ScopeParent>,
289 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub parent_state: Option<ParentState>,
291 #[serde(default, skip_serializing_if = "ScopeAttributes::is_empty")]
292 pub attributes: ScopeAttributes,
293 /// Whether the owner is listed in the daemon's `scope_authority_owners`.
294 /// Providers decide on this flag and keep no copy of the list.
295 pub owner_authorized: bool,
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301 use crate::tool_call::OpaqueFieldError;
302
303 #[test]
304 fn flow_id_uses_the_shared_opaque_token_bounds_and_names_its_field() {
305 let field = "flow_id";
306 assert_eq!(validate_flow_id(""), Err(OpaqueFieldError::Empty { field }));
307 assert_eq!(validate_flow_id("f"), Ok(()));
308 assert_eq!(validate_flow_id(&"f".repeat(256)), Ok(()));
309 assert_eq!(
310 validate_flow_id(&"f".repeat(257)),
311 Err(OpaqueFieldError::TooLong { field, length: 257 })
312 );
313 assert_eq!(validate_flow_id("!~Flow:7/step"), Ok(()));
314 for bad in ["f é", "f\t", "fé", "f\u{7f}"] {
315 let error = validate_flow_id(bad).unwrap_err();
316 assert_eq!(
317 error,
318 OpaqueFieldError::InvalidCharacter { field, index: 1 }
319 );
320 assert_eq!(error.field(), "flow_id");
321 }
322 }
323
324 #[test]
325 fn flow_only_attributes_round_trip_and_absence_keeps_the_bytes() {
326 let attributes = ScopeAttributes::default();
327 assert!(attributes.is_empty());
328 assert_eq!(serde_json::to_string(&attributes).unwrap(), "{}");
329 assert_eq!(
330 serde_json::from_str::<ScopeAttributes>("{}").unwrap(),
331 attributes
332 );
333 let attributes = ScopeAttributes {
334 flow_id: Some("flow:7".to_string()),
335 ..ScopeAttributes::default()
336 };
337 assert!(!attributes.is_empty());
338 let encoded = serde_json::to_string(&attributes).unwrap();
339 assert_eq!(encoded, r#"{"flow_id":"flow:7"}"#);
340 assert_eq!(
341 serde_json::from_str::<ScopeAttributes>(&encoded).unwrap(),
342 attributes
343 );
344 assert!(
345 serde_json::from_str::<ScopeAttributes>(r#"{"flow_id":"flow:7","unknown":true}"#)
346 .is_err()
347 );
348 }
349}