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
//! Subject decisions delegated to the shared pass consumer.
//!
//! Product resource bindings come from admitted placements, never from splitting
//! subject spelling. The consumer owns verification and placement reach.

use serde::{Deserialize, Serialize};

pub mod live;
pub mod lys_pass_adapter;
pub mod prepared;
mod refusal;
pub mod root_presence;
pub mod root_presence_start;
pub mod routes;
pub use refusal::{AccessDecisionError, AccessRefusal, NeededGrant, RefusalCause, RequiredGrant};
pub mod session;

/// Audience used for offline admission.
pub const LIMINAL_PASS_AUDIENCE: &str = "liminal";

/// Permission classification fixed by the product schema.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionClass {
    /// Decided offline from the pass on each message.
    Hot,
    /// Requires the live authority and cannot use a hot fallback.
    Deliberate,
}

/// Actions shared by the subject, link and service consumers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccessAction {
    /// Publish a subject message.
    Publish,
    /// Subscribe to a subject.
    Subscribe,
    /// Call a subject service.
    Call,
    /// Serve a subject service.
    Serve,
    /// Export a machine-held link.
    LinkExport,
    /// Import a machine-held link.
    LinkImport,
    /// Deploy a service.
    DeployService,
    /// Administer a resource.
    Admin,
}

impl AccessAction {
    /// Returns the fixed decision class.
    #[must_use]
    pub const fn class(self) -> DecisionClass {
        match self {
            Self::Publish | Self::Subscribe | Self::Call | Self::Serve => DecisionClass::Hot,
            Self::LinkExport | Self::LinkImport | Self::DeployService | Self::Admin => {
                DecisionClass::Deliberate
            }
        }
    }
}

/// The only actions accepted by the per-message offline seam.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HotAction {
    /// Publish a message.
    Publish,
    /// Subscribe to a subject.
    Subscribe,
    /// Call a service.
    Call,
    /// Serve a service.
    Serve,
}

impl From<HotAction> for AccessAction {
    fn from(value: HotAction) -> Self {
        match value {
            HotAction::Publish => Self::Publish,
            HotAction::Subscribe => Self::Subscribe,
            HotAction::Call => Self::Call,
            HotAction::Serve => Self::Serve,
        }
    }
}

/// A deliberate action presented to the hot seam.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("action {0:?} requires a live Lys decision")]
pub struct DeliberateAction(pub AccessAction);

impl TryFrom<AccessAction> for HotAction {
    type Error = DeliberateAction;
    fn try_from(value: AccessAction) -> Result<Self, Self::Error> {
        match value {
            AccessAction::Publish => Ok(Self::Publish),
            AccessAction::Subscribe => Ok(Self::Subscribe),
            AccessAction::Call => Ok(Self::Call),
            AccessAction::Serve => Ok(Self::Serve),
            AccessAction::LinkExport
            | AccessAction::LinkImport
            | AccessAction::DeployService
            | AccessAction::Admin => Err(DeliberateAction(value)),
        }
    }
}

/// Resource kinds registered by the product schema.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceKind {
    /// A network containing placed subjects.
    Network,
    /// A subject placed beneath its admitted parent or network.
    Subject,
    /// A machine-held link placed under a network.
    Link,
    /// A service placed under a network.
    Service,
}

/// Exact authority resource, independent of the subject's display spelling.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccessResource {
    /// Registered product resource kind.
    pub kind: ResourceKind,
    /// Authority-issued resource identifier.
    pub id: String,
}

/// Explicit product mapping supplied from admitted resource placements.
///
/// This is a target mapping, not an authority token. Only the verified consumer
/// can decide that a pass reaches it.
#[derive(Debug, PartialEq, Eq)]
pub struct SubjectBinding {
    network_id: String,
    resource: AccessResource,
    subject: String,
}

/// An absent or pattern-based subject mapping.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("invalid placed subject binding: {0}")]
pub struct SubjectBindingError(pub &'static str);

impl SubjectBinding {
    /// Checks an explicitly supplied mapping without deriving its parents.
    ///
    /// # Errors
    /// Refuses missing identifiers, whitespace and subject patterns.
    pub fn new(
        network_id: String,
        resource_id: String,
        subject: String,
    ) -> Result<Self, SubjectBindingError> {
        for (name, value) in [
            ("network", &network_id),
            ("resource", &resource_id),
            ("subject", &subject),
        ] {
            if value.is_empty()
                || value.chars().any(char::is_whitespace)
                || value.chars().any(char::is_control)
            {
                return Err(SubjectBindingError(name));
            }
        }
        if subject.contains(['*', '>']) {
            return Err(SubjectBindingError("subject pattern"));
        }
        Ok(Self {
            network_id,
            resource: AccessResource {
                kind: ResourceKind::Subject,
                id: resource_id,
            },
            subject,
        })
    }

    /// Returns the admitted network identity.
    #[must_use]
    pub fn network_id(&self) -> &str {
        self.network_id.as_str()
    }

    /// Borrows the exact subject resource.
    #[must_use]
    pub const fn resource(&self) -> &AccessResource {
        &self.resource
    }

    /// Returns the product subject mapped to that resource.
    #[must_use]
    pub fn subject(&self) -> &str {
        self.subject.as_str()
    }
}

/// The Lys app liminal registers its schema as.
pub const LYS_APP: &str = "liminal";

impl ResourceKind {
    /// The kind as Lys qualifies it: `<app>.<kind>`.
    #[must_use]
    pub const fn qualified(self) -> &'static str {
        match self {
            Self::Network => "liminal.network",
            Self::Subject => "liminal.subject",
            Self::Link => "liminal.link",
            Self::Service => "liminal.service",
        }
    }
}

impl AccessAction {
    /// The action's name in the schema and on the wire.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Publish => "publish",
            Self::Subscribe => "subscribe",
            Self::Call => "call",
            Self::Serve => "serve",
            Self::LinkExport => "link_export",
            Self::LinkImport => "link_import",
            Self::DeployService => "deploy_service",
            Self::Admin => "admin",
        }
    }
}

/// Grant to receipt in the product's operation log.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GrantReceipt {
    /// Grant identity returned by the verified consumer.
    pub grant: String,
}

/// Shared-library integration seam, implemented by the pinned pass adapter.
///
/// Verification must authenticate signature, holder, audience and lifetime.
/// Hot decisions must recheck expiry on every invocation, evaluate only the
/// signed placement reach (including restricted children), require outright
/// mode, and return the actual granting identity. These methods perform no
/// network call. There is no product-side replacement rights evaluator.
pub trait LysPassConsumer {
    /// Opaque verified pass owned by the shared consumer.
    type Pass;
    /// Native verified holder representation owned by the shared consumer.
    type Holder: ?Sized;
    /// Original typed offline verification failure.
    type AdmissionError: std::error::Error;

    /// Verifies one credential offline for the required audience.
    ///
    /// # Errors
    /// Returns the consumer's original typed verification failure.
    fn verify_offline(
        &self,
        credential: &[u8],
        audience: &str,
        now: u64,
    ) -> Result<Self::Pass, Self::AdmissionError>;

    /// Borrows the holder proved by this same admitted credential.
    fn verified_holder<'p>(&self, pass: &'p Self::Pass) -> &'p Self::Holder;

    /// The directory kind of the holder this same credential proved
    /// (`person`, `agent`, ...), as the signed pass states it (ACCESS-006
    /// R1): an AI is asked about as its own agent identity, never as its
    /// responsible person. `None` when the consumer cannot name it, and a
    /// membership-protected channel then refuses by name.
    fn verified_holder_kind<'p>(&self, _pass: &'p Self::Pass) -> Option<&'p str> {
        None
    }

    /// When this same credential was issued, in Unix seconds, as the signed
    /// pass states it: a subject placed after it cannot be among its rights.
    /// `None` when the consumer cannot name it.
    fn verified_issued_at(&self, _pass: &Self::Pass) -> Option<u64> {
        None
    }

    /// Decides one exact subject/action from a current verified pass.
    ///
    /// # Errors
    /// Returns the common refusal with its exact typed cause.
    fn decide_hot(
        &self,
        pass: &Self::Pass,
        subject: &SubjectBinding,
        action: HotAction,
        now: u64,
    ) -> Result<GrantReceipt, AccessDecisionError>;

    /// Decides one link grant (`link_export` or `link_import`) on one exact
    /// bound subject from a current verified pass, offline (ACCESS-002 R1).
    ///
    /// # Errors
    /// Returns the common refusal with its exact typed cause.
    fn decide_link(
        &self,
        pass: &Self::Pass,
        subject: &SubjectBinding,
        action: crate::link::LinkAction,
        now: u64,
    ) -> Result<GrantReceipt, AccessDecisionError>;
}

/// A pass admitted only through the configured offline consumer.
pub struct AdmittedLysPass<P> {
    pass: P,
}

impl<P> std::fmt::Debug for AdmittedLysPass<P> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("AdmittedLysPass")
            .finish_non_exhaustive()
    }
}

/// Admits a second credential without changing the existing signed pass bytes.
///
/// # Errors
/// Preserves the shared consumer's typed verification failure.
pub fn admit_lys_pass<C: LysPassConsumer>(
    consumer: &C,
    credential: &[u8],
    now: u64,
) -> Result<AdmittedLysPass<C::Pass>, C::AdmissionError> {
    consumer
        .verify_offline(credential, LIMINAL_PASS_AUDIENCE, now)
        .map(|pass| AdmittedLysPass { pass })
}

/// Makes exactly one fresh offline decision for this message.
///
/// No admission-wide allow is cached. The adapter, rather than subject text,
/// selects the longest applicable placed ancestor and the actual granting right.
///
/// # Errors
/// Propagates the consumer's typed refusal unchanged.
pub fn decide_message<C: LysPassConsumer>(
    consumer: &C,
    pass: &AdmittedLysPass<C::Pass>,
    subject: &SubjectBinding,
    action: HotAction,
    now: u64,
) -> Result<GrantReceipt, AccessDecisionError> {
    consumer.decide_hot(&pass.pass, subject, action, now)
}

/// Grant mode selected by the authority, never a service-side default.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GrantMode {
    /// Execute under the returned grant.
    Outright,
    /// Hold for one approval.
    ByDraft,
    /// Hold for two distinct approvals.
    ByTwo,
}

/// A live decision; held acts have no permission to execute yet.
#[derive(Debug, PartialEq, Eq)]
pub enum DeliberateDecision {
    /// The live authority authorizes execution under this exact grant.
    Outright(GrantReceipt),
    /// The act is held as an authority-owned draft.
    ByDraft {
        /// Grant requiring approval.
        grant: String,
        /// Draft identity returned by the live authority.
        draft: String,
    },
    /// The act is held for two distinct approvals.
    ByTwo {
        /// Grant requiring two approvers.
        grant: String,
        /// Draft identity returned by the live authority.
        draft: String,
    },
}

/// Live-only decision seam shared with deliberately classified services.
///
/// The adapter authenticates the same admitted pass and the route's schema
/// classification. Unavailability must return `DeliberateUnavailable`, never a
/// cached allow or a hot decision.
pub trait LysDeliberateConsumer: LysPassConsumer {
    /// Holds an ACP permission using this admitted credential.
    ///
    /// # Errors
    /// Missing prepared support or an authenticated refusal.
    fn hold_permission(
        &self,
        _pass: &Self::Pass,
        _request: prepared::PermissionRequest<'_>,
    ) -> Result<serde_json::Value, lys_pass::Error> {
        Err(lys_pass::Error::CannotAsk(
            "prepared permission unavailable",
        ))
    }

    /// Holds exact construction words using the credential this consumer admitted.
    ///
    /// # Errors
    /// A consumer without prepared support refuses explicitly.
    fn hold_site(
        &self,
        _pass: &Self::Pass,
        _request: prepared::SiteRequest<'_>,
    ) -> Result<serde_json::Value, lys_pass::Error> {
        Err(lys_pass::Error::CannotAsk(
            "prepared construction unavailable",
        ))
    }

    /// Asks the live authority for this exact resource/action.
    ///
    /// # Errors
    /// Preserves the typed refusal, including authority unavailability.
    fn decide_live(
        &self,
        pass: &Self::Pass,
        resource: &AccessResource,
        action: AccessAction,
        now: u64,
    ) -> Result<DeliberateDecision, AccessDecisionError>;
}

/// Borrows the native holder established by this same offline verification.
#[must_use]
pub fn verified_lys_holder<'p, C: LysPassConsumer>(
    consumer: &C,
    pass: &'p AdmittedLysPass<C::Pass>,
) -> &'p C::Holder {
    consumer.verified_holder(&pass.pass)
}

/// Makes a live decision for a route explicitly classified deliberate.
///
/// The consumer must check that classification against the registered schema.
/// This function never attempts a hot fallback and never executes a held act.
///
/// # Errors
/// Propagates the live authority's typed refusal unchanged.
pub fn decide_deliberate<C: LysDeliberateConsumer>(
    consumer: &C,
    pass: &AdmittedLysPass<C::Pass>,
    resource: &AccessResource,
    action: AccessAction,
    now: u64,
) -> Result<DeliberateDecision, AccessDecisionError> {
    consumer.decide_live(&pass.pass, resource, action, now)
}

/// Read-only policy source; budget and stop policy remains authority-owned.
///
/// The concrete policy representation belongs to the shared authority adapter.
/// No local policy setter or budget decision is provided.
pub trait LysPolicySource {
    /// Native policy snapshot, without a product-side replacement shape.
    type Snapshot;
    /// Original typed policy read failure.
    type Error: std::error::Error;

    /// Reads policy for an exact authority resource.
    ///
    /// # Errors
    /// Preserves the authority's typed read or availability failure.
    fn read_policy(&self, resource: &AccessResource) -> Result<Self::Snapshot, Self::Error>;
}

#[path = "auth_lys/route_class.rs"]
mod route_class;

#[cfg(test)]
#[path = "auth_lys/root_presence_start_tests.rs"]
mod root_presence_start_tests;
#[cfg(test)]
#[path = "auth_lys/root_presence_tests.rs"]
mod root_presence_tests;
pub use route_class::AccessRouteClass;

pub use live::drafts;