subc-daemon 0.45.4

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Trusted installation boundary between reviewed config and live route authority.

use crate::ConnectionId;
use std::{future::Future, pin::Pin, sync::Arc};

use super::*;

/// Exact stored inputs for one approved transition. This value cannot be
/// deserialized from a control request or assembled by an untrusted module.
#[derive(Clone)]
pub struct ApprovedRoutePolicy {
    authorization: Option<(ConnectionId, u64, tokio::time::Instant)>,
    module: String,
    generation: u64,
    digest: Digest,
    changeset: Changeset,
    delivery: DeliverySnapshot,
}

impl ApprovedRoutePolicy {
    pub(crate) fn connection(&self) -> Option<ConnectionId> {
        self.authorization.map(|(connection, _, _)| connection)
    }
    pub fn module(&self) -> &str {
        &self.module
    }
    pub fn generation(&self) -> u64 {
        self.generation
    }
    pub fn plan_digest(&self) -> &Digest {
        &self.digest
    }
    pub fn changeset(&self) -> &Changeset {
        &self.changeset
    }
    pub fn delivery(&self) -> &DeliverySnapshot {
        &self.delivery
    }
}

pub type RoutePolicyInstall<'a> =
    Pin<Box<dyn Future<Output = Result<RoutePolicyInstallation>> + Send + 'a>>;

/// In-memory policy restoration captured by the trusted route adapter. Both
/// operations are infallible, bounded in-memory changes; they cannot await,
/// perform I/O, or reacquire the configuration store or module lock. Restoring
/// policy does not resurrect closed routes or their revoked permission stamps.
pub trait RoutePolicyReceipt: Send {
    fn commit(&mut self);
    fn restore(&mut self);
}

/// Owned reversible installation. Dropping an unresolved installation restores
/// its captured policy, including a pre-gate policy absent from store history.
pub struct RoutePolicyInstallation {
    receipt: Option<Box<dyn RoutePolicyReceipt>>,
}

impl RoutePolicyInstallation {
    pub fn new(receipt: Box<dyn RoutePolicyReceipt>) -> Self {
        Self {
            receipt: Some(receipt),
        }
    }
    pub fn commit(&mut self) {
        if let Some(mut receipt) = self.receipt.take() {
            receipt.commit();
        }
    }
    pub fn restore(&mut self) {
        if let Some(mut receipt) = self.receipt.take() {
            receipt.restore();
        }
    }
}

impl Drop for RoutePolicyInstallation {
    fn drop(&mut self) {
        self.restore();
    }
}

/// The daemon's route-policy adapter, supplied through its Rust constructor.
/// Success means affected routes and the stamps granting their permissions
/// have been revoked, and every new route.open reads the exact approved policy.
/// The delivery caller holds the module configuration lock, but not the store
/// mutex, across this call. An implementation must not reacquire that lock or
/// report success after merely requesting an asynchronous policy reload.
/// Its future must retain a restoration guard before changing authority, so
/// cancellation also restores the previous policy. Daemon restart rebuilds
/// authority from the durable active generation, or from the configuration files
/// used before approval was enabled when no active generation has been recorded.
pub trait RoutePolicyAuthority: Send + Sync {
    /// Module-owned bind policy is installed by the module's delivery ACK.
    fn requires_module_ack(&self) -> bool {
        false
    }
    fn install_and_revoke<'a>(&'a self, policy: ApprovedRoutePolicy) -> RoutePolicyInstall<'a>;
}

pub(super) struct PendingRoutePolicy {
    installation: RoutePolicyInstallation,
    previous_generation: Option<u64>,
}

impl OwnerState {
    pub(super) fn restore_route_policy(&mut self, module: &str, generation: u64) {
        if let Some(mut pending) = self
            .route_policy_receipts
            .remove(&(module.into(), generation))
        {
            pending.installation.restore();
            if let Some(previous) = pending.previous_generation {
                self.installed_route_policies
                    .insert(module.into(), previous);
            } else {
                self.installed_route_policies.remove(module);
            }
        }
    }

    pub(super) fn commit_route_policy(&mut self, module: &str, generation: u64) {
        if let Some(mut pending) = self
            .route_policy_receipts
            .remove(&(module.into(), generation))
        {
            pending.installation.commit();
        }
    }

    pub(super) fn commit_anchored_route_policies(&mut self) {
        if self.store.status().anchor_pending {
            return;
        }
        let active = self
            .store
            .body()
            .map(|body| {
                body.versions
                    .iter()
                    .filter_map(|(tuple, versions)| {
                        versions
                            .active
                            .map(|generation| (tuple.module.clone(), generation))
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        for (module, generation) in active {
            self.commit_route_policy(&module, generation);
        }
    }
}

pub(super) fn restore_superseded(
    receipts: &mut BTreeMap<(String, u64), PendingRoutePolicy>,
    installed: &mut BTreeMap<String, u64>,
    modules: &BTreeSet<String>,
    delivery: &mut delivery::DeliveryState,
) {
    let pending: Vec<_> = receipts
        .keys()
        .filter(|(module, _)| modules.contains(module))
        .cloned()
        .collect();
    for (module, generation) in pending {
        if let Some(mut pending) = receipts.remove(&(module.clone(), generation)) {
            pending.installation.restore();
            if let Some(previous) = pending.previous_generation {
                installed.insert(module.clone(), previous);
            } else {
                installed.remove(&module);
            }
            delivery.invalidate_policy(&module, generation);
        }
    }
}

pub(super) fn required(changeset: &Changeset, module: &str) -> bool {
    changeset.fields.iter().any(|field| {
        field.module_id == module && field.apply == subc_config::ApplyKind::RouteRebind
    })
}

pub(super) fn ready(state: &mut OwnerState, module: &str, generation: u64) -> Result<bool> {
    state.store.body()?;
    Ok(ready_loaded(state, module, generation))
}

pub(super) fn ready_loaded(state: &OwnerState, module: &str, generation: u64) -> bool {
    let required = state
        .store
        .loaded_admission_state()
        .1
        .generations
        .get(&generation)
        .is_some_and(|entry| required(&entry.generation.changeset, module));
    !required || state.installed_route_policies.get(module) == Some(&generation)
}

impl RuntimeOwner {
    pub(crate) fn route_policy_authorized(&self, policy: &ApprovedRoutePolicy) -> Result<bool> {
        let Some((connection, attempt, deadline)) = policy.authorization else {
            return Ok(true);
        };
        if tokio::time::Instant::now() >= deadline {
            return Ok(false);
        }
        let state = self.inner.try_lock().map_err(|_| {
            GateError::new(
                "config_delivery_deferred",
                "configuration publication is busy",
            )
        })?;
        Ok(
            state.active_declarations.get(&policy.module) == Some(&connection)
                && state.delivery.policy_authorization(
                    &policy.module,
                    policy.generation,
                    connection,
                ) == Some((attempt, deadline)),
        )
    }
    pub fn with_route_policy_authority(self, authority: Arc<dyn RoutePolicyAuthority>) -> Self {
        let _ = self.route_policy_authority.set(authority);
        self
    }

    pub(crate) fn install_module_route_authority(&self, authority: Arc<dyn RoutePolicyAuthority>) {
        let _ = self.route_policy_authority.set(authority);
    }

    pub(super) fn check_route_policy_authority(&self, changeset: &Changeset) -> Result<()> {
        if self.route_policy_authority.get().is_none()
            && changeset
                .fields
                .iter()
                .any(|field| field.apply == subc_config::ApplyKind::RouteRebind)
        {
            return Err(GateError::new("route_policy_authority_unavailable",
                "config_gated: RoutePolicyAuthority is absent; approved route policy cannot be installed and affected routes and stamps cannot be revoked"));
        }
        if self
            .route_policy_authority
            .get()
            .is_some_and(|authority| authority.requires_module_ack())
            && changeset.fields.iter().any(|field| {
                field.apply == subc_config::ApplyKind::RouteRebind && field.module_id == "subc"
            })
        {
            return Err(GateError::new("daemon_route_policy_authority_unavailable", "daemon-owned route_rebind policy is not supported; scope authority changes require daemon restart"));
        }
        Ok(())
    }

    /// Called under the module configuration lock after an admitted replacement
    /// starts, if this generation requires one. Only saved approved bytes are
    /// passed to the policy adapter.
    pub(crate) async fn install_approved_route_policy(
        self: &std::sync::Arc<Self>,
        module: &str,
        generation: u64,
    ) -> Result<()> {
        let authority = self.route_policy_authority.get().ok_or_else(|| {
            GateError::new(
                "route_policy_authority_unavailable",
                "config_gated: RoutePolicyAuthority is absent",
            )
        })?;
        let authorization = if authority.requires_module_ack() {
            let module_id = module.to_owned();
            let authorization = self
                .on_blocking(move |owner| {
                    let mut state = owner.lock()?;
                    let authorization =
                        state
                            .active_declarations
                            .get(&module_id)
                            .and_then(|connection| {
                                state
                                    .delivery
                                    .policy_authorization(&module_id, generation, *connection)
                                    .map(|(attempt, deadline)| (*connection, attempt, deadline))
                            });
                    if authorization.is_none() {
                        state.restore_route_policy(&module_id, generation);
                    }
                    Ok(authorization)
                })
                .await?;
            let Some(authorization) = authorization else {
                return Ok(());
            };
            Some(authorization)
        } else {
            None
        };
        let module_id = module.to_owned();
        let prepared = self
            .on_blocking(move |owner| owner.prepare_route_policy(&module_id, generation))
            .await?;
        let Some((mut policy, previous_generation)) = prepared else {
            return Ok(());
        };
        policy.authorization = authorization;
        if !self.route_policy_authorized(&policy)? {
            return Ok(());
        }
        let installation = match authority.install_and_revoke(policy).await {
            Ok(installation) => installation,
            Err(error) => {
                let module_id = module.to_owned();
                self.on_blocking(move |owner| {
                    owner.lock()?.restore_route_policy(&module_id, generation);
                    Ok(())
                })
                .await?;
                return Err(error);
            }
        };
        let module = module.to_owned();
        self.on_blocking(move |owner| {
            owner.finish_route_policy(&module, generation, previous_generation, installation)
        })
        .await
    }

    fn prepare_route_policy(
        &self,
        module: &str,
        generation: u64,
    ) -> Result<Option<(ApprovedRoutePolicy, Option<u64>)>> {
        let mut state = self.lock()?;
        state.store.delivery_ready()?;
        if ready(&mut state, module, generation)? {
            return Ok(None);
        }
        let body = state.store.body()?;
        if !body.versions.iter().any(|(tuple, versions)| {
            tuple.module == module
                && tuple.project.is_none()
                && (versions.pending == Some(generation) || versions.active == Some(generation))
        }) {
            return Err(GateError::new(
                "delivery_superseded",
                "route policy generation is no longer pending",
            ));
        }
        let previous_generation = body
            .versions
            .iter()
            .find(|(tuple, _)| tuple.module == module && tuple.project.is_none())
            .and_then(|(_, versions)| versions.active);
        let entry = body.generations.get(&generation).ok_or_else(|| {
            GateError::new("config_gated", "approved route policy generation is absent")
        })?;
        Ok(Some((
            ApprovedRoutePolicy {
                authorization: None,
                module: module.into(),
                generation,
                digest: entry.generation.plan_digest.clone(),
                changeset: entry.generation.changeset.clone(),
                delivery: entry.delivery.clone().ok_or_else(|| {
                    GateError::new("config_gated", "approved route policy bytes are absent")
                })?,
            },
            previous_generation,
        )))
    }

    fn finish_route_policy(
        &self,
        module: &str,
        generation: u64,
        previous_generation: Option<u64>,
        installation: RoutePolicyInstallation,
    ) -> Result<()> {
        {
            let mut state = self.lock()?;
            if !state
                .store
                .body()?
                .versions
                .iter()
                .any(|(tuple, versions)| {
                    tuple.module == module
                        && tuple.project.is_none()
                        && (versions.pending == Some(generation)
                            || versions.active == Some(generation))
                })
            {
                return Err(GateError::new(
                    "delivery_superseded",
                    "route policy generation was superseded during installation",
                ));
            }
            let target = state.active_declarations.get(module).copied();
            state
                .delivery
                .policy_installed(module, generation, target)?;
            state
                .installed_route_policies
                .insert(module.into(), generation);
            state.route_policy_receipts.insert(
                (module.into(), generation),
                PendingRoutePolicy {
                    installation,
                    previous_generation,
                },
            );
            state.commit_anchored_route_policies();
        }
        self.notify_delivery_changed();
        Ok(())
    }

    pub(crate) fn route_policy_needed(&self, module: &str, generation: u64) -> Result<bool> {
        let mut state = self.lock()?;
        Ok(!ready(&mut state, module, generation)?)
    }
}