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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Registry-minted connection passes.

use ed25519_dalek::{Signature, VerifyingKey};
use std::collections::BTreeSet;
use std::time::{SystemTime, UNIX_EPOCH};

use crate::ServerError;
use crate::config::PassConfig;

pub const PASS_VERSION_V1: u8 = 1;
const SIGNATURE_LEN: usize = 64;

/// Most conversations one pass may scope. A pass arrives inside a `Connect`
/// before admission, so its eight bytes per conversation must fit the
/// pre-admission bound; a larger declared count is refused before anything
/// is allocated for it.
///
/// The count check in [`WirePassV1::parse`] is reachable from the wire even
/// under the 64 KiB pre-admission cap: the count is a declared `u32`, so a
/// small `Connect` can claim any count without carrying the bytes for it.
/// The cap bounds the frame; this bound keeps the claim from sizing an
/// allocation, for the wire and for direct parse callers alike.
pub(crate) const MAX_PASS_CONVERSATIONS: usize =
    crate::server::connection::pre_admission::PRE_ADMISSION_FRAME_BOUND / 8;
const _: () = assert!(MAX_PASS_CONVERSATIONS == 8192);

#[derive(Clone, PartialEq, Eq)]
pub struct PassPrincipal {
    pub participant: Vec<u8>,
    pub public_key: [u8; 32],
    pub conversations: BTreeSet<u64>,
    pub live: String,
    pub may_enroll: bool,
}

#[derive(Clone, PartialEq, Eq)]
pub struct WirePassV1 {
    pub participant: Vec<u8>,
    pub public_key: [u8; 32],
    pub conversations: Vec<u64>,
    pub live: String,
    pub may_enroll: bool,
    pub issued_at: u64,
    pub expires_at: u64,
    pub signature: [u8; SIGNATURE_LEN],
}

/// A credential field in a `Debug`: its length, never its bytes
/// (ACCESS-004 R5, the CREDENTIAL-DEBUG rule).
pub(crate) struct ByteLength(pub(crate) usize);

impl std::fmt::Debug for ByteLength {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{} bytes", self.0)
    }
}

impl std::fmt::Debug for PassPrincipal {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PassPrincipal")
            .field("participant", &ByteLength(self.participant.len()))
            .field("public_key", &ByteLength(self.public_key.len()))
            .field("conversations", &self.conversations)
            .field("live", &ByteLength(self.live.len()))
            .field("may_enroll", &self.may_enroll)
            .finish()
    }
}

impl std::fmt::Debug for WirePassV1 {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WirePassV1")
            .field("participant", &ByteLength(self.participant.len()))
            .field("public_key", &ByteLength(self.public_key.len()))
            .field("conversations", &self.conversations)
            .field("live", &ByteLength(self.live.len()))
            .field("may_enroll", &self.may_enroll)
            .field("issued_at", &self.issued_at)
            .field("expires_at", &self.expires_at)
            .field("signature", &ByteLength(self.signature.len()))
            .finish()
    }
}

/// Who a connection is, as the one `Connect` verification proved it
/// (ACCESS-004 R1).
///
/// Two verifications make one, both in this module: [`PassVerifier::verify`],
/// from a pass whose registry signature and validity window it has checked,
/// and [`VerifiedHolder::from_lys_session`], from a Lys pass the installed
/// admitter verified offline at `Connect` (ACCESS-001, the second producer).
/// There is no other constructor, so no further credential scheme can
/// produce one by accident. A bearer `Connect` names no one and yields none.
///
/// No code outside this module can build one (ACCESS-004 R1):
///
/// ```compile_fail,E0451
/// let holder = liminal_server::auth_pass::VerifiedHolder {
///     participant: b"watcher".to_vec(),
///     live: "watcher.".to_owned(),
/// };
/// drop(holder);
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct VerifiedHolder {
    participant: Vec<u8>,
    live: String,
    source: HolderSource,
}

/// Which verification proved a holder, and so where its subject rights are
/// decided.
#[derive(Clone, Debug, PartialEq, Eq)]
enum HolderSource {
    /// A registry pass: rights are its live prefix.
    RegistryPass,
    /// A Lys pass: rights are decided per subject by the connection's Lys
    /// session; `kind` is the holder's directory kind as the signed pass
    /// states it (Person, Agent, `ServiceAccount`, Connector), `None` when
    /// the pass does not state one.
    Lys { kind: Option<String> },
}

impl VerifiedHolder {
    /// The holder a Lys pass proved, as the admitted session names it
    /// (ACCESS-004 R1's second producer, ACCESS-001). Called only from the
    /// `Connect` verification, with the session the admitter returned.
    pub(crate) fn from_lys_session(session: &dyn crate::auth_lys::session::LysSession) -> Self {
        Self {
            participant: session.holder().as_bytes().to_vec(),
            live: String::new(),
            source: HolderSource::Lys {
                kind: session.holder_kind().map(str::to_owned),
            },
        }
    }

    /// The holder's Lys directory kind, when a Lys pass proved it and stated
    /// one; `None` for a registry-pass holder.
    #[must_use]
    pub fn kind(&self) -> Option<&str> {
        match &self.source {
            HolderSource::RegistryPass => None,
            HolderSource::Lys { kind } => kind.as_deref(),
        }
    }

    /// Whether this holder's own grant covers `channel`. A registry pass
    /// grants its live prefix, and an empty prefix grants nothing. A Lys
    /// holder's rights are the Lys session's per-subject decision, which the
    /// connection makes before it asks this; the holder adds no second rule.
    #[must_use]
    pub fn allows_channel(&self, channel: &str) -> bool {
        match self.source {
            HolderSource::RegistryPass => {
                !self.live.is_empty() && channel.starts_with(self.live.as_str())
            }
            HolderSource::Lys { .. } => true,
        }
    }

    /// The holder's participant bytes, as the pass named them.
    #[must_use]
    pub fn participant(&self) -> &[u8] {
        &self.participant
    }

    /// The subject prefix the holder's pass grants.
    #[must_use]
    pub fn live(&self) -> &str {
        &self.live
    }

    /// Whether `identity` names this holder: its UTF-8 bytes equal the
    /// participant's exactly (ACCESS-004 R2).
    #[must_use]
    pub fn is_named(&self, identity: &str) -> bool {
        identity.as_bytes() == self.participant.as_slice()
    }
}

impl std::fmt::Debug for VerifiedHolder {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("VerifiedHolder")
            .field("participant", &ByteLength(self.participant.len()))
            .field("live", &ByteLength(self.live.len()))
            .field("source", &self.source)
            .finish()
    }
}

/// A pass [`PassVerifier::verify`] accepted: the principal it stamps and the
/// holder it proves.
pub(crate) struct VerifiedPass {
    pub(crate) principal: PassPrincipal,
    pub(crate) holder: VerifiedHolder,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PassCheckError {
    Malformed,
    /// The pass declared more conversations than a pre-admission `Connect`
    /// can carry, eight bytes each.
    ScopeTooLarge,
    Signature,
    Expired,
}
impl PassCheckError {
    #[must_use]
    pub const fn check_name(self) -> &'static str {
        match self {
            Self::Malformed => "malformed",
            Self::ScopeTooLarge => "scope_too_large",
            Self::Signature => "signature",
            Self::Expired => "expired",
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct PassVerifier {
    key: VerifyingKey,
    skew: u64,
    /// `auth.require_verified_worker` (ACCESS-004 R3), carried here because
    /// the flag needs a verifier: no holder can be proved without one.
    require_verified_worker: bool,
}
impl PassVerifier {
    /// The verifier `auth` configures, carrying its
    /// `require_verified_worker`; `None` when `auth` has no `[auth.pass]`.
    /// The one derivation for every constructor that reads `[auth]`.
    ///
    /// # Errors
    /// Returns [`ServerError::ConfigValidation`] for a malformed key.
    pub(crate) fn from_auth(auth: &crate::config::AuthConfig) -> Result<Option<Self>, ServerError> {
        auth.pass
            .as_ref()
            .map(|pass| {
                Self::from_config(pass).map(|verifier| Self {
                    require_verified_worker: auth.require_verified_worker,
                    ..verifier
                })
            })
            .transpose()
    }

    /// This verifier, refusing every worker registration from a connection
    /// that proved no holder.
    #[cfg(test)]
    pub(crate) const fn requiring_verified_worker(self) -> Self {
        Self {
            require_verified_worker: true,
            ..self
        }
    }

    /// Whether a worker registration from a connection that proved no holder
    /// is refused (ACCESS-004 R3).
    pub(crate) const fn requires_verified_worker(&self) -> bool {
        self.require_verified_worker
    }

    /// Builds a verifier from the required operator pass configuration.
    ///
    /// # Errors
    /// Returns [`ServerError::ConfigValidation`] when the configured key is not
    /// exactly one valid Ed25519 verifying key encoded as 64 hexadecimal digits.
    pub(crate) fn from_config(config: &PassConfig) -> Result<Self, ServerError> {
        let key = hex::decode(&config.registry_verifying_key).map_err(|error| {
            ServerError::ConfigValidation {
                message: format!(
                    "auth.pass.registry_verifying_key: expected 64 hexadecimal digits: {error}"
                ),
            }
        })?;
        Self::new(&key, config.maximum_clock_skew_seconds).map_err(|_| {
            ServerError::ConfigValidation {
                message: "auth.pass.registry_verifying_key: expected a valid 32-byte Ed25519 verifying key".to_owned(),
            }
        })
    }

    /// Builds a verifier from operator configuration.
    ///
    /// # Errors
    /// Returns [`PassCheckError::Malformed`] unless the key is exactly 32 bytes.
    pub(crate) fn new(key: &[u8], skew: u64) -> Result<Self, PassCheckError> {
        let key: [u8; 32] = key.try_into().map_err(|_| PassCheckError::Malformed)?;
        let key = VerifyingKey::from_bytes(&key).map_err(|_| PassCheckError::Malformed)?;
        Ok(Self {
            key,
            skew,
            require_verified_worker: false,
        })
    }

    /// Verifies `bytes` as a registry pass, and names its holder.
    ///
    /// # Errors
    /// Returns the precise malformed, signature, or expired check failure.
    pub(crate) fn verify(&self, bytes: &[u8]) -> Result<VerifiedPass, PassCheckError> {
        let principal = WirePassV1::verify(bytes, &self.key, self.skew, SystemTime::now())?;
        let holder = VerifiedHolder {
            participant: principal.participant.clone(),
            live: principal.live.clone(),
            source: HolderSource::RegistryPass,
        };
        Ok(VerifiedPass { principal, holder })
    }
}

impl WirePassV1 {
    /// Encodes all signed fields in fixed order using big-endian lengths and integers.
    ///
    /// # Errors
    /// Returns [`PassCheckError::Malformed`] for noncanonical scope or time ordering.
    pub fn canonical_unsigned_bytes(&self) -> Result<Vec<u8>, PassCheckError> {
        if self.issued_at > self.expires_at || self.conversations.windows(2).any(|p| p[0] >= p[1]) {
            return Err(PassCheckError::Malformed);
        }
        let mut out = vec![PASS_VERSION_V1];
        put_bytes(&mut out, &self.participant)?;
        out.extend_from_slice(&self.public_key);
        put_len(&mut out, self.conversations.len())?;
        for id in &self.conversations {
            out.extend_from_slice(&id.to_be_bytes());
        }
        put_bytes(&mut out, self.live.as_bytes())?;
        out.push(u8::from(self.may_enroll));
        out.extend_from_slice(&self.issued_at.to_be_bytes());
        out.extend_from_slice(&self.expires_at.to_be_bytes());
        Ok(out)
    }

    /// Encodes the complete pass including its signature.
    ///
    /// # Errors
    /// Returns [`PassCheckError::Malformed`] for noncanonical input.
    pub fn canonical_bytes(&self) -> Result<Vec<u8>, PassCheckError> {
        let mut out = self.canonical_unsigned_bytes()?;
        out.extend_from_slice(&self.signature);
        Ok(out)
    }

    /// Parses canonical version-1 bytes.
    ///
    /// # Errors
    /// Returns [`PassCheckError::Malformed`] for any format violation.
    pub fn parse(bytes: &[u8]) -> Result<Self, PassCheckError> {
        let unsigned_len = bytes
            .len()
            .checked_sub(SIGNATURE_LEN)
            .ok_or(PassCheckError::Malformed)?;
        let (unsigned, sig) = bytes.split_at(unsigned_len);
        let mut c = Cursor(unsigned);
        if c.u8()? != PASS_VERSION_V1 {
            return Err(PassCheckError::Malformed);
        }
        let participant = c.bytes()?.to_vec();
        let public_key = c.array()?;
        let count = c.len()?;
        // The count is the client's own claim, read before the signature is
        // checked: it is bounded before it sizes any allocation.
        if count > MAX_PASS_CONVERSATIONS {
            return Err(PassCheckError::ScopeTooLarge);
        }
        let mut conversations = Vec::with_capacity(count);
        for _ in 0..count {
            conversations.push(c.u64()?);
        }
        let live = std::str::from_utf8(c.bytes()?)
            .map_err(|_| PassCheckError::Malformed)?
            .to_owned();
        let may_enroll = match c.u8()? {
            0 => false,
            1 => true,
            _ => return Err(PassCheckError::Malformed),
        };
        let issued_at = c.u64()?;
        let expires_at = c.u64()?;
        if !c.0.is_empty()
            || issued_at > expires_at
            || conversations.windows(2).any(|p| p[0] >= p[1])
        {
            return Err(PassCheckError::Malformed);
        }
        Ok(Self {
            participant,
            public_key,
            conversations,
            live,
            may_enroll,
            issued_at,
            expires_at,
            signature: sig.try_into().map_err(|_| PassCheckError::Malformed)?,
        })
    }

    /// Verifies strict Ed25519 signature and the skew-bounded validity window.
    ///
    /// # Errors
    /// Returns the precise malformed, signature, or expired check failure.
    pub fn verify(
        bytes: &[u8],
        key: &VerifyingKey,
        skew: u64,
        now: SystemTime,
    ) -> Result<PassPrincipal, PassCheckError> {
        let pass = Self::parse(bytes)?;
        key.verify_strict(
            &pass.canonical_unsigned_bytes()?,
            &Signature::from_bytes(&pass.signature),
        )
        .map_err(|_| PassCheckError::Signature)?;
        let now = now
            .duration_since(UNIX_EPOCH)
            .map_err(|_| PassCheckError::Expired)?
            .as_secs();
        if now < pass.issued_at.saturating_sub(skew) || now > pass.expires_at.saturating_add(skew) {
            return Err(PassCheckError::Expired);
        }
        Ok(PassPrincipal {
            participant: pass.participant,
            public_key: pass.public_key,
            conversations: pass.conversations.into_iter().collect(),
            live: pass.live,
            may_enroll: pass.may_enroll,
        })
    }
}

fn put_len(out: &mut Vec<u8>, len: usize) -> Result<(), PassCheckError> {
    out.extend_from_slice(
        &u32::try_from(len)
            .map_err(|_| PassCheckError::Malformed)?
            .to_be_bytes(),
    );
    Ok(())
}
fn put_bytes(out: &mut Vec<u8>, bytes: &[u8]) -> Result<(), PassCheckError> {
    put_len(out, bytes.len())?;
    out.extend_from_slice(bytes);
    Ok(())
}
struct Cursor<'a>(&'a [u8]);
impl<'a> Cursor<'a> {
    const fn take(&mut self, n: usize) -> Result<&'a [u8], PassCheckError> {
        if self.0.len() < n {
            return Err(PassCheckError::Malformed);
        }
        let (a, b) = self.0.split_at(n);
        self.0 = b;
        Ok(a)
    }
    fn u8(&mut self) -> Result<u8, PassCheckError> {
        Ok(self.take(1)?[0])
    }
    fn len(&mut self) -> Result<usize, PassCheckError> {
        let a: [u8; 4] = self
            .take(4)?
            .try_into()
            .map_err(|_| PassCheckError::Malformed)?;
        usize::try_from(u32::from_be_bytes(a)).map_err(|_| PassCheckError::Malformed)
    }
    fn u64(&mut self) -> Result<u64, PassCheckError> {
        Ok(u64::from_be_bytes(
            self.take(8)?
                .try_into()
                .map_err(|_| PassCheckError::Malformed)?,
        ))
    }
    fn bytes(&mut self) -> Result<&'a [u8], PassCheckError> {
        let n = self.len()?;
        self.take(n)
    }
    fn array<const N: usize>(&mut self) -> Result<[u8; N], PassCheckError> {
        self.take(N)?
            .try_into()
            .map_err(|_| PassCheckError::Malformed)
    }
}

#[cfg(test)]
mod debug_tests;

#[cfg(test)]
mod tests {
    use super::*;

    /// Unsigned-pass bytes up to and including a declared conversation count,
    /// with no conversations after it, then a zero signature.
    fn pass_declaring(count: u32) -> Vec<u8> {
        let mut bytes = vec![PASS_VERSION_V1];
        bytes.extend_from_slice(&0_u32.to_be_bytes());
        bytes.extend_from_slice(&[0_u8; 32]);
        bytes.extend_from_slice(&count.to_be_bytes());
        bytes.extend_from_slice(&[0_u8; SIGNATURE_LEN]);
        bytes
    }

    #[test]
    fn a_pass_declaring_u32_max_conversations_is_refused_by_name_before_allocation() {
        assert_eq!(
            WirePassV1::parse(&pass_declaring(u32::MAX)),
            Err(PassCheckError::ScopeTooLarge)
        );
        assert_eq!(
            PassCheckError::ScopeTooLarge.check_name(),
            "scope_too_large"
        );
    }

    #[test]
    fn a_pass_declaring_one_past_the_bound_is_refused_and_the_bound_itself_is_not()
    -> Result<(), Box<dyn std::error::Error>> {
        let at_bound = u32::try_from(MAX_PASS_CONVERSATIONS)?;
        assert_eq!(
            WirePassV1::parse(&pass_declaring(at_bound + 1)),
            Err(PassCheckError::ScopeTooLarge)
        );
        // At the bound the count is admitted; the missing conversations then
        // make the pass malformed.
        assert_eq!(
            WirePassV1::parse(&pass_declaring(at_bound)),
            Err(PassCheckError::Malformed)
        );
        Ok(())
    }

    #[test]
    fn shared_version_one_vector_is_byte_exact_and_verifies()
    -> Result<(), Box<dyn std::error::Error>> {
        let vector: serde_json::Value =
            serde_json::from_str(include_str!("../test-vectors/wire-pass-v1.json"))?;
        let unsigned = hex::decode(
            vector["unsigned_pass_hex"]
                .as_str()
                .ok_or("unsigned bytes")?,
        )?;
        let signature: [u8; 64] =
            hex::decode(vector["signature_hex"].as_str().ok_or("signature")?)?
                .try_into()
                .map_err(|_| "signature length")?;
        let bytes = hex::decode(vector["pass_hex"].as_str().ok_or("pass bytes")?)?;
        let registry_key: [u8; 32] = hex::decode(
            vector["registry_verifying_key_hex"]
                .as_str()
                .ok_or("verifying key")?,
        )?
        .try_into()
        .map_err(|_| "key length")?;
        let pass = WirePassV1::parse(&bytes).map_err(|error| format!("parse failed: {error:?}"))?;
        assert_eq!(
            pass.canonical_unsigned_bytes()
                .map_err(|error| format!("encode failed: {error:?}"))?,
            unsigned
        );
        assert_eq!(pass.signature, signature);
        let key = VerifyingKey::from_bytes(&registry_key)?;
        let principal = WirePassV1::verify(
            &bytes,
            &key,
            0,
            UNIX_EPOCH + std::time::Duration::from_secs(pass.issued_at),
        )
        .map_err(|error| format!("verify failed: {error:?}"))?;
        assert_eq!(principal.participant, b"participant-42");
        assert_eq!(
            principal.conversations.into_iter().collect::<Vec<_>>(),
            vec![7, 42, 9001]
        );
        assert_eq!(principal.live, "workspace/acme/");
        assert!(principal.may_enroll);
        Ok(())
    }
}