Skip to main content

liminal_server/config/
types.rs

1use std::net::SocketAddr;
2use std::path::PathBuf;
3use std::time::Duration;
4
5use crate::ServerError;
6
7/// Declarative configuration for the standalone liminal server wrapper.
8#[derive(Debug, Clone, serde::Deserialize)]
9#[serde(deny_unknown_fields)]
10pub struct ServerConfig {
11    /// Socket address where the standalone server will listen for client traffic.
12    pub listen_address: SocketAddr,
13    /// Additional named wire addresses on an encrypted network, sharing admission.
14    #[serde(default)]
15    pub extra_listen_addresses: Vec<SocketAddr>,
16    /// Socket address where the health endpoint server will listen for probes.
17    pub health_listen_address: SocketAddr,
18    /// IGNORED SINCE 0.14.3. Kept only so an existing config file still loads.
19    ///
20    /// This was the maximum time shutdown would wait for existing connections
21    /// to hang up by themselves before closing them. Nothing reads it now.
22    ///
23    /// A drain exists to let in-flight requests finish. In this server every
24    /// write is durable and flushed BEFORE it is acknowledged, so at the
25    /// instant shutdown begins there is no in-flight request to finish and
26    /// nothing for the wait to buy. What it did in practice, on a deployment
27    /// whose connections are long-lived idle clients that never hang up on
28    /// their own, was spend its whole budget on every restart and then close
29    /// the connections anyway — 5 s per restart, measured on Tom Whiting's
30    /// estate on 2026-09-14. Shutdown now stops accepting, closes every
31    /// connection itself (an orderly close each peer reads as a shutdown), and
32    /// flushes durable state, with no timer in that path.
33    ///
34    /// Any value parses, including zero. Setting it changes nothing.
35    pub drain_timeout_ms: u64,
36    /// Channel topology definitions declared by the operator.
37    pub channels: Vec<ChannelDef>,
38    /// Declarative routing rules that connect configured channels.
39    pub routing_rules: Vec<RoutingRuleDef>,
40    /// Optional filesystem location for durable server state.
41    ///
42    /// A fresh boot surfaces `ConfigValidation` unless this path's PARENT
43    /// directory already exists: the haematite engine creates the store dir
44    /// exactly one level below a pre-existing parent it can fence (never
45    /// `create_dir_all` — deliberate upstream hardening). Create the parent;
46    /// the engine fences into it.
47    pub persistence_path: Option<PathBuf>,
48    /// Optional beamr distribution cluster membership configuration.
49    pub cluster: Option<ClusterConfig>,
50    /// Optional connection authentication configuration.
51    ///
52    /// When present, every client `Connect` handshake must carry a matching
53    /// `auth_token`; when absent the server is open (byte-identical to the
54    /// pre-auth behaviour). Not an ACL system — a single shared bearer token.
55    #[serde(default)]
56    pub auth: Option<AuthConfig>,
57    /// Service construction profile. Absent `[services]` (or an absent `profile`
58    /// key within it) defaults to `"full"`, so existing deployments build exactly
59    /// what they build today.
60    #[serde(default)]
61    pub services: ServicesConfig,
62    /// Operational bounds (§5). Absent `[limits]` (or any absent key within it)
63    /// defaults to the certifying-pair-signed numbers, so an operator who sets
64    /// nothing still runs bounded — "unlimited-by-silence is no longer a legal
65    /// state" (§5). Every value is a hard cap enforced by a typed refusal; a
66    /// zero (or otherwise invalid) value is a config validation error, never a
67    /// silent "unlimited".
68    #[serde(default)]
69    pub limits: LimitsConfig,
70    /// Optional WebSocket transport acceptor (LP-WS-TRANSPORT R1).
71    ///
72    /// When present the server binds a sibling WebSocket listener carrying the
73    /// canonical liminal wire protocol (one binary message per canonical frame)
74    /// alongside the main TCP listener. When absent NO HTTP/WebSocket listener
75    /// is started and the server behaves byte-identically to the pre-WebSocket
76    /// build. Every field inside is a deployment decision; the origin allow-list
77    /// FAILS CLOSED (an absent or empty list refuses every Origin-bearing
78    /// upgrade) and the keepalive ping interval is disabled unless explicitly
79    /// configured.
80    #[serde(default)]
81    pub websocket: Option<WebSocketConfig>,
82    /// Participant lifecycle activation (LP gap closure, Part B).
83    ///
84    /// When present the server installs the production participant semantic
85    /// handler and advertises the participant capability bit on every
86    /// connection. Every field inside is REQUIRED and carries NO default:
87    /// participant lifecycle values are deployment decisions, and an absent
88    /// field is a typed startup error rather than an assumed number. When the
89    /// section is absent the participant capability stays disabled and the
90    /// server behaves byte-identically to the pre-activation build.
91    #[serde(default)]
92    pub participant: Option<ParticipantConfig>,
93}
94
95impl ServerConfig {
96    /// Returns the configured drain timeout, which shutdown IGNORES since
97    /// 0.14.3.
98    ///
99    /// Retained so an embedder that reads it keeps compiling, and so the value
100    /// an operator wrote can still be named in the shutdown log line that
101    /// reports it ignored. See [`ServerConfig::drain_timeout_ms`].
102    #[must_use]
103    pub const fn drain_timeout(&self) -> Duration {
104        Duration::from_millis(self.drain_timeout_ms)
105    }
106}
107
108/// Declarative channel definition loaded from server configuration.
109#[derive(Debug, Clone, serde::Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct ChannelDef {
112    /// Unique channel name used by routing rules and operators.
113    pub name: String,
114    /// Filesystem path to a JSON Schema document that validates every message
115    /// published to this channel.
116    ///
117    /// The path is resolved relative to the directory containing the config file
118    /// (absolute paths are used verbatim). Config validation reads and parses the
119    /// referenced document and stores the result in [`Self::loaded_schema`]; a
120    /// missing file, an unreadable file, or a file that is not valid JSON is an
121    /// accumulated validation error that stops startup.
122    ///
123    /// `None` means the channel has no schema: it keeps the permissive empty
124    /// schema (`{}`) that accepts any JSON payload.
125    #[serde(default)]
126    pub schema_ref: Option<PathBuf>,
127    /// Whether this channel requires durable persistence.
128    pub durable: bool,
129    /// Schema document loaded and parsed from [`Self::schema_ref`] during config
130    /// validation. Populated only by [`crate::config::validate`]; a directly
131    /// constructed [`ChannelDef`] that skips validation carries `None` here and is
132    /// therefore built with the permissive empty schema regardless of
133    /// [`Self::schema_ref`]. Never deserialized from the config file.
134    #[serde(skip)]
135    pub loaded_schema: Option<LoadedSchema>,
136}
137
138/// A channel's JSON Schema document as loaded from disk during config validation.
139///
140/// Carries both the parsed document (fed to the validation engine when the channel
141/// is built) and the raw file bytes (hashed into the protocol schema id advertised
142/// at subscribe time, so an SDK deriving ids from the same schema bytes converges).
143#[derive(Debug, Clone)]
144pub struct LoadedSchema {
145    /// Raw bytes of the schema file, hashed to derive the protocol schema id.
146    pub bytes: Vec<u8>,
147    /// Parsed JSON Schema document, fed to the channel's validation engine.
148    pub document: serde_json::Value,
149}
150
151/// Declarative routing rule definition loaded from server configuration.
152#[derive(Debug, Clone, serde::Deserialize)]
153#[serde(deny_unknown_fields)]
154pub struct RoutingRuleDef {
155    /// Source channel name from which messages are routed.
156    pub source_channel: String,
157    /// Target channel name to which matching messages are routed.
158    pub target_channel: String,
159    /// Optional predicate expression that filters routed messages.
160    pub predicate: Option<String>,
161}
162
163/// Public beamr distribution cookie, refused during configuration validation.
164/// Mirrors beamr's own [`beamr::distribution::DEFAULT_COOKIE`].
165pub const DEFAULT_COOKIE: &str = "beamr-cookie";
166
167/// Beamr distribution for copies of one server on a trusted network.
168///
169/// Federation provides the network between servers; a cluster joins replicas
170/// of the same server using an explicitly configured shared secret cookie.
171#[derive(Debug, Clone, serde::Deserialize)]
172#[serde(deny_unknown_fields)]
173pub struct ClusterConfig {
174    /// Unique node name advertised to the beamr distribution cluster.
175    pub node_name: String,
176    /// Socket address this node binds for inbound distribution links from peers.
177    ///
178    /// This is distinct from [`ServerConfig::listen_address`] (the client wire
179    /// port): a clustered node listens on two ports — one for clients, one for
180    /// peer distribution traffic.
181    pub listen_address: SocketAddr,
182    /// Seed node socket addresses used to join an existing cluster.
183    pub seed_nodes: Vec<SocketAddr>,
184    /// Required secret distribution handshake cookie. Every node in a cluster
185    /// must explicitly set the same cookie or the OTP handshake is rejected.
186    /// An omitted cookie fails deserialization; an empty cookie or the public
187    /// [`DEFAULT_COOKIE`] fails configuration validation.
188    pub cookie: String,
189}
190
191/// Connection authentication configuration.
192///
193/// A single shared bearer token compared (constant-time) against the `auth_token`
194/// carried on every client `Connect` handshake. This is the table-stakes access
195/// gate, not an ACL system: one token grants full access. Its absence (no `[auth]`
196/// section) is open mode (ACCESS-010): the exchange listens on loopback only,
197/// admits every connection whatever credential it presents, and asks Lys
198/// nothing; `[auth]` makes it gated, and a gated exchange never falls back to
199/// open.
200#[derive(Clone, serde::Deserialize)]
201#[serde(deny_unknown_fields)]
202pub struct AuthConfig {
203    /// Shared secret token a client must present in its `Connect` handshake. Must
204    /// be non-empty when the `[auth]` section is present (an empty token is a
205    /// config validation error, since it would gate nothing).
206    pub token: String,
207    /// Optional registry-minted pass verifier, additive beside the bearer.
208    #[serde(default)]
209    pub pass: Option<PassConfig>,
210    /// The Lys pass as a second credential beside the wire pass (ACCESS-001
211    /// R2): when set, a `Connect` carrying a Lys pass record is verified
212    /// offline against the issuer's published keys and decided per message.
213    #[serde(default)]
214    pub lys: Option<LysConfig>,
215    /// Refuse every worker registration from a connection that proved no
216    /// holder (ACCESS-004 R3): a bearer connection, or one before any pass.
217    /// Off by default, so a worker that dials with the bearer, as aion's does,
218    /// keeps registering; turning it on is the operator's act, and it needs
219    /// `[auth.pass]`, without which no connection could prove a holder.
220    #[serde(default)]
221    pub require_verified_worker: bool,
222}
223
224/// The token is a credential: its `Debug` names its length only
225/// (ACCESS-004 R5).
226impl std::fmt::Debug for AuthConfig {
227    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        formatter
229            .debug_struct("AuthConfig")
230            .field("token", &crate::auth_pass::ByteLength(self.token.len()))
231            .field("pass", &self.pass)
232            .field("lys", &self.lys)
233            .field("require_verified_worker", &self.require_verified_worker)
234            .finish()
235    }
236}
237
238/// Which of the two access modes a configuration names (ACCESS-010 R1).
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub enum AccessMode {
241    /// No `[auth]`: loopback only, every connection admitted, nothing asked of Lys.
242    Open,
243    /// `[auth]` present: a bearer, a pass verifier or a Lys admitter decides.
244    Gated,
245}
246
247impl std::fmt::Display for AccessMode {
248    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249        formatter.write_str(match self {
250            Self::Open => "open",
251            Self::Gated => "gated",
252        })
253    }
254}
255
256impl ServerConfig {
257    /// The access mode: open with no `[auth]`, gated with one.
258    #[must_use]
259    pub const fn access_mode(&self) -> AccessMode {
260        if self.auth.is_some() {
261            AccessMode::Gated
262        } else {
263            AccessMode::Open
264        }
265    }
266}
267
268/// Registry pass verification configuration. Every field is required when present.
269#[derive(Debug, Clone, serde::Deserialize)]
270#[serde(deny_unknown_fields)]
271pub struct PassConfig {
272    /// Registry Ed25519 verifying key as exactly 64 hexadecimal characters.
273    pub registry_verifying_key: String,
274    /// Maximum admitted server-clock skew in seconds.
275    pub maximum_clock_skew_seconds: u64,
276}
277
278/// WebSocket transport acceptor configuration (`[websocket]`, LP-WS-TRANSPORT R1).
279///
280/// The sibling WebSocket route is an explicit opt-in: the section itself must be
281/// present for any HTTP/WebSocket listener to start, and inside it the listen
282/// address and the single exact upgrade path are required with no defaults.
283///
284/// The deployment TLS contract (tear ruling Q1) is raw `ws://` behind a named
285/// TLS-terminating proxy that owns public `wss://` and certificates; liminal
286/// grows no TLS stack. Origin validation nonetheless belongs to this acceptor:
287/// [`Self::allowed_origins`] is the explicit allow-list checked on every
288/// Origin-bearing upgrade, and there is NO default list — absent or empty
289/// configuration fails closed for browser-origin upgrades while a native client
290/// that sends no `Origin` header may still upgrade (F6).
291///
292/// OPERATOR NOTE — the same deployment contract covers the pre-upgrade window
293/// (domain-owner ruling, 2026-07-18): the fronting proxy must ALSO enforce
294/// pre-upgrade read timeouts, handshake concurrency limits, and connection
295/// rate limits. Between TCP accept and a completed WebSocket upgrade this
296/// listener does not count the socket against `[limits] max_connections` and
297/// applies no read deadline of its own (only the fixed request-head size
298/// bound), so a deployment that exposes this port without the named proxy is
299/// out of contract on untrusted networks. A named handshake read-deadline
300/// config plus an in-flight handshake cap derived from the configured
301/// `max_connections` value is the ledgered post-demo hardening.
302#[derive(Debug, Clone, serde::Deserialize)]
303#[serde(deny_unknown_fields)]
304pub struct WebSocketConfig {
305    /// Socket address the WebSocket acceptor binds. Required; distinct from the
306    /// main wire listener, the health listener, and any cluster listener.
307    pub listen_address: SocketAddr,
308    /// The single exact HTTP request path that accepts WebSocket upgrades.
309    /// Required; must start with `/`. Every other path — and every ordinary
310    /// HTTP request — receives a small fixed non-success response and closes.
311    pub path: String,
312    /// Explicit browser-origin allow-list checked on every Origin-bearing
313    /// upgrade (F6). Entries are compared byte-exact against the request's
314    /// serialized `Origin` header value (RFC 6454 ASCII serialization, e.g.
315    /// `https://app.example.com`). Absent or empty means NO browser origin is
316    /// accepted (fail closed); native clients sending no `Origin` header are
317    /// unaffected.
318    #[serde(default)]
319    pub allowed_origins: Vec<String>,
320    /// CON-014 R2: the console served beside this exchange, admitted at every
321    /// address the machine is reached by. An Origin-bearing upgrade is also
322    /// admitted when the Origin is `http://host[:port]` or `https://host[:port]`,
323    /// its port (the explicit one, else the scheme's own) is listed here, and
324    /// its host is the host of the request's own `Host` header. A site at
325    /// another host on the same port is refused as today. Absent or empty adds
326    /// nothing.
327    #[serde(default)]
328    pub allowed_origin_ports: Vec<u16>,
329    /// Q-A transport-liveness keepalive: the server-side WebSocket Ping
330    /// interval in milliseconds. This is a precise LAW-1 carve-out — liveness
331    /// pings never mint application events, never re-arm application state, and
332    /// never serve as a source of truth; failure detection remains the socket's
333    /// typed terminal events. The bound is one ping per interval per
334    /// connection, so the idle cost is `interval x connection-count`. Absent
335    /// means pings are DISABLED, accepting proxy-idle-disconnect churn as the
336    /// documented consequence. A configured zero is a validation error.
337    #[serde(default)]
338    pub ping_interval_ms: Option<u64>,
339}
340
341/// Service construction profile selection (D2).
342///
343/// The `profile` value is carried as a raw string here rather than a typed enum so
344/// an unrecognised value is a config *validation* error with a helpful message
345/// (via [`Self::profile`]) rather than an opaque deserialization failure — matching
346/// how every other semantic config check surfaces. Absent `profile` defaults to
347/// `"full"`.
348#[derive(Debug, Clone, serde::Deserialize)]
349#[serde(deny_unknown_fields)]
350pub struct ServicesConfig {
351    /// Construction profile: `"full"` (the default, unchanged behaviour) or
352    /// `"worker-front-door"` (capability-scoped worker deployments).
353    #[serde(default = "default_service_profile")]
354    pub profile: String,
355    /// Row bounds for the server-owned durable streams.
356    #[serde(default)]
357    pub self_streams: SelfStreamsConfig,
358}
359
360/// Retained row bounds for each server-owned durable stream.
361#[derive(Debug, Clone, Copy, serde::Deserialize)]
362#[serde(deny_unknown_fields)]
363pub struct SelfStreamsConfig {
364    /// Maximum retained cost records.
365    #[serde(default = "default_cost_rows")]
366    pub cost_rows: u64,
367    /// Maximum retained lifecycle and connection events.
368    #[serde(default = "default_events_rows")]
369    pub events_rows: u64,
370}
371
372impl Default for SelfStreamsConfig {
373    fn default() -> Self {
374        Self {
375            cost_rows: default_cost_rows(),
376            events_rows: default_events_rows(),
377        }
378    }
379}
380
381const fn default_cost_rows() -> u64 {
382    10_000
383}
384
385const fn default_events_rows() -> u64 {
386    100_000
387}
388
389impl Default for ServicesConfig {
390    fn default() -> Self {
391        Self {
392            profile: default_service_profile(),
393            self_streams: SelfStreamsConfig::default(),
394        }
395    }
396}
397
398impl ServicesConfig {
399    /// Resolves the raw `profile` string into a typed [`ServiceProfile`].
400    ///
401    /// # Errors
402    /// Returns [`ServerError::ConfigValidation`] when the value is not a recognised
403    /// profile.
404    pub fn profile(&self) -> Result<ServiceProfile, ServerError> {
405        ServiceProfile::parse(&self.profile)
406    }
407}
408
409fn default_service_profile() -> String {
410    ServiceProfile::FULL.to_owned()
411}
412
413/// Which connection-services adapter the server constructs (D2).
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415pub enum ServiceProfile {
416    /// Full channel/conversation/durability services — the default. Constructs the
417    /// haematite store, channel supervisor, conversation supervisor, and dedup
418    /// cache exactly as before.
419    Full,
420    /// Capability-scoped worker front door: the connection supervisor only, with no
421    /// channel/conversation/haematite machinery. Backs worker registration,
422    /// correlated push/reply, and notifier-consumed reserved publishes; ordinary
423    /// channel and conversation frames are rejected with a typed error frame.
424    WorkerFrontDoor,
425}
426
427impl ServiceProfile {
428    /// Config value selecting the full-service profile.
429    pub const FULL: &'static str = "full";
430    /// Config value selecting the worker-front-door profile.
431    pub const WORKER_FRONT_DOOR: &'static str = "worker-front-door";
432
433    /// Parses a `[services] profile` value into a typed profile.
434    ///
435    /// # Errors
436    /// Returns [`ServerError::ConfigValidation`] for any value other than
437    /// [`Self::FULL`] or [`Self::WORKER_FRONT_DOOR`].
438    pub fn parse(value: &str) -> Result<Self, ServerError> {
439        match value {
440            Self::FULL => Ok(Self::Full),
441            Self::WORKER_FRONT_DOOR => Ok(Self::WorkerFrontDoor),
442            other => Err(ServerError::ConfigValidation {
443                message: format!(
444                    "services.profile: unknown profile '{other}'; expected \"{}\" or \"{}\"",
445                    Self::FULL,
446                    Self::WORKER_FRONT_DOOR
447                ),
448            }),
449        }
450    }
451}
452
453mod limits;
454mod lys;
455mod participant;
456pub use crate::auth_membership::grant_stream::GrantStreamConfig;
457pub use limits::LimitsConfig;
458pub use lys::*;
459pub use participant::{ParticipantConfig, PruningConfig};