Skip to main content

subc_daemon/control/
capability_census.rs

1//! The capability deny census: closes live routes an attested deny edge now
2//! forbids. Route binds still pending when an edge is added are rechecked at
3//! settlement instead; see `route_bind_settlement`.
4
5use super::*;
6
7impl ControlHandler {
8    /// Reconcile only live, attested route bindings after a capability deny edge
9    /// or target claim was added. This is deliberately a control-plane census:
10    /// the opaque forwarding hot path must not grow a per-frame capability check.
11    pub(super) fn enforce_capability_denies(&self) {
12        let registrations = match self.registry.list_registered_modules() {
13            Ok(snapshot) => snapshot,
14            Err(err) => {
15                warn!(error = %err, "failed to read registrations for capability deny census");
16                return;
17            }
18        };
19        let manifests = registrations
20            .into_iter()
21            .map(|registration| {
22                (
23                    registration.manifest.module_id.clone(),
24                    registration.manifest,
25                )
26            })
27            .collect::<BTreeMap<_, _>>();
28        let census = match self.forwarding.route_census(None) {
29            Ok(census) => census,
30            Err(err) => {
31                warn!(error = %err, "failed to read route census for capability deny enforcement");
32                return;
33            }
34        };
35
36        for (target_module_id, routes) in census {
37            let Some(target_manifest) = manifests.get(&target_module_id) else {
38                continue;
39            };
40            let mut closed_routes = Vec::new();
41            let mut goodbyes = Vec::new();
42            for route in routes {
43                let Principal::Reserved {
44                    module_id: opening_module_id,
45                } = &route.principal
46                else {
47                    continue;
48                };
49                let Some(opening_manifest) = manifests.get(opening_module_id) else {
50                    continue;
51                };
52                let Some(capability) = denied_capability(
53                    opening_manifest.capabilities.as_ref(),
54                    target_manifest.capabilities.as_ref(),
55                ) else {
56                    continue;
57                };
58
59                match self.forwarding.release_client_route(
60                    route.goodbye_target.connection_id,
61                    route.goodbye_target.channel,
62                    route.goodbye_target.epoch,
63                ) {
64                    Ok(RouteRelease::Removed(module_goodbye)) => {
65                        warn!(
66                            opening_module_id,
67                            target_module_id,
68                            capability,
69                            "force-closing route because an attested capability deny edge now matches"
70                        );
71                        goodbyes.push(module_goodbye);
72                        goodbyes.push(route.goodbye_target.clone());
73                        closed_routes.push(route);
74                    }
75                    Ok(RouteRelease::Stale | RouteRelease::Absent) => {}
76                    Err(err) => warn!(
77                        opening_module_id,
78                        target_module_id,
79                        capability,
80                        error = %err,
81                        "failed to force-close capability-denied route"
82                    ),
83                }
84            }
85
86            if closed_routes.is_empty() {
87                continue;
88            }
89            send_route_control_pushes(
90                &self.forwarding,
91                closed_routes,
92                ClientControlPush::RouteClosed {
93                    module_id: target_module_id,
94                    channels: Vec::new(),
95                    reason: RouteCloseReason::CapabilityDenied,
96                    drained: false,
97                    abandoned: 0,
98                    excluded_subscriptions: 0,
99                    terminal: Some(false),
100                },
101            );
102            // route.closed records the reason; the route GOODBYE ends the
103            // client's handle and settles any calls still pending on it.
104            self.emit_route_goodbyes(goodbyes);
105        }
106    }
107}
108
109impl ControlHandler {
110    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
111    /// requirement event without depending on an operator polling a status command.
112    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
113        let handler = Arc::downgrade(&self);
114        let evaluator = self.capability_evaluator.clone();
115        tokio::spawn(async move {
116            loop {
117                evaluator.wait_for_change_or_deadline().await;
118                let Some(handler) = handler.upgrade() else {
119                    break;
120                };
121                handler.refresh_capability_requirements();
122            }
123        });
124    }
125}
126
127impl ControlHandler {
128    pub(super) fn runtime_capability_snapshot(
129        &self,
130    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
131        let runtime = self
132            .supervisor
133            .list()
134            .into_iter()
135            .map(|module| {
136                let status = module.status().map_err(|err| {
137                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
138                })?;
139                Ok(RuntimeModule {
140                    module_id: status.module_id,
141                    state: status.state,
142                    enabled: status.enabled,
143                })
144            })
145            .collect::<Result<Vec<_>, RouterError>>()?;
146        // Include every registration, published or not. The capability
147        // evaluator counts a module as providing its capabilities as soon as it
148        // has registered, even before `catalog.list` shows it, so a HELLO in
149        // progress does not change other modules' required-capability
150        // verdicts. See `Registry::list_registered_modules`.
151        let registrations = self.registry.list_registered_modules().map_err(|err| {
152            RouterError::backend(
153                0,
154                0,
155                format!("failed to list capability registrations: {err}"),
156            )
157        })?;
158        let registrations = registrations
159            .into_iter()
160            .map(|registration| RegisteredModule {
161                module_id: registration.manifest.module_id,
162                module_version: registration.manifest.module_version,
163                capabilities: registration.manifest.capabilities,
164            })
165            .collect();
166        Ok((runtime, registrations))
167    }
168
169    /// The capability side effects of a module becoming the active registration
170    /// for its id: cache its manifest (logging how it differs from the cached
171    /// one), run the deny census when its declarations call for one, and recompute the
172    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
173    /// candidate's does not, and the supervisor does it at promotion instead,
174    /// through [`crate::supervise::SwapPromotionObserver`].
175    pub(super) fn apply_registration_capabilities(
176        &self,
177        registration: &crate::registry::ModuleRegistration,
178    ) {
179        let cached_registration = RegisteredModule {
180            module_id: registration.manifest.module_id.clone(),
181            module_version: registration.manifest.module_version.clone(),
182            capabilities: registration.manifest.capabilities.clone(),
183        };
184        let change = self.capability_evaluator.record_hello(&cached_registration);
185        log_manifest_change(&cached_registration.module_id, &change);
186        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
187            self.enforce_capability_denies();
188        }
189        self.refresh_capability_requirements();
190    }
191
192    /// Point the shared supervisor handle at this handler for swap promotions.
193    /// Called wherever a handler is put behind the `Arc` the router serves, so
194    /// it can be held weakly.
195    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
196        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
197            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
198        self.supervisor.set_swap_promotion_observer(observer);
199    }
200
201    pub fn refresh_capability_requirements(&self) {
202        match self.runtime_capability_snapshot() {
203            Ok((runtime, registrations)) => {
204                let events = self
205                    .capability_evaluator
206                    .evaluate_now(&runtime, &registrations);
207                if !events.is_empty() {
208                    self.catalog_readiness_revision
209                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
210                }
211                log_requirement_events(events, &self.daemon_shutdown);
212            }
213            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
214        }
215    }
216
217    /// Why a registered module is not accepting new route binds, or `None` when
218    /// it is. This is the module's effective readiness: its declared readiness
219    /// first, then every `need: required` capability it declares evaluating to
220    /// `provided`. `route.open` and `catalog.list` both read it here so the
221    /// catalog never reports a module routable that `route.open` would refuse.
222    pub(super) fn not_ready_reason(
223        &self,
224        registration: &crate::registry::ModuleRegistration,
225    ) -> Option<NotReadyReason> {
226        if !registration.ready {
227            return Some(NotReadyReason {
228                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
229                capability: None,
230            });
231        }
232        self.first_unprovided_required_capability(registration)
233            .map(|capability| NotReadyReason {
234                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
235                capability: Some(capability),
236            })
237    }
238
239    /// The lexicographically first capability this registration declares
240    /// `need: required` whose evaluator verdict is not `provided`.
241    ///
242    /// The verdicts are the capability evaluator's own; nothing here decides
243    /// what "provided" means. The evaluator counts a capability provided as
244    /// soon as a module claiming it has REGISTERED, not once that module is
245    /// ready. That distinction is what keeps two modules that require each
246    /// other's capabilities from deadlocking: if "provided" meant "the claimant
247    /// is ready", each would wait for the other to become ready first and
248    /// neither ever would. Do not tighten it to readiness.
249    ///
250    /// A required capability with no verdict at all means this registration's
251    /// HELLO or catalog.update landed after the last recompute; recompute once
252    /// rather than let a missing verdict read as either answer. If it is still
253    /// missing (the recompute itself failed) the capability counts as
254    /// unprovided: the refusal is retryable, and routing a module whose
255    /// required provider is unknown is the outcome this check exists to stop.
256    fn first_unprovided_required_capability(
257        &self,
258        registration: &crate::registry::ModuleRegistration,
259    ) -> Option<String> {
260        self.first_unprovided_required_capability_for(
261            &registration.manifest.module_id,
262            registration.manifest.capabilities.as_ref(),
263        )
264    }
265
266    pub(super) fn first_unprovided_required_capability_for(
267        &self,
268        module_id: &str,
269        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
270    ) -> Option<String> {
271        let required = capabilities
272            .into_iter()
273            .flat_map(|declarations| declarations.requires.iter())
274            .filter(|requirement| requirement.need == CapabilityNeed::Required)
275            .map(|requirement| requirement.capability.as_str())
276            .collect::<BTreeSet<_>>();
277        if required.is_empty() {
278            return None;
279        }
280        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
281        if required
282            .iter()
283            .any(|capability| verdict(capability).is_none())
284        {
285            self.refresh_capability_requirements();
286        }
287        required
288            .into_iter()
289            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
290            .map(str::to_string)
291    }
292
293    pub(super) fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
294        self.capability_evaluator
295            .statuses()
296            .into_iter()
297            .map(RequirementStatus::into_wire)
298            .collect()
299    }
300}
301
302pub(super) fn append_capability_problem_detail(
303    detail: Option<String>,
304    capability_detail: Option<String>,
305) -> Option<String> {
306    match (detail, capability_detail) {
307        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
308        (Some(detail), None) => Some(detail),
309        (None, Some(capability_detail)) => Some(capability_detail),
310        (None, None) => None,
311    }
312}
313
314/// Return whether a catalog change can create a newly violating live route.
315/// Removing an attested claim is intentionally excluded: it makes fewer routes
316/// forbidden and therefore must leave the existing route census untouched.
317pub(super) fn capability_census_trigger(
318    old: Option<&CapabilityDeclarations>,
319    new: Option<&CapabilityDeclarations>,
320) -> bool {
321    let old_provides = old
322        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
323        .unwrap_or_default();
324    let old_denies = old
325        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
326        .unwrap_or_default();
327    let new = new.cloned().unwrap_or(CapabilityDeclarations {
328        provides: Vec::new(),
329        requires: Vec::new(),
330        must_never_reach: Vec::new(),
331    });
332
333    new.provides
334        .iter()
335        .any(|capability| !old_provides.contains(capability))
336        || new
337            .must_never_reach
338            .iter()
339            .any(|capability| !old_denies.contains(capability))
340}