liminal-server 0.22.0

Standalone server for the liminal messaging bus
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! The production bindings of the service seams (ACCESS-003 R1), built once
//! from `[auth.lys.services]` and `[auth.lys.broker]`.
//!
//! - [`SeatStarter`](super::SeatStarter): [`LysSeatStarter`], a seat started
//!   by Lys's start-command route on the configured machine.
//! - [`KeySender`](super::KeySender): [`ChannelKeySender`], the keys
//!   published on `sessions.<id>.keys` through the server's own publish path.
//! - [`BudgetSource`](super::BudgetSource): [`LysBudgets`], budgets and stops
//!   read from Lys, carried whole.
//! - [`ServiceAction`](super::ServiceAction): [`PublishingActions`], alarms
//!   and launches published on their subjects, context readings reported to
//!   Lys through the [`ContextReporter`] the context watch shares.
//!
//! Every Lys request is made as this liminal, a machine Lys knows: the
//! bearer is the current machine pass held by the boot pass source,
//! verified offline at start exactly as any presented pass is. Without
//! `[auth.lys.machine]` the services cannot ask Lys as anyone, and start is
//! refused by that name, never served with a guessed identity.

use super::actions::PublishingActions;
use super::broker::{Broker, BrokerRefusal, ObservedEcho};
use super::budgets::LysBudgets;
use super::context_watch::ContextReporter;
use super::keys::{ChannelKeySender, ConnectionPublisher, ServicePublisher};
use super::lys_http::{HttpLys, LysAnswer, LysHttp};
use super::seats::LysSeatStarter;
use super::{
    BudgetPolicy, BudgetSource, KeySender, SeatStarter, ServiceAction, ServiceEffectError,
    ServiceKind, ServiceRequest, Services,
};
use crate::auth_lys::LysPassConsumer;
use crate::config::types::LysConfig;
use crate::server::connection::LiminalConnectionServices;
use std::sync::Arc;
mod debug;

/// Administrative effect seams and an optional address broker, bound once.
pub struct ServiceBindings {
    administrative: Option<AdministrativeBindings>,
    context: Arc<ContextReporter>,
    watch_context: bool,
    broker: Option<Broker>,
    echo: Option<ObservedEcho>,
    relay: Option<Arc<super::relay::Relay>>,
    relay_topology_local: Option<String>,
}

#[derive(Debug)]
struct AdministrativeBindings {
    seats: LysSeatStarter,
    keys: ChannelKeySender,
    budgets: LysBudgets,
    actions: PublishingActions,
}

impl std::fmt::Debug for ServiceBindings {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ServiceBindings")
            .field("administrative", &self.administrative)
            .field("watch_context", &self.watch_context)
            .field("broker", &self.broker)
            .field("echo", &self.echo)
            .field("relay", &self.relay)
            .finish_non_exhaustive()
    }
}

impl ServiceBindings {
    /// Binds every seam: Lys asked through `http` with `bearer` (this
    /// machine's own pass), seats started on `machine`, messages published
    /// through `publisher`.
    #[must_use]
    pub fn new(
        http: &Arc<dyn LysHttp>,
        bearer: &str,
        machine: String,
        publisher: &Arc<dyn ServicePublisher>,
    ) -> Self {
        let context = Arc::new(ContextReporter::new(Arc::clone(http), bearer.to_owned()));
        Self {
            administrative: Some(AdministrativeBindings {
                seats: LysSeatStarter::new(Arc::clone(http), bearer.to_owned(), machine),
                keys: ChannelKeySender::new(Arc::clone(publisher)),
                budgets: LysBudgets::new(Arc::clone(http), bearer.to_owned()),
                actions: PublishingActions::new(Arc::clone(publisher), Arc::clone(&context)),
            }),
            context,
            watch_context: false,
            broker: None,
            echo: None,
            relay: None,
            relay_topology_local: None,
        }
    }

    /// Whether the operator asked for the context watch to run.
    #[must_use]
    pub const fn watches_context(&self) -> bool {
        self.watch_context
    }

    /// The seams, lent for one [`serve`](super::serve).
    #[must_use]
    pub fn services(&self) -> Services<'_> {
        Services {
            seats: self,
            keys: self,
            budgets: self,
            actions: self,
        }
    }

    /// The reporter the context watch shares with the `context-watch` call.
    #[must_use]
    pub fn context_reporter(&self) -> Arc<ContextReporter> {
        Arc::clone(&self.context)
    }

    /// The configured address broker, independent of administrative services.
    #[must_use]
    pub const fn broker(&self) -> Option<&Broker> {
        self.broker.as_ref()
    }

    /// The configured blind relay, independent of administrative services.
    #[must_use]
    pub const fn relay(&self) -> Option<&Arc<super::relay::Relay>> {
        self.relay.as_ref()
    }

    /// The console's canonical local endpoint for relay observations.
    #[must_use]
    pub fn relay_topology_local(&self) -> Option<&str> {
        self.relay_topology_local.as_deref()
    }

    /// Serves a broker request on the connection's admitted session.
    ///
    /// # Errors
    /// The broker or admitted session is absent, or the broker refuses the call.
    pub fn serve_broker(
        &self,
        session: Option<&dyn crate::auth_lys::session::LysSession>,
        subject: &str,
        request: &ServiceRequest<'_>,
        now: u64,
    ) -> Result<serde_json::Value, BrokerRefusal> {
        let broker = self
            .broker
            .as_ref()
            .ok_or(BrokerRefusal::Named("broker_not_configured"))?;
        let session = session.ok_or(BrokerRefusal::Named("pass_not_admitted"))?;
        broker.serve(session, subject, request, now)
    }

    /// Builds configured services when the boot machine pass is present.
    /// `Ok(None)` when no services are selected or a dial pass was refused.
    /// Lys is asked on `handle`'s runtime; messages are published through
    /// `services` as `liminal.<host>`.
    ///
    /// # Errors
    /// `[auth.lys.machine]` is absent (the services would have no identity to
    /// ask Lys as), this machine's pass or the issuer's key set cannot be
    /// read or does not verify, or the issuer is not an HTTP origin.
    pub fn configure(
        lys: &LysConfig,
        services: Arc<LiminalConnectionServices>,
        handle: tokio::runtime::Handle,
        now: u64,
    ) -> Result<Option<Self>, ServiceEffectError> {
        if lys.services.is_none()
            && lys.broker.is_none()
            && !lys.relay.as_ref().is_some_and(|relay| relay.enabled)
        {
            return Ok(None);
        }
        let machine = lys
            .machine
            .as_ref()
            .ok_or_else(|| ServiceEffectError("auth.lys.machine is absent".into()))?;
        let pass = match crate::link_pass::MachinePass::configured(machine) {
            Ok(pass) => pass,
            Err(error) if !machine.agent_id.is_empty() && error.source_absent() => return Ok(None),
            Err(error) => return Err(ServiceEffectError(error.to_string())),
        };
        let bearer = machine_bearer(lys, now)?;
        let http: Arc<dyn LysHttp> = Arc::new(MachineHttp {
            http: HttpLys::new(lys.api_url.as_deref().unwrap_or(&lys.issuer), handle)?,
            pass,
        });
        let host = lys
            .services
            .as_ref()
            .map_or("broker", |section| section.host.as_str());
        let topology_local = services.console().device().to_owned();
        let publisher: Arc<dyn ServicePublisher> =
            Arc::new(ConnectionPublisher::new(services, host.to_owned()));
        let mut bindings = if let Some(section) = &lys.services {
            let mut bindings = Self::new(&http, &bearer, section.machine.clone(), &publisher);
            bindings.watch_context = section.context_watch;
            bindings
        } else {
            Self {
                administrative: None,
                context: Arc::new(ContextReporter::new(Arc::clone(&http), bearer)),
                watch_context: false,
                broker: None,
                echo: None,
                relay: None,
                relay_topology_local: None,
            }
        };
        if let Some(section) = &lys.broker {
            let machine = lys.machine.as_ref().ok_or_else(|| {
                ServiceEffectError("auth.lys.broker requires auth.lys.machine".to_owned())
            })?;
            let recorded = machine
                .machines
                .iter()
                .map(|(holder, key)| {
                    let mut bytes = [0; 32];
                    hex::decode_to_slice(key, &mut bytes).map_err(|_| {
                        ServiceEffectError(format!(
                            "auth.lys.machine.machines: invalid key for holder {holder}"
                        ))
                    })?;
                    let identity = crate::link_handshake::MachineIdentity::new(bytes);
                    identity.x25519_public().map_err(|error| {
                        ServiceEffectError(format!(
                            "auth.lys.machine.machines: holder {holder}: {error}"
                        ))
                    })?;
                    Ok((holder.clone(), identity))
                })
                .collect::<Result<_, ServiceEffectError>>()?;
            let broker = Broker::new(lys.network_id.clone(), recorded, publisher);
            bindings.echo = Some(
                ObservedEcho::bind(section.udp_listen, broker.counters()).map_err(|error| {
                    ServiceEffectError(format!("auth.lys.broker.udp_listen: {error}"))
                })?,
            );
            bindings.broker = Some(broker);
        }
        if lys.relay.as_ref().is_some_and(|relay| relay.enabled) {
            let machine = lys.machine.as_ref().ok_or_else(|| {
                ServiceEffectError("auth.lys.relay requires auth.lys.machine".to_owned())
            })?;
            let recorded = machine
                .machines
                .iter()
                .map(|(holder, key)| {
                    let mut bytes = [0; 32];
                    hex::decode_to_slice(key, &mut bytes).map_err(|_| {
                        ServiceEffectError(format!("invalid recorded machine for holder {holder}"))
                    })?;
                    let identity = crate::link_handshake::MachineIdentity::new(bytes);
                    identity
                        .x25519_public()
                        .map_err(|error| ServiceEffectError(error.to_string()))?;
                    Ok((holder.clone(), identity))
                })
                .collect::<Result<_, ServiceEffectError>>()?;
            bindings.relay = Some(super::relay::Relay::new(lys.network_id.clone(), recorded));
            bindings.relay_topology_local = Some(topology_local);
        }
        Ok(Some(bindings))
    }

    fn administrative(&self) -> Result<&AdministrativeBindings, ServiceEffectError> {
        self.administrative
            .as_ref()
            .ok_or_else(|| ServiceEffectError("auth.lys.services is not configured".to_owned()))
    }
}

impl SeatStarter for ServiceBindings {
    fn start(&self, seat: &str, operation: &str) -> Result<(), ServiceEffectError> {
        self.administrative()?.seats.start(seat, operation)
    }
}

impl KeySender for ServiceBindings {
    fn send(&self, session: &str, keys: &[u8], operation: &str) -> Result<(), ServiceEffectError> {
        self.administrative()?.keys.send(session, keys, operation)
    }
}

impl BudgetSource for ServiceBindings {
    fn read(&self, name: &str) -> Result<Option<BudgetPolicy>, ServiceEffectError> {
        self.administrative()?.budgets.read(name)
    }
}

impl ServiceAction for ServiceBindings {
    fn act(
        &self,
        service: ServiceKind,
        payload: &[u8],
        operation: &str,
    ) -> Result<(), ServiceEffectError> {
        self.administrative()?
            .actions
            .act(service, payload, operation)
    }
}

/// This machine's own Lys pass as the bearer the services ask Lys with.
///
/// It is verified offline for audience `liminal` at `now` against the
/// issuer's key set, so an expired or foreign pass refuses start by its
/// cause.
///
/// # Errors
/// No `[auth.lys.machine]`, or the pass or key set is unreadable or refused.
pub fn machine_bearer(lys: &LysConfig, now: u64) -> Result<String, ServiceEffectError> {
    let machine = lys.machine.as_ref().ok_or_else(|| {
        ServiceEffectError(
            "auth.lys.services or auth.lys.broker needs auth.lys.machine: services use this machine's pass"
                .to_owned(),
        )
    })?;
    let keys_json = std::fs::read_to_string(&lys.keys_path).map_err(|error| {
        ServiceEffectError(format!(
            "auth.lys.keys_path {}: {error}",
            lys.keys_path.display()
        ))
    })?;
    let adapter = crate::auth_lys::lys_pass_adapter::LysPassAdapter::from_keys_json(
        &keys_json,
        lys.issuer.clone(),
    )
    .map_err(|error| ServiceEffectError(format!("auth.lys key set refused: {error}")))?;
    let pass = crate::link_pass::MachinePass::configured(machine)
        .map_err(|error| ServiceEffectError(error.to_string()))?;
    let pass_bytes = pass
        .current()
        .map_err(|error| ServiceEffectError(error.to_string()))?;
    adapter
        .verify_offline(
            pass_bytes.as_bytes(),
            crate::auth_lys::LIMINAL_PASS_AUDIENCE,
            now,
        )
        .map_err(|error| ServiceEffectError(format!("auth.lys.machine pass refused: {error}")))?;
    Ok(pass_bytes.trim().to_owned())
}

// Keep the holder so renewal reaches services that are already bound.
struct MachineHttp {
    http: HttpLys,
    pass: crate::link_pass::MachinePass,
}
impl LysHttp for MachineHttp {
    fn get(&self, _: &str, path: &str) -> Result<LysAnswer, ServiceEffectError> {
        let token = self
            .pass
            .current()
            .map_err(|error| ServiceEffectError(error.to_string()))?;
        self.http.get(&token, path)
    }
    fn post(
        &self,
        _: &str,
        path: &str,
        body: &serde_json::Value,
    ) -> Result<LysAnswer, ServiceEffectError> {
        let token = self
            .pass
            .current()
            .map_err(|error| ServiceEffectError(error.to_string()))?;
        self.http.post(&token, path, body)
    }
}

#[cfg(test)]
mod tests {
    use super::ServiceBindings;
    use crate::config::types::LysConfig;
    use crate::server::connection::LiminalConnectionServices;
    use crate::services::ServiceRequest;
    use lys_core::keys::Ed25519Identity;
    use serde_json::json;
    use std::net::UdpSocket;
    use std::sync::Arc;
    use std::time::Duration;

    fn base64url(bytes: &[u8]) -> String {
        const ALPHABET: &[u8; 64] =
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
        let mut encoded = String::new();
        for chunk in bytes.chunks(3) {
            let first = chunk[0];
            encoded.push(char::from(ALPHABET[usize::from(first >> 2)]));
            let second = chunk.get(1).copied().unwrap_or(0);
            encoded.push(char::from(
                ALPHABET[usize::from((first & 3) << 4 | second >> 4)],
            ));
            if chunk.len() > 1 {
                let third = chunk.get(2).copied().unwrap_or(0);
                encoded.push(char::from(
                    ALPHABET[usize::from((second & 15) << 2 | third >> 6)],
                ));
                if chunk.len() > 2 {
                    encoded.push(char::from(ALPHABET[usize::from(third & 63)]));
                }
            }
        }
        encoded
    }

    fn machine_pass() -> Result<(String, String), serde_json::Error> {
        let issuer = Ed25519Identity::from_seed(&zeroize::Zeroizing::new([9; 32]));
        let keys = json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": "broker",
            "x": base64url(&issuer.public_key_bytes()), "alg": "EdDSA", "use": "sig"}]});
        let claims = json!({"iss": "https://issuer.example", "sub": "broker", "aud": "liminal",
            "iat": 0, "exp": 20, "rights": [],
            "holder": {"id": "broker", "kind": "machine", "responsible": "owner"}});
        let header = base64url(br#"{"alg":"EdDSA","typ":"JWT","kid":"broker"}"#);
        let signed = format!("{header}.{}", base64url(&serde_json::to_vec(&claims)?));
        let token = format!("{signed}.{}", base64url(&issuer.sign(signed.as_bytes())));
        Ok((keys.to_string(), token))
    }

    #[test]
    fn broker_only_configuration_binds_echo_and_refuses_unadmitted_calls()
    -> Result<(), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        let keys = root.path().join("issuer-keys.json");
        let pass = root.path().join("machine.pass");
        let (keys_json, token) = machine_pass()?;
        std::fs::write(&keys, keys_json)?;
        std::fs::write(&pass, token)?;
        let lys: LysConfig = toml::from_str(&format!(
            r#"
issuer = "https://issuer.example"
network_id = "network-a"
keys_path = "{}"
[broker]
udp_listen = "127.0.0.1:0"
[machine]
identity_path = "unused"
pass_path = "{}"
"#,
            keys.display(),
            pass.display()
        ))?;
        let runtime = tokio::runtime::Builder::new_current_thread().build()?;
        let services = Arc::new(LiminalConnectionServices::empty()?);
        let bindings = ServiceBindings::configure(&lys, services, runtime.handle().clone(), 10)?
            .ok_or("broker did not configure")?;
        assert!(bindings.broker().is_some());
        let refused = bindings
            .serve_broker(
                None,
                "net.broker.lookup",
                &ServiceRequest {
                    operation: "lookup",
                    payload: b"{}",
                },
                10,
            )
            .err()
            .ok_or("unadmitted call accepted")?;
        assert_eq!(refused.to_string(), "pass_not_admitted");
        let refused = bindings
            .services()
            .seats
            .start("unused", "operation")
            .err()
            .ok_or("unconfigured administrative service acted")?;
        assert!(
            refused
                .to_string()
                .contains("auth.lys.services is not configured")
        );
        let address = bindings.echo.as_ref().ok_or("echo missing")?.local_addr();
        let socket = UdpSocket::bind("127.0.0.1:0")?;
        socket.set_read_timeout(Some(Duration::from_secs(3)))?;
        socket.send_to(&[b"LMOB".as_slice(), &[3; 16]].concat(), address)?;
        let mut reply = [0; 64];
        let (length, _) = socket.recv_from(&mut reply)?;
        assert_eq!(length, 27);
        assert_eq!(&reply[..20], &[b"LMOA".as_slice(), &[3; 16]].concat());
        drop(bindings);
        let rebound = UdpSocket::bind(address)?;
        assert_eq!(rebound.local_addr()?, address);
        Ok(())
    }
}