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                // An accepted scope change can still refuse individual records, and the
197                // owner is the only party that sees the reply. Name them here so
198                // an operator can tell a refused session from a missing one
199                // without the owner's logs. Capped so a call that refuses
200                // thousands cannot flood the log; the count above is complete.
201                for refused in applied
202                    .results
203                    .iter()
204                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
205                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
206                {
207                    warn!(
208                        owner = %owner,
209                        generation,
210                        scope_ref = %refused.scope_ref,
211                        scope_epoch = refused.scope_epoch,
212                        code = refused.code.as_deref().unwrap_or(""),
213                        "scope record refused"
214                    );
215                }
216                self.close_scope_drained_routes(drained);
217                let response = if is_apply {
218                    ModuleControlResponseToModule::ScopeApply {
219                        generation,
220                        results: applied.results,
221                        end_results: applied.end_results,
222                        ended: applied.ended,
223                    }
224                } else {
225                    ModuleControlResponseToModule::ScopeSync {
226                        generation,
227                        results: applied.results,
228                        ended: applied.ended,
229                    }
230                };
231                Ok(vec![control_response_body_frame(
232                    &frame,
233                    &response,
234                    "scope change response",
235                )?])
236            }
237            Err(refusal) => {
238                info!(
239                    owner = %owner,
240                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
241                    generation,
242                    code = refusal.code,
243                    "scope change refused"
244                );
245                Ok(vec![control_error_frame(
246                    &frame,
247                    refusal.code,
248                    refusal.message,
249                )?])
250            }
251        }
252    }
253
254    /// Notify both endpoints of routes drained by a scope change.
255    pub(super) fn close_scope_drained_routes(
256        &self,
257        drained: Vec<crate::forwarding::ScopeDrainedRoute>,
258    ) {
259        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
260    }
261
262    /// Re-authorize a stored source on a principal the module supplies.
263    ///
264    /// That principal carries no spawn or authority epoch, so this reply never
265    /// conveys a caller attestation or a first-party mark, and a provider must
266    /// not apply automatic grants on anything it authorizes.
267    pub(super) fn handle_route_authorize(
268        &self,
269        connection_id: ConnectionId,
270        frame: Frame,
271        principal: Principal,
272        scope: subc_protocol::scope::RouteAuthorizeScope,
273        target: String,
274        expected: subc_protocol::scope::RouteAuthorizeExpected,
275    ) -> Result<Vec<Frame>, RouterError> {
276        use crate::scopes::admission::{admit_route, AdmissionMode};
277        use subc_protocol::scope::{
278            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
279        };
280        let registry = self
281            .registry
282            .route_admission_snapshot()
283            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
284        let owner_configured = match &scope.owner {
285            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
286            _ => false,
287        };
288        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
289        let answer = {
290            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
291            let permitted = registry
292                .iter()
293                .find(|r| r.connection_id == connection_id)
294                .is_some_and(|r| {
295                    scopes.is_federated_owner(&Principal::Reserved {
296                        module_id: r.module_id.clone(),
297                    }) && r.capabilities.as_ref().is_some_and(|caps| {
298                        caps.provides
299                            .iter()
300                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
301                    })
302                });
303            if !permitted {
304                drop(scopes);
305                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
306                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
307            }
308            admit_route(
309                &scopes,
310                &registry,
311                &principal,
312                &target,
313                Some(&selector),
314                owner_configured,
315                AdmissionMode::Authorize(&expected),
316            )
317        };
318        let response = match answer {
319            Ok(admission) => {
320                let mut response = RouteAuthorizeResponse::new(
321                    RouteAuthorizeOutcome::Authorized,
322                    "route admission authorized",
323                );
324                response.content_version = admission.content_version;
325                response
326            }
327            Err(refusal) => refusal.response(),
328        };
329        Ok(vec![control_response_body_frame(
330            &frame,
331            &response,
332            "RouteAuthorizeResponse",
333        )?])
334    }
335
336    /// `scope.describe`: any registered module may read any scope, because a
337    /// provider must read the scope a route it serves is stamped with.
338    pub(super) fn handle_scope_describe(
339        &self,
340        connection_id: ConnectionId,
341        frame: Frame,
342        owner: Principal,
343        scope_ref: String,
344    ) -> Result<Vec<Frame>, RouterError> {
345        let registered = self
346            .registry
347            .get_module_by_connection(connection_id)
348            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
349        let Some(registered) = registered else {
350            return Ok(vec![control_error_frame(
351                &frame,
352                "not_registered",
353                "scope.describe requires an active module registration owned by this connection",
354            )?]);
355        };
356        let scopes = self
357            .scopes
358            .read()
359            .unwrap_or_else(|poisoned| poisoned.into_inner());
360        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
361            return Ok(vec![control_error_frame(
362                &frame,
363                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
364                "scope.describe of the federated owner requires scope-federated/v1",
365            )?]);
366        }
367        let mut description = scopes.describe(&owner, &scope_ref);
368        drop(scopes);
369        if owner
370            != (Principal::Reserved {
371                module_id: registered.manifest.module_id.clone(),
372            })
373        {
374            if let Some(facts) = description
375                .stamp
376                .as_mut()
377                .and_then(|stamp| stamp.attributes.federated.as_mut())
378            {
379                facts.stamp_required = false;
380            }
381        }
382        // Describe readers also decode strict ScopeAttributes. Attribution is
383        // safe to omit unless the requesting module declares it understands it.
384        if !registered
385            .manifest
386            .capabilities
387            .as_ref()
388            .is_some_and(|caps| {
389                caps.provides
390                    .iter()
391                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
392            })
393        {
394            if let Some(stamp) = description.stamp.as_mut() {
395                stamp.attributes.on_behalf_of_agent = None;
396            }
397        }
398        if !registered
399            .manifest
400            .capabilities
401            .as_ref()
402            .is_some_and(|caps| {
403                caps.provides
404                    .iter()
405                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
406            })
407        {
408            if let Some(stamp) = description.stamp.as_mut() {
409                stamp.attributes.flow_version = None;
410                stamp.attributes.flow_code_hash = None;
411                stamp.attributes.flow_install_id = None;
412            }
413        }
414        let owner_configured = match &owner {
415            // Ask whether the owner is configured (`is_configured`), not
416            // whether it is on the roster (`get(..).is_some()`): a supervised
417            // module's process can register and describe a scope before the
418            // supervisor has put it on the roster.
419            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
420            _ => false,
421        };
422        let response = ModuleControlResponseToModule::ScopeDescribe {
423            status: description.status,
424            scope_epoch: description.scope_epoch,
425            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
426            owner_synced: description.owner_synced,
427            owner_configured,
428            scope: description.stamp,
429        };
430        Ok(vec![control_response_body_frame(
431            &frame,
432            &response,
433            "ModuleControlResponseToModule::ScopeDescribe",
434        )?])
435    }
436}
437
438/// Most refused scope records named individually in the log per sync; the
439/// `refused` count on the accepted line is always complete.
440const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
441
442/// Per-outcome counts of one accepted `scope.sync`, for its log line.
443#[derive(Debug, Default, PartialEq, Eq)]
444pub(super) struct ScopeOutcomeCounts {
445    pub(super) created: usize,
446    pub(super) replaced: usize,
447    pub(super) updated: usize,
448    pub(super) unchanged: usize,
449    pub(super) refused: usize,
450}
451
452impl ScopeOutcomeCounts {
453    pub(super) fn of(results: &[ScopeRecordResult]) -> Self {
454        let mut counts = Self::default();
455        for result in results {
456            let slot = match result.outcome {
457                ScopeRecordOutcome::Created => &mut counts.created,
458                ScopeRecordOutcome::Replaced => &mut counts.replaced,
459                ScopeRecordOutcome::Updated => &mut counts.updated,
460                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
461                ScopeRecordOutcome::Refused => &mut counts.refused,
462            };
463            *slot += 1;
464        }
465        counts
466    }
467}