liminal-server 0.25.4

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
//! The link route on one connection (ACCESS-002 R1).
//!
//! A machine admitted on a Lys pass offers to open one end of a link on an
//! application stream (`LinkOpen`). The server proves the offered machine
//! key is the one Lys recorded for the connection's verified holder, asks
//! Lys live for the offered end's grant on the link (never the pass alone),
//! and answers the Noise `KK` handshake keyed from the two machines' Lys
//! identities; the stream is then a keyed link. A message crossing it
//! (`LinkMessage`) is opened by the link's transport and decided from both
//! machines' passes, `link_export` on the exporting machine's and
//! `link_import` on this machine's, before it is published here; a refusal
//! names its end on the link's stream.

use liminal::protocol::{
    Frame, LinkOffer, LinkOpenOutcome, MessageEnvelope, PUBLISH_ACK_POSITION_VERSION,
};
use liminal_protocol::reason_code::PUBLISH_UNRESOLVED_CODE;

use super::apply::unix_seconds_now;
use super::services::{
    ChannelOperation, Reach, access_to_server_error, reserved_namespace_refusal,
};
use super::state::{ConnectionProcessState, FrameAction};
use super::supervisor::runtime::ConnectionRuntime;
use crate::auth_lys::session::LysSession;
use crate::auth_lys::{
    AccessDecisionError, DeliberateDecision, GrantReceipt, RefusalCause, SubjectBinding,
};
use crate::link::{Link, LinkAction, LinkLife, LinkRefusal, LinkRights};
use crate::link_handshake::{LinkHandshake, LinkTransport, NOISE_OVERHEAD};

/// The reason code a refused crossing answers with, on the link's stream.
pub(super) const LINK_CROSSING_REFUSED_CODE: u16 = 0x0203;

#[cfg(test)]
mod open_tests;
#[cfg(test)]
mod refusal_tests;

#[cfg(feature = "test-support")]
impl crate::server::ConnectionSupervisor {
    /// Installs the service adapter's production observations in link wire fixtures.
    ///
    /// # Errors
    /// Returns an error when this supervisor already has an observation owner.
    pub fn install_link_observations_for_tests(
        &self,
        services: &super::services::LiminalConnectionServices,
    ) -> Result<(), crate::ServerError> {
        self.install_signals(services.signals().clone())
    }
}

/// A link open on this connection: its description, the end the remote
/// machine took, and the transport its handshake keyed.
#[derive(Debug)]
pub(super) struct OpenLink {
    link: Link,
    remote_end: LinkAction,
    transport: LinkTransport,
    life: LinkLife,
    calls: calls::IncomingCalls,
    certificate_until: Option<u64>,
}

mod life;
pub(super) use life::ConnectionLinks;

impl OpenLink {
    /// The end the remote machine took.
    pub(super) const fn remote_end(&self) -> LinkAction {
        self.remote_end
    }
}

/// The connection's admitted pass as the remote machine's link rights.
#[derive(Debug)]
struct SessionLinkRights<'a>(&'a dyn LysSession);

impl LinkRights for SessionLinkRights<'_> {
    fn holds(
        &self,
        action: LinkAction,
        subject: &SubjectBinding,
        now: u64,
    ) -> Result<GrantReceipt, AccessDecisionError> {
        self.0.decide_link(subject, action, now)
    }
}

/// Why an open did not key a link.
enum OpenRefusal {
    Held { grant: String, draft: String },
    Refused(String),
    Pass(AccessDecisionError),
}

/// The four-field refusal as the wire carries it, or the cause's words.
fn refusal_text(error: &AccessDecisionError) -> String {
    let envelope =
        serde_json::to_string(&error.refusal).unwrap_or_else(|_| error.cause.to_string());
    if error.cause == RefusalCause::RenewedWithoutGrant {
        format!("{}:{envelope}", error.cause)
    } else {
        envelope
    }
}

fn refused_open(
    state: &ConnectionProcessState,
    offer: &LinkOffer,
    action: &str,
    reason: String,
) -> LinkOpenOutcome {
    let peer = state.lys_session.as_ref().map_or_else(
        || format!("key:{}", blake3::hash(&offer.machine).to_hex()),
        |session| session.holder().to_owned(),
    );
    tracing::warn!(link = %offer.link_id, action, %peer, %reason, "inbound link open refused");
    LinkOpenOutcome::Refused { reason }
}

/// A `LinkOpen` frame: the ack carries the handshake answer, the draft Lys
/// holds the open under, or the refusal by name.
pub(super) fn link_open_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    stream_id: u32,
    offer: &LinkOffer,
) -> FrameAction {
    let opened = state
        .links
        .bind(pid, runtime, state.revocation.as_ref())
        .and_then(|()| open_link(runtime, state, stream_id, offer))
        .and_then(|(open, handshake)| {
            state
                .links
                .insert(runtime, stream_id, open)
                .map(|()| handshake)
        });
    let outcome = match opened {
        Ok(handshake) => LinkOpenOutcome::Opened { handshake },
        Err(OpenRefusal::Held { grant, draft }) => LinkOpenOutcome::Held { grant, draft },
        Err(OpenRefusal::Refused(reason)) => refused_open(
            state,
            offer,
            LinkAction::from(offer.end).other().access_action().name(),
            reason,
        ),
        Err(OpenRefusal::Pass(error)) => refused_open(
            state,
            offer,
            &error.refusal.refused.action,
            refusal_text(&error),
        ),
    };
    FrameAction::Respond(Frame::LinkOpenAck {
        flags: 0,
        stream_id,
        outcome,
    })
}

mod open;
use open::open_link;
mod admission;
pub(super) use admission::own_device_connect_refusal;

/// A `LinkMessage` frame: the crossing opened, decided on both ends and
/// published here, answered as a publish on the link's stream; or refused by
/// name under [`LINK_CROSSING_REFUSED_CODE`].
pub(super) fn link_message_frame_response(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    stream_id: u32,
    subject: &str,
    sealed: &[u8],
) -> FrameAction {
    match cross(runtime, state, stream_id, subject, sealed) {
        Ok(Crossed::Publication(crossing)) => {
            publish_crossing(pid, runtime, state, stream_id, subject, &crossing)
        }
        Ok(Crossed::Call(packet)) => {
            calls::dispatch(pid, runtime, state, stream_id, subject, packet)
        }
        Err(reason) => FrameAction::Respond(Frame::PublishError {
            flags: 0,
            stream_id,
            reason_code: LINK_CROSSING_REFUSED_CODE,
            message: Some(reason),
        }),
    }
}

enum Crossed {
    Publication(Crossing),
    Call(crate::link::calls::CallPacket),
}

struct Crossing {
    envelope: MessageEnvelope,
    position: u64,
    link_id: String,
    life: LinkLife,
}

fn publish_crossing(
    pid: u64,
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    stream_id: u32,
    subject: &str,
    crossing: &Crossing,
) -> FrameAction {
    let error_response = |reason_code, message: String| {
        FrameAction::Respond(Frame::PublishError {
            flags: 0,
            stream_id,
            reason_code,
            message: Some(message),
        })
    };
    let services = runtime.services();
    if let Some(error) = reserved_namespace_refusal(subject) {
        return error_response(LINK_CROSSING_REFUSED_CODE, error.to_string());
    }
    if let Err(refusal) = services.admit_channel(ChannelOperation::Publish, subject) {
        // A definite admission refusal settles this subject; a failed roster does not.
        let code = match &refusal {
            super::channel_registry::ChannelAccessError::RosterUnavailable { .. } => {
                refusal.reason_code()
            }
            super::channel_registry::ChannelAccessError::NotRegistered { .. }
            | super::channel_registry::ChannelAccessError::Quiesced { .. }
            | super::channel_registry::ChannelAccessError::ConsoleNamespace { .. }
            | super::channel_registry::ChannelAccessError::ConsoleTapTarget { .. }
            | super::channel_registry::ChannelAccessError::ConsoleTapLimit { .. } => {
                LINK_CROSSING_REFUSED_CODE
            }
        };
        return error_response(code, access_to_server_error(&refusal).to_string());
    }
    let key = format!("link/{}/{subject}/{}", crossing.link_id, crossing.position);
    let outcome = match services.publish(pid, subject, &crossing.envelope, Some(&key)) {
        Ok(outcome) => outcome,
        Err(error) => {
            let code = if matches!(error, crate::ServerError::PublishUnresolved { .. }) {
                PUBLISH_UNRESOLVED_CODE
            } else {
                0xFFFF
            };
            return error_response(code, error.to_string());
        }
    };
    if outcome.reach == Reach::Suppressed {
        if outcome.durable_position.is_none() {
            return error_response(
                PUBLISH_UNRESOLVED_CODE,
                "crossing receipt is still in flight".to_owned(),
            );
        }
        let observed = runtime
            .signals
            .get()
            .ok_or_else(|| "crossing signals are not installed".to_owned())
            .and_then(|signals| signals.already_crossed(&crossing.link_id, &crossing.life));
        if let Err(error) = observed {
            return error_response(0xFFFF, error);
        }
    }
    FrameAction::Respond(Frame::PublishAck {
        // The authenticated source position identifies the crossing even after a restart.
        flags: 0,
        stream_id,
        message_id: crossing.position,
        durable_position: outcome.durable_position.filter(|_| {
            state
                .negotiated_version
                .is_some_and(|version| version >= PUBLISH_ACK_POSITION_VERSION)
        }),
    })
}

fn cross(
    runtime: &ConnectionRuntime,
    state: &ConnectionProcessState,
    stream_id: u32,
    subject: &str,
    sealed: &[u8],
) -> Result<Crossed, String> {
    let ConnectionProcessState {
        lys_session, links, ..
    } = state;
    let Some(session) = lys_session.as_ref() else {
        return Err("a crossing is decided on a connection admitted on a Lys pass".to_owned());
    };
    let Some(host) = runtime.link_host() else {
        return Err("this liminal holds no machine identity".to_owned());
    };
    let mut contents = links.lock()?;
    let Some(open) = contents.links.get_mut(&stream_id) else {
        return Err(format!("no link is open on stream {stream_id}"));
    };
    if open
        .certificate_until
        .is_some_and(|until| unix_seconds_now() >= until)
    {
        return Err("certificate_pass_expired".into());
    }
    if open.remote_end() != LinkAction::Export {
        return Err(
            "messages cross from the exporting end; the remote machine imports on this link"
                .to_owned(),
        );
    }
    let mut plain = vec![0_u8; sealed.len()];
    let written = open
        .transport
        .open(sealed, &mut plain)
        .map_err(|error| format!("link frame refused: {error}"))?;
    plain.truncate(written);
    let remote = SessionLinkRights(session.as_ref());
    open.link
        .crossing(&remote, host.rights(), subject, unix_seconds_now())
        .map_err(|refusal| match &refusal {
            LinkRefusal::Export(error) => {
                format!("crossing refused at export: {}", refusal_text(error))
            }
            LinkRefusal::Import(error) => {
                format!("crossing refused at import: {}", refusal_text(error))
            }
            LinkRefusal::Binding(_) => refusal.to_string(),
        })?;
    if crate::link::calls::CallPacket::is_call(&plain) {
        let bound = host
            .peers()
            .ok_or("peer_calls_not_configured")?
            .max_call_bytes
            .get();
        return crate::link::calls::CallPacket::decode(&plain, bound)
            .map(Crossed::Call)
            .map_err(|error| error.to_string());
    }
    let header = plain
        .get(..8)
        .ok_or("crossed message has no position header")?;
    let position = u64::from_be_bytes(
        header
            .try_into()
            .map_err(|_| "crossed position is not eight bytes")?,
    );
    let link_id = open.link.resource().id;
    let life = open.life.clone();
    drop(contents);
    let envelope = MessageEnvelope::from_wire_bytes(&plain[8..])
        .map_err(|error| format!("the crossed message is not an envelope: {error}"))?;
    Ok(Crossed::Publication(Crossing {
        envelope,
        position,
        link_id,
        life,
    }))
}

mod calls;

pub(super) fn settled_calls(
    state: &ConnectionProcessState,
    runtime: &ConnectionRuntime,
) -> Result<Vec<Frame>, String> {
    let mut contents = state.links.lock()?;
    let Some(host) = runtime.link_host() else {
        return Ok(Vec::new());
    };
    let Some(peers) = host.peers() else {
        return Ok(Vec::new());
    };
    let mut frames = Vec::new();
    for (stream, open) in &mut contents.links {
        frames.extend(
            calls::settled(
                open,
                *stream,
                peers.max_call_bytes.get(),
                |open, subject| {
                    if open
                        .certificate_until
                        .is_some_and(|until| unix_seconds_now() >= until)
                    {
                        return Err(crate::link::calls::CallError::PeerGone);
                    }
                    let session = state
                        .lys_session
                        .as_deref()
                        .ok_or(crate::link::calls::CallError::Unavailable)?;
                    open.link
                        .crossing(
                            &SessionLinkRights(session),
                            host.rights(),
                            subject,
                            unix_seconds_now(),
                        )
                        .map(|_| ())
                        .map_err(|_| crate::link::calls::CallError::Unavailable)
                },
            )
            .map_err(|error| error.to_string())?,
        );
    }
    drop(contents);
    Ok(frames)
}