Skip to main content

liminal_server/server/connection/supervisor/
builder.rs

1use super::{
2    Arc, AuthConfig, ConnectionNotifier, ConnectionRuntime, ConnectionServices,
3    ConnectionSupervisor, LimitsConfig, PassVerifier, ServerError, SupervisorInner,
4};
5
6/// The configured `[auth]` section as the supervisor carries it: the bearer
7/// token as opaque bytes for the handshake's constant-time comparison, and the
8/// registry pass verifier built from `auth.pass` when one is configured. The
9/// single derivation behind [`ConnectionSupervisor::from_config`] and
10/// [`ConnectionSupervisorBuilder::auth`], so the two cannot drift.
11pub(super) fn configured_authentication(
12    auth: &AuthConfig,
13) -> Result<(Vec<u8>, Option<PassVerifier>), ServerError> {
14    let pass_verifier = PassVerifier::from_auth(auth)?;
15    Ok((auth.token.clone().into_bytes(), pass_verifier))
16}
17
18/// Composes a [`ConnectionSupervisor`] over caller-owned services.
19///
20/// Any of the optional parts — `[auth]` (bearer + pass verifier), a connection
21/// notifier, operational limits — can be set together. Minted by
22/// [`ConnectionSupervisor::builder`].
23pub struct ConnectionSupervisorBuilder {
24    pub(super) services: Arc<dyn ConnectionServices>,
25    pub(super) notifier: Option<Arc<dyn ConnectionNotifier>>,
26    pub(super) auth_token: Option<Vec<u8>>,
27    pub(super) pass_verifier: Option<PassVerifier>,
28    pub(super) lys: Option<LysInstall>,
29    pub(super) limits: LimitsConfig,
30}
31
32// The bearer token prints as its length, never its bytes (PROTO-007 R2).
33impl std::fmt::Debug for ConnectionSupervisorBuilder {
34    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        formatter
36            .debug_struct("ConnectionSupervisorBuilder")
37            .field("services", &self.services)
38            .field("notifier", &self.notifier)
39            .field("auth_token_len", &self.auth_token.as_ref().map(Vec::len))
40            .field("pass_verifier", &self.pass_verifier)
41            .field("lys", &self.lys)
42            .field("limits", &self.limits)
43            .finish()
44    }
45}
46
47/// What `[auth.lys]` installs on the connection runtime: the admitter with
48/// the network id its subjects are placed under (ACCESS-001 R2), the
49/// machine's link host (ACCESS-002 R1), the service bindings (ACCESS-003 R1)
50/// and the channel membership gate (ACCESS-006 R1).
51#[derive(Debug)]
52pub struct LysInstall {
53    /// Admits a Lys pass at `Connect` and decides its routes.
54    pub(crate) admitter: Arc<dyn crate::auth_lys::session::LysAdmitter>,
55    /// The network every subject is placed under.
56    pub(crate) network_id: String,
57    /// This machine's link host, `[auth.lys.machine]`.
58    pub(crate) link_host: Option<Arc<crate::link::LinkHost>>,
59    /// The service effect seams, `[auth.lys.services]`.
60    pub(crate) services: Option<Arc<crate::services::production::ServiceBindings>>,
61    /// The channel membership gate `[auth.lys.membership]` configures, over
62    /// the same issuer.
63    pub(crate) membership: Option<Arc<crate::auth_membership::MembershipGate>>,
64}
65
66/// The tokio runtime Lys is asked on, live deliberate decisions and the
67/// service bindings' HTTP alike, owned by the server for its life; `None`
68/// without `[auth.lys]`. One worker: every ask is one short request made
69/// from a connection's slice through `Handle::block_on` on a scoped thread,
70/// never a runtime nested in the connection scheduler.
71///
72/// # Errors
73/// The runtime could not start, by name.
74pub fn lys_ask_runtime(
75    auth: Option<&AuthConfig>,
76) -> Result<Option<tokio::runtime::Runtime>, ServerError> {
77    if auth.is_none_or(|auth| auth.lys.is_none()) {
78        return Ok(None);
79    }
80    tokio::runtime::Builder::new_multi_thread()
81        .worker_threads(1)
82        .thread_name("liminal-lys-ask")
83        .enable_all()
84        .build()
85        .map(Some)
86        .map_err(|error| ServerError::ConfigValidation {
87            message: format!("the Lys ask runtime could not start: {error}"),
88        })
89}
90
91/// Builds the Lys admitter `[auth.lys]` configures, reading the issuer's key
92/// set once; `None` without the section. `ask_handle` is the runtime live
93/// asks run on ([`lys_ask_runtime`], or an embedder's own); `auth.lys.live`
94/// without one is refused at start, by name.
95///
96/// # Errors
97/// A key set, pass or identity that cannot be read or is refused, by name.
98pub fn configured_lys(
99    auth: &AuthConfig,
100    ask_handle: Option<tokio::runtime::Handle>,
101) -> Result<Option<LysInstall>, ServerError> {
102    Ok(lys_install(auth, ask_handle, false)?.map(|(install, _)| install))
103}
104
105/// [`configured_lys`] for a server that binds before it asks: the machine
106/// pass's first issue, when nothing built before the bind reads the pass,
107/// is returned to be begun once the listener binds (SRV-041 R4).
108///
109/// # Errors
110/// As [`configured_lys`].
111pub fn configured_lys_after_bind(
112    auth: &AuthConfig,
113    ask_handle: Option<tokio::runtime::Handle>,
114) -> Result<(Option<LysInstall>, Option<crate::link_pass::StartIssue>), ServerError> {
115    Ok(lys_install(auth, ask_handle, true)?
116        .map_or((None, None), |(install, issue)| (Some(install), issue)))
117}
118
119fn lys_install(
120    auth: &AuthConfig,
121    ask_handle: Option<tokio::runtime::Handle>,
122    after_bind: bool,
123) -> Result<Option<(LysInstall, Option<crate::link_pass::StartIssue>)>, ServerError> {
124    let Some(lys) = auth.lys.as_ref() else {
125        return Ok(None);
126    };
127    let keys_json =
128        std::fs::read_to_string(&lys.keys_path).map_err(|error| ServerError::ConfigValidation {
129            message: format!("auth.lys.keys_path {}: {error}", lys.keys_path.display()),
130        })?;
131    let mut adapter = crate::auth_lys::lys_pass_adapter::LysPassAdapter::from_keys_json(
132        &keys_json,
133        lys.issuer.clone(),
134    )
135    .map_err(|error| ServerError::ConfigValidation {
136        message: format!("auth.lys key set refused: {error}"),
137    })?;
138    if lys.live {
139        // Deliberate decisions ask the issuer live, with the holder's pass,
140        // on the server's runtime; the ask never nests a runtime.
141        let Some(handle) = ask_handle.as_ref() else {
142            return Err(ServerError::ConfigValidation {
143                message:
144                    "auth.lys.live needs the server's Lys ask runtime at start; none was given"
145                        .to_owned(),
146            });
147        };
148        let mut live = crate::auth_lys::live::HttpLysAsk::new(
149            lys.api_url.as_deref().unwrap_or(&lys.issuer),
150            handle.clone(),
151        )
152        .map_err(|error| ServerError::ConfigValidation {
153            message: format!("auth.lys.issuer refused for live asks: {error}"),
154        })?;
155        // Lys answers its batch check for an administrator or an app, never
156        // a seat's pass: with an app credential configured the question is
157        // asked as this liminal, about the holder.
158        if let Some(path) = lys.app_credential_path.as_ref() {
159            let credential =
160                std::fs::read_to_string(path).map_err(|error| ServerError::ConfigValidation {
161                    message: format!(
162                        "auth.lys.app_credential_path '{}' cannot be read: {}",
163                        path.display(),
164                        error.kind()
165                    ),
166                })?;
167            live = live.asking_as(credential.trim().to_owned());
168        }
169        adapter = adapter.with_live(Arc::new(live));
170    }
171    let adapter = Arc::new(adapter);
172    let now = std::time::SystemTime::now()
173        .duration_since(std::time::UNIX_EPOCH)
174        .map_err(|_| ServerError::ConfigValidation {
175            message: "machine pass clock is before the Unix epoch".to_owned(),
176        })?
177        .as_secs();
178    let machine_pass = crate::link_pass::configured(lys, adapter, ask_handle, now, after_bind)?;
179    let membership = lys
180        .membership
181        .as_ref()
182        .map(|membership| crate::auth_membership::configured_gate(membership, &lys.issuer))
183        .transpose()?;
184    Ok(Some((
185        LysInstall {
186            admitter: machine_pass.admitter,
187            network_id: lys.network_id.clone(),
188            link_host: machine_pass.host,
189            services: None,
190            membership,
191        },
192        machine_pass.issue,
193    )))
194}
195
196impl ConnectionSupervisorBuilder {
197    /// Installs the configured `[auth]` section: the bearer token, and the
198    /// registry pass verifier when `auth.pass` is present — derived exactly as
199    /// [`ConnectionSupervisor::from_config`] derives them.
200    ///
201    /// # Errors
202    /// Returns [`ServerError::ConfigValidation`] when `auth.pass` names a key
203    /// that is not exactly one valid Ed25519 verifying key as 64 hexadecimal
204    /// digits — the same error, with the same text, that `from_config` returns
205    /// for that configuration.
206    pub fn auth(mut self, auth: &AuthConfig) -> Result<Self, ServerError> {
207        let (auth_token, pass_verifier) = configured_authentication(auth)?;
208        self.auth_token = Some(auth_token);
209        self.pass_verifier = pass_verifier;
210        self.lys = configured_lys(auth, tokio::runtime::Handle::try_current().ok())?;
211        Ok(self)
212    }
213
214    /// Test seam: installs `lys` exactly as `[auth.lys]` would, with no
215    /// configuration file and no issuer key behind it.
216    #[cfg(test)]
217    #[must_use]
218    pub(in crate::server::connection) fn lys_for_tests(mut self, lys: LysInstall) -> Self {
219        self.lys = Some(lys);
220        self
221    }
222
223    /// Installs the connection-keyed notifier, invoked on worker registration
224    /// lifecycle and on pass-stamped attach/detach.
225    #[must_use]
226    pub fn notifier(mut self, notifier: Arc<dyn ConnectionNotifier>) -> Self {
227        self.notifier = Some(notifier);
228        self
229    }
230
231    /// Installs the operational limits (§5); unset, the signed defaults apply.
232    #[must_use]
233    pub const fn limits(mut self, limits: LimitsConfig) -> Self {
234        self.limits = limits;
235        self
236    }
237
238    /// Starts the supervisor.
239    ///
240    /// # Errors
241    /// Returns [`ServerError`] when incarnation startup or scheduler startup
242    /// fails.
243    pub fn build(self) -> Result<ConnectionSupervisor, ServerError> {
244        SupervisorInner::new(
245            self.services,
246            self.notifier,
247            self.auth_token,
248            self.pass_verifier,
249            self.lys,
250            self.limits,
251            None,
252        )
253        .map(|inner| ConnectionSupervisor {
254            inner: Arc::new(inner),
255        })
256    }
257}
258
259/// Installs the `[auth.lys]` parts on the runtime, each once: the admitter,
260/// the link host, the membership gate and the service bindings.
261pub(super) fn install_lys(runtime: &ConnectionRuntime, lys: LysInstall) -> Result<(), ServerError> {
262    let LysInstall {
263        admitter,
264        network_id,
265        link_host,
266        services: bindings,
267        membership,
268    } = lys;
269    runtime
270        .install_lys_admitter(admitter, network_id)
271        .map_err(|_| ServerError::ConfigValidation {
272            message: "auth.lys admitter was already installed".to_owned(),
273        })?;
274    if let Some(host) = link_host {
275        runtime
276            .install_link_host(host)
277            .map_err(|_| ServerError::ConfigValidation {
278                message: "auth.lys.machine was already installed".to_owned(),
279            })?;
280    }
281    if let Some(gate) = membership {
282        runtime
283            .install_membership_gate(gate)
284            .map_err(|_| ServerError::ConfigValidation {
285                message: "auth.lys.membership was already installed".to_owned(),
286            })?;
287    }
288    if let Some(bindings) = bindings {
289        runtime
290            .install_service_bindings(bindings)
291            .map_err(|_| ServerError::ConfigValidation {
292                message: "auth.lys.services was already installed".to_owned(),
293            })?;
294    }
295    Ok(())
296}