Skip to main content

subc_daemon/control/
scopes.rs

1use super::*;
2
3impl ControlHandler {
4    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
5    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
6        self.scopes
7            .write()
8            .unwrap_or_else(|poisoned| poisoned.into_inner())
9            .set_wall_clock(Arc::new(clock));
10        self
11    }
12}
13
14impl ControlHandler {
15    pub(super) fn publish_scope_changes(
16        &self,
17        changes: &[crate::scopes::ScopeTagChange],
18        expired: &[crate::scopes::ScopeExpired],
19    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
20        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
21    }
22}
23
24impl ControlHandler {
25    pub(super) fn handle_scope_served_by(
26        &self,
27        connection_id: ConnectionId,
28        frame: Frame,
29    ) -> Result<Vec<Frame>, RouterError> {
30        let registered = self
31            .registry
32            .get_module_by_connection(connection_id)
33            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
34        let Some(registered) = registered else {
35            return Ok(vec![control_error_frame(
36                &frame,
37                "not_registered",
38                "scope.served_by requires an active module registration owned by this connection",
39            )?]);
40        };
41        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
42        {
43            Ok(request) => request,
44            Err(err) => {
45                return Ok(vec![control_error_frame(
46                    &frame,
47                    "invalid_control_body",
48                    format!("malformed scope.served_by body: {err}"),
49                )?])
50            }
51        };
52        let answer = self
53            .scopes
54            .read()
55            .unwrap_or_else(|poisoned| poisoned.into_inner())
56            .served_by(
57                &registered.manifest.module_id,
58                &request.scope_ref,
59                request.scope_epoch,
60                &request.module_id,
61            );
62        let reply = subc_control::ScopeServedByReply::new(
63            answer,
64            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
65        );
66        Ok(vec![control_response_body_frame(
67            &frame,
68            &reply,
69            "ScopeServedByReply",
70        )?])
71    }
72}
73
74impl ControlHandler {
75    /// Resolve folders before taking the scope-table lock: a slow filesystem
76    /// must not hold up admissions for unrelated scoped routes.
77    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
78        let mut scopes = ScopeRecords::from(scopes);
79        for (index, record) in scopes.records.iter_mut().enumerate() {
80            if let Some(refusal) = Self::canonicalize_workdir(record) {
81                scopes.refusals.insert(index, refusal);
82            }
83        }
84        scopes
85    }
86
87    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
88        let workdir = record.workdir.as_mut()?;
89        let path = std::path::Path::new(workdir);
90        if !path.is_absolute() {
91            return Some((
92                error_codes::INVALID_WORKDIR,
93                "workdir must be absolute".to_string(),
94            ));
95        }
96        match ProjectRootId::from_path_allowing_missing(path) {
97            Ok(root) => match root.as_path().to_str() {
98                Some(canonical) => {
99                    *workdir = canonical.to_string();
100                    None
101                }
102                None => Some((
103                    error_codes::INVALID_WORKDIR,
104                    "canonical workdir is not UTF-8".to_string(),
105                )),
106            },
107            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
108        }
109    }
110
111    /// `scope.sync`: the owner is the module registered on this connection.
112    /// A connection with no registration (every client connection, `direct`
113    /// included) is refused `not_registered` before the table is consulted.
114    pub(super) fn handle_scope_sync(
115        &self,
116        connection_id: ConnectionId,
117        frame: Frame,
118        generation: u64,
119        scopes: Vec<ScopeRecord>,
120    ) -> Result<Vec<Frame>, RouterError> {
121        self.handle_scope_change(connection_id, frame, generation, scopes, None)
122    }
123
124    pub(super) fn handle_scope_change(
125        &self,
126        connection_id: ConnectionId,
127        frame: Frame,
128        generation: u64,
129        scopes: Vec<ScopeRecord>,
130        end: Option<Vec<ScopeEnd>>,
131    ) -> Result<Vec<Frame>, RouterError> {
132        let is_apply = end.is_some();
133        let Some(registration) = self
134            .registry
135            .get_module_by_connection(connection_id)
136            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
137        else {
138            return Ok(vec![control_error_frame(
139                &frame,
140                "not_registered",
141                "scope.sync and scope.apply require an active module registration owned by this connection",
142            )?]);
143        };
144        let owner = registration.manifest.module_id;
145        let scopes = Self::prepare_scope_records(scopes);
146        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
147        let is_current_launch = |connection: ConnectionId| {
148            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
149        };
150        // Lock order is the scope table, then the forwarding table: the new
151        // tags are published, and the routes the change closes are selected,
152        // while the scope table is still write-locked, so no admission can read
153        // a record whose tag is not yet published.
154        let mut table = self
155            .scopes
156            .write()
157            .unwrap_or_else(|poisoned| poisoned.into_inner());
158        let outcome = match end {
159            Some(end) => table.apply(
160                &owner,
161                connection_id,
162                is_current_launch,
163                generation,
164                scopes,
165                end,
166            ),
167            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
168        };
169        let drained = match &outcome {
170            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
171            Err(_) => Vec::new(),
172        };
173        let has_deadlines = outcome.is_ok() && table.has_deadlines();
174        drop(table);
175        if has_deadlines {
176            self.scope_deadline_added.notify_one();
177        }
178        match outcome {
179            Ok(applied) => {
180                let counts = ScopeOutcomeCounts::of(&applied.results);
181                info!(
182                    owner = %owner,
183                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
184                    generation,
185                    records = applied.results.len(),
186                    created = counts.created,
187                    replaced = counts.replaced,
188                    updated = counts.updated,
189                    unchanged = counts.unchanged,
190                    refused = counts.refused,
191                    ended = applied.ended.len(),
192                    tag_changes = applied.tag_changes.len(),
193                    routes_closed = drained.len(),
194                    "scope change accepted"
195                );
196                let mut route_counts = std::collections::HashMap::new();
197                for route in &drained {
198                    *route_counts
199                        .entry((
200                            route.scope.owner.as_str(),
201                            route.scope.scope_ref.as_str(),
202                            route.scope.tag.scope_epoch,
203                        ))
204                        .or_insert(0usize) += 1;
205                }
206                for (scope, cause) in &applied.owner_ended {
207                    let routes_closed = route_counts
208                        .get(&(owner.as_str(), scope.scope_ref.as_str(), scope.scope_epoch))
209                        .copied()
210                        .unwrap_or(0);
211                    info!(owner = %owner, scope_ref = %scope.scope_ref,
212                        scope_epoch = scope.scope_epoch, cause = cause.as_str(),
213                        routes_closed, "scope ended");
214                }
215                // An accepted scope change can still refuse individual records, and the
216                // owner is the only party that sees the reply. Name them here so
217                // an operator can tell a refused session from a missing one
218                // without the owner's logs. Capped so a call that refuses
219                // thousands cannot flood the log; the count above is complete.
220                for refused in applied
221                    .results
222                    .iter()
223                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
224                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
225                {
226                    warn!(
227                        owner = %owner,
228                        generation,
229                        scope_ref = %refused.scope_ref,
230                        scope_epoch = refused.scope_epoch,
231                        code = refused.code.as_deref().unwrap_or(""),
232                        "scope record refused"
233                    );
234                }
235                self.close_scope_drained_routes(drained);
236                let response = if is_apply {
237                    ModuleControlResponseToModule::ScopeApply {
238                        generation,
239                        results: applied.results,
240                        end_results: applied.end_results,
241                        ended: applied.ended,
242                    }
243                } else {
244                    ModuleControlResponseToModule::ScopeSync {
245                        generation,
246                        results: applied.results,
247                        ended: applied.ended,
248                    }
249                };
250                Ok(vec![control_response_body_frame(
251                    &frame,
252                    &response,
253                    "scope change response",
254                )?])
255            }
256            Err(refusal) => {
257                info!(
258                    owner = %owner,
259                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
260                    generation,
261                    code = refusal.code,
262                    "scope change refused"
263                );
264                Ok(vec![control_error_frame(
265                    &frame,
266                    refusal.code,
267                    refusal.message,
268                )?])
269            }
270        }
271    }
272
273    /// Notify both endpoints of routes drained by a scope change.
274    pub(super) fn close_scope_drained_routes(
275        &self,
276        drained: Vec<crate::forwarding::ScopeDrainedRoute>,
277    ) {
278        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
279    }
280
281    /// Re-authorize a stored source on a principal the module supplies.
282    ///
283    /// That principal carries no spawn or authority epoch, so this reply never
284    /// conveys a caller attestation or a first-party mark, and a provider must
285    /// not apply automatic grants on anything it authorizes.
286    pub(super) fn handle_route_authorize(
287        &self,
288        connection_id: ConnectionId,
289        frame: Frame,
290        principal: Principal,
291        scope: subc_protocol::scope::RouteAuthorizeScope,
292        target: String,
293        expected: subc_protocol::scope::RouteAuthorizeExpected,
294    ) -> Result<Vec<Frame>, RouterError> {
295        use crate::scopes::admission::{admit_route, AdmissionMode};
296        use subc_protocol::scope::{
297            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
298        };
299        let registry = self
300            .registry
301            .route_admission_snapshot()
302            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
303        let owner_configured = match &scope.owner {
304            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
305            _ => false,
306        };
307        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
308        let answer = {
309            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
310            let permitted = registry
311                .iter()
312                .find(|r| r.connection_id == connection_id)
313                .is_some_and(|r| {
314                    scopes.is_federated_owner(&Principal::Reserved {
315                        module_id: r.module_id.clone(),
316                    }) && r.capabilities.as_ref().is_some_and(|caps| {
317                        caps.provides
318                            .iter()
319                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
320                    })
321                });
322            if !permitted {
323                drop(scopes);
324                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
325                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
326            }
327            admit_route(
328                &scopes,
329                &registry,
330                &principal,
331                &target,
332                Some(&selector),
333                owner_configured,
334                AdmissionMode::Authorize(&expected),
335            )
336        };
337        let response = match answer {
338            Ok(admission) => {
339                let mut response = RouteAuthorizeResponse::new(
340                    RouteAuthorizeOutcome::Authorized,
341                    "route admission authorized",
342                );
343                response.content_version = admission.content_version;
344                response
345            }
346            Err(refusal) => refusal.response(),
347        };
348        Ok(vec![control_response_body_frame(
349            &frame,
350            &response,
351            "RouteAuthorizeResponse",
352        )?])
353    }
354
355    /// `scope.describe`: any registered module may read any scope, because a
356    /// provider must read the scope a route it serves is stamped with.
357    pub(super) fn handle_scope_describe(
358        &self,
359        connection_id: ConnectionId,
360        frame: Frame,
361        owner: Principal,
362        scope_ref: String,
363    ) -> Result<Vec<Frame>, RouterError> {
364        let registered = self
365            .registry
366            .get_module_by_connection(connection_id)
367            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
368        let Some(registered) = registered else {
369            return Ok(vec![control_error_frame(
370                &frame,
371                "not_registered",
372                "scope.describe requires an active module registration owned by this connection",
373            )?]);
374        };
375        let scopes = self
376            .scopes
377            .read()
378            .unwrap_or_else(|poisoned| poisoned.into_inner());
379        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
380            return Ok(vec![control_error_frame(
381                &frame,
382                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
383                "scope.describe of the federated owner requires scope-federated/v1",
384            )?]);
385        }
386        let mut description = scopes.describe(&owner, &scope_ref);
387        drop(scopes);
388        if owner
389            != (Principal::Reserved {
390                module_id: registered.manifest.module_id.clone(),
391            })
392        {
393            if let Some(facts) = description
394                .stamp
395                .as_mut()
396                .and_then(|stamp| stamp.attributes.federated.as_mut())
397            {
398                facts.stamp_required = false;
399            }
400        }
401        // Describe readers also decode strict ScopeAttributes. Attribution is
402        // safe to omit unless the requesting module declares it understands it.
403        if !registered
404            .manifest
405            .capabilities
406            .as_ref()
407            .is_some_and(|caps| {
408                caps.provides
409                    .iter()
410                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
411            })
412        {
413            if let Some(stamp) = description.stamp.as_mut() {
414                stamp.attributes.on_behalf_of_agent = None;
415            }
416        }
417        if !registered
418            .manifest
419            .capabilities
420            .as_ref()
421            .is_some_and(|caps| {
422                caps.provides
423                    .iter()
424                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
425            })
426        {
427            if let Some(stamp) = description.stamp.as_mut() {
428                stamp.attributes.flow_version = None;
429                stamp.attributes.flow_code_hash = None;
430                stamp.attributes.flow_install_id = None;
431            }
432        }
433        let owner_configured = match &owner {
434            // Ask whether the owner is configured (`is_configured`), not
435            // whether it is on the roster (`get(..).is_some()`): a supervised
436            // module's process can register and describe a scope before the
437            // supervisor has put it on the roster.
438            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
439            _ => false,
440        };
441        let response = ModuleControlResponseToModule::ScopeDescribe {
442            status: description.status,
443            scope_epoch: description.scope_epoch,
444            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
445            owner_synced: description.owner_synced,
446            owner_configured,
447            scope: description.stamp,
448        };
449        Ok(vec![control_response_body_frame(
450            &frame,
451            &response,
452            "ModuleControlResponseToModule::ScopeDescribe",
453        )?])
454    }
455}
456
457/// Most refused scope records named individually in the log per sync; the
458/// `refused` count on the accepted line is always complete.
459const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
460
461/// Per-outcome counts of one accepted `scope.sync`, for its log line.
462#[derive(Debug, Default, PartialEq, Eq)]
463pub(super) struct ScopeOutcomeCounts {
464    pub(super) created: usize,
465    pub(super) replaced: usize,
466    pub(super) updated: usize,
467    pub(super) unchanged: usize,
468    pub(super) refused: usize,
469}
470
471impl ScopeOutcomeCounts {
472    pub(super) fn of(results: &[ScopeRecordResult]) -> Self {
473        let mut counts = Self::default();
474        for result in results {
475            let slot = match result.outcome {
476                ScopeRecordOutcome::Created => &mut counts.created,
477                ScopeRecordOutcome::Replaced => &mut counts.replaced,
478                ScopeRecordOutcome::Updated => &mut counts.updated,
479                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
480                ScopeRecordOutcome::Refused => &mut counts.refused,
481            };
482            *slot += 1;
483        }
484        counts
485    }
486}