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.check().is_ok() {
133            self.commit_verified_route_policies();
134        }
135    }
136
137    pub(super) fn commit_verified_route_policies(&mut self) {
138        if self.store.loaded_anchor_pending() || self.store.usable().is_err() {
139            return;
140        }
141        let active = self
142            .store
143            .loaded_admission_state()
144            .1
145            .versions
146            .iter()
147            .filter_map(|(tuple, versions)| {
148                versions
149                    .active
150                    .map(|generation| (tuple.module.clone(), generation))
151            })
152            .collect::<Vec<_>>();
153        for (module, generation) in active {
154            self.commit_route_policy(&module, generation);
155        }
156    }
157}
158
159pub(super) fn restore_superseded(
160    receipts: &mut BTreeMap<(String, u64), PendingRoutePolicy>,
161    installed: &mut BTreeMap<String, u64>,
162    modules: &BTreeSet<String>,
163    delivery: &mut delivery::DeliveryState,
164) {
165    let pending: Vec<_> = receipts
166        .keys()
167        .filter(|(module, _)| modules.contains(module))
168        .cloned()
169        .collect();
170    for (module, generation) in pending {
171        if let Some(mut pending) = receipts.remove(&(module.clone(), generation)) {
172            pending.installation.restore();
173            if let Some(previous) = pending.previous_generation {
174                installed.insert(module.clone(), previous);
175            } else {
176                installed.remove(&module);
177            }
178            delivery.invalidate_policy(&module, generation);
179        }
180    }
181}
182
183pub(super) fn required(changeset: &Changeset, module: &str) -> bool {
184    changeset.fields.iter().any(|field| {
185        field.module_id == module && field.apply == subc_config::ApplyKind::RouteRebind
186    })
187}
188
189pub(super) fn ready(state: &mut OwnerState, module: &str, generation: u64) -> Result<bool> {
190    state.store.body()?;
191    Ok(ready_loaded(state, module, generation))
192}
193
194pub(super) fn ready_loaded(state: &OwnerState, module: &str, generation: u64) -> bool {
195    let required = state
196        .store
197        .loaded_admission_state()
198        .1
199        .generations
200        .get(&generation)
201        .is_some_and(|entry| required(&entry.generation.changeset, module));
202    !required || state.installed_route_policies.get(module) == Some(&generation)
203}
204
205impl RuntimeOwner {
206    pub(crate) fn route_policy_authorized(&self, policy: &ApprovedRoutePolicy) -> Result<bool> {
207        // Runs under the forwarding write lock, as the authorization callback of
208        // `ForwardingTable::rebind_module_policy`. The owner's state is taken
209        // before the forwarding lock elsewhere (lowering a first-party mark), so
210        // this only ever try-locks it: a busy owner defers the install for a
211        // retry instead of waiting, and the two can never deadlock.
212        let Some((connection, attempt, deadline)) = policy.authorization else {
213            return Ok(true);
214        };
215        if tokio::time::Instant::now() >= deadline {
216            return Ok(false);
217        }
218        let state = self.inner.try_lock().map_err(|_| {
219            GateError::new(
220                "config_delivery_deferred",
221                "configuration publication is busy",
222            )
223        })?;
224        Ok(
225            state.active_declarations.get(&policy.module) == Some(&connection)
226                && state.delivery.policy_authorization(
227                    &policy.module,
228                    policy.generation,
229                    connection,
230                ) == Some((attempt, deadline)),
231        )
232    }
233    pub fn with_route_policy_authority(self, authority: Arc<dyn RoutePolicyAuthority>) -> Self {
234        let _ = self.route_policy_authority.set(authority);
235        self
236    }
237
238    pub(crate) fn install_module_route_authority(&self, authority: Arc<dyn RoutePolicyAuthority>) {
239        let _ = self.route_policy_authority.set(authority);
240    }
241
242    pub(super) fn check_route_policy_authority(&self, changeset: &Changeset) -> Result<()> {
243        if self.route_policy_authority.get().is_none()
244            && changeset
245                .fields
246                .iter()
247                .any(|field| field.apply == subc_config::ApplyKind::RouteRebind)
248        {
249            return Err(GateError::new("route_policy_authority_unavailable",
250                "config_gated: RoutePolicyAuthority is absent; approved route policy cannot be installed and affected routes and stamps cannot be revoked"));
251        }
252        if self
253            .route_policy_authority
254            .get()
255            .is_some_and(|authority| authority.requires_module_ack())
256            && changeset.fields.iter().any(|field| {
257                field.apply == subc_config::ApplyKind::RouteRebind && field.module_id == "subc"
258            })
259        {
260            return Err(GateError::new("daemon_route_policy_authority_unavailable", "daemon-owned route_rebind policy is not supported; scope authority changes require daemon restart"));
261        }
262        Ok(())
263    }
264
265    /// Called under the module configuration lock after an admitted replacement
266    /// starts, if this generation requires one. Only saved approved bytes are
267    /// passed to the policy adapter.
268    pub(crate) async fn install_approved_route_policy(
269        self: &std::sync::Arc<Self>,
270        module: &str,
271        generation: u64,
272    ) -> Result<()> {
273        let authority = self.route_policy_authority.get().ok_or_else(|| {
274            GateError::new(
275                "route_policy_authority_unavailable",
276                "config_gated: RoutePolicyAuthority is absent",
277            )
278        })?;
279        let authorization = if authority.requires_module_ack() {
280            let module_id = module.to_owned();
281            let authorization = self
282                .on_blocking(move |owner| {
283                    let mut state = owner.lock()?;
284                    let authorization =
285                        state
286                            .active_declarations
287                            .get(&module_id)
288                            .and_then(|connection| {
289                                state
290                                    .delivery
291                                    .policy_authorization(&module_id, generation, *connection)
292                                    .map(|(attempt, deadline)| (*connection, attempt, deadline))
293                            });
294                    if authorization.is_none() {
295                        state.restore_route_policy(&module_id, generation);
296                    }
297                    Ok(authorization)
298                })
299                .await?;
300            let Some(authorization) = authorization else {
301                return Ok(());
302            };
303            Some(authorization)
304        } else {
305            None
306        };
307        let module_id = module.to_owned();
308        let prepared = self
309            .on_blocking(move |owner| owner.prepare_route_policy(&module_id, generation))
310            .await?;
311        let Some((mut policy, previous_generation)) = prepared else {
312            return Ok(());
313        };
314        policy.authorization = authorization;
315        if !self.route_policy_authorized(&policy)? {
316            return Ok(());
317        }
318        let installation = match authority.install_and_revoke(policy).await {
319            Ok(installation) => installation,
320            Err(error) => {
321                let module_id = module.to_owned();
322                self.on_blocking(move |owner| {
323                    owner.lock()?.restore_route_policy(&module_id, generation);
324                    Ok(())
325                })
326                .await?;
327                return Err(error);
328            }
329        };
330        let module = module.to_owned();
331        self.on_blocking(move |owner| {
332            owner.finish_route_policy(&module, generation, previous_generation, installation)
333        })
334        .await
335    }
336
337    fn prepare_route_policy(
338        &self,
339        module: &str,
340        generation: u64,
341    ) -> Result<Option<(ApprovedRoutePolicy, Option<u64>)>> {
342        let mut state = self.lock()?;
343        state.store.delivery_ready()?;
344        if ready(&mut state, module, generation)? {
345            return Ok(None);
346        }
347        let body = state.store.body()?;
348        if !body.versions.iter().any(|(tuple, versions)| {
349            tuple.module == module
350                && tuple.project.is_none()
351                && (versions.pending == Some(generation) || versions.active == Some(generation))
352        }) {
353            return Err(GateError::new(
354                "delivery_superseded",
355                "route policy generation is no longer pending",
356            ));
357        }
358        let previous_generation = body
359            .versions
360            .iter()
361            .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())
362            .and_then(|(_, versions)| versions.active);
363        let entry = body.generations.get(&generation).ok_or_else(|| {
364            GateError::new("config_gated", "approved route policy generation is absent")
365        })?;
366        Ok(Some((
367            ApprovedRoutePolicy {
368                authorization: None,
369                module: module.into(),
370                generation,
371                digest: entry.generation.plan_digest.clone(),
372                changeset: entry.generation.changeset.clone(),
373                delivery: entry.delivery.clone().ok_or_else(|| {
374                    GateError::new("config_gated", "approved route policy bytes are absent")
375                })?,
376            },
377            previous_generation,
378        )))
379    }
380
381    fn finish_route_policy(
382        &self,
383        module: &str,
384        generation: u64,
385        previous_generation: Option<u64>,
386        installation: RoutePolicyInstallation,
387    ) -> Result<()> {
388        {
389            let mut state = self.lock()?;
390            if !state
391                .store
392                .body()?
393                .versions
394                .iter()
395                .any(|(tuple, versions)| {
396                    tuple.module == module
397                        && tuple.project.is_none()
398                        && (versions.pending == Some(generation)
399                            || versions.active == Some(generation))
400                })
401            {
402                return Err(GateError::new(
403                    "delivery_superseded",
404                    "route policy generation was superseded during installation",
405                ));
406            }
407            let target = state.active_declarations.get(module).copied();
408            state
409                .delivery
410                .policy_installed(module, generation, target)?;
411            state
412                .installed_route_policies
413                .insert(module.into(), generation);
414            state.route_policy_receipts.insert(
415                (module.into(), generation),
416                PendingRoutePolicy {
417                    installation,
418                    previous_generation,
419                },
420            );
421            state.commit_anchored_route_policies();
422        }
423        self.notify_delivery_changed();
424        Ok(())
425    }
426
427    pub(crate) fn route_policy_needed(&self, module: &str, generation: u64) -> Result<bool> {
428        let mut state = self.lock()?;
429        Ok(!ready(&mut state, module, generation)?)
430    }
431}