Skip to main content

subc_daemon/config_gate/
route_policy.rs

1//! Trusted installation boundary between reviewed config and live route authority.
2
3use crate::ConnectionId;
4use std::{future::Future, pin::Pin, sync::Arc};
5
6use super::*;
7
8/// Exact stored inputs for one approved transition. This value cannot be
9/// deserialized from a control request or assembled by an untrusted module.
10#[derive(Clone)]
11pub struct ApprovedRoutePolicy {
12    authorization: Option<(ConnectionId, u64, tokio::time::Instant)>,
13    module: String,
14    generation: u64,
15    digest: Digest,
16    changeset: Changeset,
17    delivery: DeliverySnapshot,
18}
19
20impl ApprovedRoutePolicy {
21    pub(crate) fn connection(&self) -> Option<ConnectionId> {
22        self.authorization.map(|(connection, _, _)| connection)
23    }
24    pub fn module(&self) -> &str {
25        &self.module
26    }
27    pub fn generation(&self) -> u64 {
28        self.generation
29    }
30    pub fn plan_digest(&self) -> &Digest {
31        &self.digest
32    }
33    pub fn changeset(&self) -> &Changeset {
34        &self.changeset
35    }
36    pub fn delivery(&self) -> &DeliverySnapshot {
37        &self.delivery
38    }
39}
40
41pub type RoutePolicyInstall<'a> =
42    Pin<Box<dyn Future<Output = Result<RoutePolicyInstallation>> + Send + 'a>>;
43
44/// In-memory policy restoration captured by the trusted route adapter. Both
45/// operations are infallible, bounded in-memory changes; they cannot await,
46/// perform I/O, or reacquire the configuration store or module lock. Restoring
47/// policy does not resurrect closed routes or their revoked permission stamps.
48pub trait RoutePolicyReceipt: Send {
49    fn commit(&mut self);
50    fn restore(&mut self);
51}
52
53/// Owned reversible installation. Dropping an unresolved installation restores
54/// its captured policy, including a pre-gate policy absent from store history.
55pub struct RoutePolicyInstallation {
56    receipt: Option<Box<dyn RoutePolicyReceipt>>,
57}
58
59impl RoutePolicyInstallation {
60    pub fn new(receipt: Box<dyn RoutePolicyReceipt>) -> Self {
61        Self {
62            receipt: Some(receipt),
63        }
64    }
65    pub fn commit(&mut self) {
66        if let Some(mut receipt) = self.receipt.take() {
67            receipt.commit();
68        }
69    }
70    pub fn restore(&mut self) {
71        if let Some(mut receipt) = self.receipt.take() {
72            receipt.restore();
73        }
74    }
75}
76
77impl Drop for RoutePolicyInstallation {
78    fn drop(&mut self) {
79        self.restore();
80    }
81}
82
83/// The daemon's route-policy adapter, supplied through its Rust constructor.
84/// Success means affected routes and the stamps granting their permissions
85/// have been revoked, and every new route.open reads the exact approved policy.
86/// The delivery caller holds the module configuration lock, but not the store
87/// mutex, across this call. An implementation must not reacquire that lock or
88/// report success after merely requesting an asynchronous policy reload.
89/// Its future must retain a restoration guard before changing authority, so
90/// cancellation also restores the previous policy. Daemon restart rebuilds
91/// authority from the durable active generation, or from the configuration files
92/// used before approval was enabled when no active generation has been recorded.
93pub trait RoutePolicyAuthority: Send + Sync {
94    /// Module-owned bind policy is installed by the module's delivery ACK.
95    fn requires_module_ack(&self) -> bool {
96        false
97    }
98    fn install_and_revoke<'a>(&'a self, policy: ApprovedRoutePolicy) -> RoutePolicyInstall<'a>;
99}
100
101pub(super) struct PendingRoutePolicy {
102    installation: RoutePolicyInstallation,
103    previous_generation: Option<u64>,
104}
105
106impl OwnerState {
107    pub(super) fn restore_route_policy(&mut self, module: &str, generation: u64) {
108        if let Some(mut pending) = self
109            .route_policy_receipts
110            .remove(&(module.into(), generation))
111        {
112            pending.installation.restore();
113            if let Some(previous) = pending.previous_generation {
114                self.installed_route_policies
115                    .insert(module.into(), previous);
116            } else {
117                self.installed_route_policies.remove(module);
118            }
119        }
120    }
121
122    pub(super) fn commit_route_policy(&mut self, module: &str, generation: u64) {
123        if let Some(mut pending) = self
124            .route_policy_receipts
125            .remove(&(module.into(), generation))
126        {
127            pending.installation.commit();
128        }
129    }
130
131    pub(super) fn commit_anchored_route_policies(&mut self) {
132        if self.store.status().anchor_pending {
133            return;
134        }
135        let active = self
136            .store
137            .body()
138            .map(|body| {
139                body.versions
140                    .iter()
141                    .filter_map(|(tuple, versions)| {
142                        versions
143                            .active
144                            .map(|generation| (tuple.module.clone(), generation))
145                    })
146                    .collect::<Vec<_>>()
147            })
148            .unwrap_or_default();
149        for (module, generation) in active {
150            self.commit_route_policy(&module, generation);
151        }
152    }
153}
154
155pub(super) fn restore_superseded(
156    receipts: &mut BTreeMap<(String, u64), PendingRoutePolicy>,
157    installed: &mut BTreeMap<String, u64>,
158    modules: &BTreeSet<String>,
159    delivery: &mut delivery::DeliveryState,
160) {
161    let pending: Vec<_> = receipts
162        .keys()
163        .filter(|(module, _)| modules.contains(module))
164        .cloned()
165        .collect();
166    for (module, generation) in pending {
167        if let Some(mut pending) = receipts.remove(&(module.clone(), generation)) {
168            pending.installation.restore();
169            if let Some(previous) = pending.previous_generation {
170                installed.insert(module.clone(), previous);
171            } else {
172                installed.remove(&module);
173            }
174            delivery.invalidate_policy(&module, generation);
175        }
176    }
177}
178
179pub(super) fn required(changeset: &Changeset, module: &str) -> bool {
180    changeset.fields.iter().any(|field| {
181        field.module_id == module && field.apply == subc_config::ApplyKind::RouteRebind
182    })
183}
184
185pub(super) fn ready(state: &mut OwnerState, module: &str, generation: u64) -> Result<bool> {
186    state.store.body()?;
187    Ok(ready_loaded(state, module, generation))
188}
189
190pub(super) fn ready_loaded(state: &OwnerState, module: &str, generation: u64) -> bool {
191    let required = state
192        .store
193        .loaded_admission_state()
194        .1
195        .generations
196        .get(&generation)
197        .is_some_and(|entry| required(&entry.generation.changeset, module));
198    !required || state.installed_route_policies.get(module) == Some(&generation)
199}
200
201impl RuntimeOwner {
202    pub(crate) fn route_policy_authorized(&self, policy: &ApprovedRoutePolicy) -> Result<bool> {
203        let Some((connection, attempt, deadline)) = policy.authorization else {
204            return Ok(true);
205        };
206        if tokio::time::Instant::now() >= deadline {
207            return Ok(false);
208        }
209        let state = self.inner.try_lock().map_err(|_| {
210            GateError::new(
211                "config_delivery_deferred",
212                "configuration publication is busy",
213            )
214        })?;
215        Ok(
216            state.active_declarations.get(&policy.module) == Some(&connection)
217                && state.delivery.policy_authorization(
218                    &policy.module,
219                    policy.generation,
220                    connection,
221                ) == Some((attempt, deadline)),
222        )
223    }
224    pub fn with_route_policy_authority(self, authority: Arc<dyn RoutePolicyAuthority>) -> Self {
225        let _ = self.route_policy_authority.set(authority);
226        self
227    }
228
229    pub(crate) fn install_module_route_authority(&self, authority: Arc<dyn RoutePolicyAuthority>) {
230        let _ = self.route_policy_authority.set(authority);
231    }
232
233    pub(super) fn check_route_policy_authority(&self, changeset: &Changeset) -> Result<()> {
234        if self.route_policy_authority.get().is_none()
235            && changeset
236                .fields
237                .iter()
238                .any(|field| field.apply == subc_config::ApplyKind::RouteRebind)
239        {
240            return Err(GateError::new("route_policy_authority_unavailable",
241                "config_gated: RoutePolicyAuthority is absent; approved route policy cannot be installed and affected routes and stamps cannot be revoked"));
242        }
243        if self
244            .route_policy_authority
245            .get()
246            .is_some_and(|authority| authority.requires_module_ack())
247            && changeset.fields.iter().any(|field| {
248                field.apply == subc_config::ApplyKind::RouteRebind && field.module_id == "subc"
249            })
250        {
251            return Err(GateError::new("daemon_route_policy_authority_unavailable", "daemon-owned route_rebind policy is not supported; scope authority changes require daemon restart"));
252        }
253        Ok(())
254    }
255
256    /// Called under the module configuration lock after an admitted replacement
257    /// starts, if this generation requires one. Only saved approved bytes are
258    /// passed to the policy adapter.
259    pub(crate) async fn install_approved_route_policy(
260        self: &std::sync::Arc<Self>,
261        module: &str,
262        generation: u64,
263    ) -> Result<()> {
264        let authority = self.route_policy_authority.get().ok_or_else(|| {
265            GateError::new(
266                "route_policy_authority_unavailable",
267                "config_gated: RoutePolicyAuthority is absent",
268            )
269        })?;
270        let authorization = if authority.requires_module_ack() {
271            let module_id = module.to_owned();
272            let authorization = self
273                .on_blocking(move |owner| {
274                    let mut state = owner.lock()?;
275                    let authorization =
276                        state
277                            .active_declarations
278                            .get(&module_id)
279                            .and_then(|connection| {
280                                state
281                                    .delivery
282                                    .policy_authorization(&module_id, generation, *connection)
283                                    .map(|(attempt, deadline)| (*connection, attempt, deadline))
284                            });
285                    if authorization.is_none() {
286                        state.restore_route_policy(&module_id, generation);
287                    }
288                    Ok(authorization)
289                })
290                .await?;
291            let Some(authorization) = authorization else {
292                return Ok(());
293            };
294            Some(authorization)
295        } else {
296            None
297        };
298        let module_id = module.to_owned();
299        let prepared = self
300            .on_blocking(move |owner| owner.prepare_route_policy(&module_id, generation))
301            .await?;
302        let Some((mut policy, previous_generation)) = prepared else {
303            return Ok(());
304        };
305        policy.authorization = authorization;
306        if !self.route_policy_authorized(&policy)? {
307            return Ok(());
308        }
309        let installation = match authority.install_and_revoke(policy).await {
310            Ok(installation) => installation,
311            Err(error) => {
312                let module_id = module.to_owned();
313                self.on_blocking(move |owner| {
314                    owner.lock()?.restore_route_policy(&module_id, generation);
315                    Ok(())
316                })
317                .await?;
318                return Err(error);
319            }
320        };
321        let module = module.to_owned();
322        self.on_blocking(move |owner| {
323            owner.finish_route_policy(&module, generation, previous_generation, installation)
324        })
325        .await
326    }
327
328    fn prepare_route_policy(
329        &self,
330        module: &str,
331        generation: u64,
332    ) -> Result<Option<(ApprovedRoutePolicy, Option<u64>)>> {
333        let mut state = self.lock()?;
334        state.store.delivery_ready()?;
335        if ready(&mut state, module, generation)? {
336            return Ok(None);
337        }
338        let body = state.store.body()?;
339        if !body.versions.iter().any(|(tuple, versions)| {
340            tuple.module == module
341                && tuple.project.is_none()
342                && (versions.pending == Some(generation) || versions.active == Some(generation))
343        }) {
344            return Err(GateError::new(
345                "delivery_superseded",
346                "route policy generation is no longer pending",
347            ));
348        }
349        let previous_generation = body
350            .versions
351            .iter()
352            .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())
353            .and_then(|(_, versions)| versions.active);
354        let entry = body.generations.get(&generation).ok_or_else(|| {
355            GateError::new("config_gated", "approved route policy generation is absent")
356        })?;
357        Ok(Some((
358            ApprovedRoutePolicy {
359                authorization: None,
360                module: module.into(),
361                generation,
362                digest: entry.generation.plan_digest.clone(),
363                changeset: entry.generation.changeset.clone(),
364                delivery: entry.delivery.clone().ok_or_else(|| {
365                    GateError::new("config_gated", "approved route policy bytes are absent")
366                })?,
367            },
368            previous_generation,
369        )))
370    }
371
372    fn finish_route_policy(
373        &self,
374        module: &str,
375        generation: u64,
376        previous_generation: Option<u64>,
377        installation: RoutePolicyInstallation,
378    ) -> Result<()> {
379        {
380            let mut state = self.lock()?;
381            if !state
382                .store
383                .body()?
384                .versions
385                .iter()
386                .any(|(tuple, versions)| {
387                    tuple.module == module
388                        && tuple.project.is_none()
389                        && (versions.pending == Some(generation)
390                            || versions.active == Some(generation))
391                })
392            {
393                return Err(GateError::new(
394                    "delivery_superseded",
395                    "route policy generation was superseded during installation",
396                ));
397            }
398            let target = state.active_declarations.get(module).copied();
399            state
400                .delivery
401                .policy_installed(module, generation, target)?;
402            state
403                .installed_route_policies
404                .insert(module.into(), generation);
405            state.route_policy_receipts.insert(
406                (module.into(), generation),
407                PendingRoutePolicy {
408                    installation,
409                    previous_generation,
410                },
411            );
412            state.commit_anchored_route_policies();
413        }
414        self.notify_delivery_changed();
415        Ok(())
416    }
417
418    pub(crate) fn route_policy_needed(&self, module: &str, generation: u64) -> Result<bool> {
419        let mut state = self.lock()?;
420        Ok(!ready(&mut state, module, generation)?)
421    }
422}