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