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