liminal-server 0.23.1

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
//! The agent's own pass, signed for the issuer's agent route at boot.
//!
//! Crossings read the verified rights offline. An open renews a due agent
//! pass and judges the renewed rights and lifetime on that same open.
use crate::ServerError;
use crate::auth_lys::lys_pass_adapter::{LysPassAdapter, MachineLinkRights};
use crate::auth_lys::session::{ConsumerAdmitter, LysAdmissionRefusal, LysAdmitter, LysSession};
use crate::auth_lys::{
    AccessAction, AccessDecisionError, AccessRefusal, AccessResource, DeliberateDecision,
    GrantReceipt, HotAction, LysPassConsumer, RefusalCause, SubjectBinding,
};
use crate::config::types::{LysConfig, MachineConfig};
use crate::link::{LinkAction, LinkHost, LinkRights};
use crate::link_handshake::{LocalMachine, MachineIdentity};
use lys_core::keys::Ed25519Identity;
use std::net::IpAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use zeroize::Zeroizing;
mod agent_dial;
mod cose;
pub(crate) mod debug;
mod holder;
use agent_dial::{Dial, Renewal};
pub(crate) use holder::MachinePass;

type GrantAnswer = Result<GrantReceipt, AccessDecisionError>;
type LinkAnswer = Result<DeliberateDecision, AccessDecisionError>;
static REFUSALS: AtomicU64 = AtomicU64::new(0);
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub(crate) struct PassRefusal(&'static str);
impl PassRefusal {
    pub(crate) fn source_absent(&self) -> bool {
        self.0 == "machine_pass_not_configured"
    }
}
fn named(name: &str) -> PassRefusal {
    // Only contract names enter logs and metric labels, never response words.
    const NAMES: &str = "agent_dial_refused agent_signature_refused HolderRetired ProviderUnavailable \
        ClientUnknown ScopeUnknown ScopeNotGranted PassRefused RequestMalformed signature_refused \
        wrong_audience wrong_issuer pass_expired pass_not_yet_valid unpublished_key \
        pass_encoding_refused contract_refused rights_outside_audience rights_truncated endpoint_refused";
    let name = match name {
        "AgentSignatureRefused" => "agent_signature_refused",
        "agent_pass_unproven" | "agent_not_holder" | "audience_not_approved" => {
            "agent_dial_refused"
        }
        "agent_retired" => "HolderRetired",
        "agent_pass_unavailable" => "ProviderUnavailable",
        name => name,
    };
    let known = NAMES.split_ascii_whitespace().find(|known| *known == name);
    PassRefusal(known.unwrap_or("machine_pass_refused"))
}
fn record_refusal(error: &PassRefusal, phase: &'static str) {
    let count = REFUSALS.fetch_add(1, Ordering::Relaxed) + 1;
    // Open refusals are named once by their connection or retry owner.
    if phase == "boot" {
        tracing::warn!(reason = error.0, phase, count, "machine pass refused");
    }
    if let Some(registry) = liminal::metrics::global_registry() {
        match registry
            .register_counter("liminal_machine_pass_refusals_total", [("reason", error.0)])
        {
            Ok(counter) => counter.increment(),
            Err(error) => {
                tracing::error!(%error, "machine pass refusal counter registration failed");
            }
        }
    }
}
fn identifier(value: &str) -> bool {
    !value.is_empty() && !value.chars().any(|c| c.is_whitespace() || c.is_control())
}
fn api_url(value: &str) -> Result<reqwest::Url, PassRefusal> {
    let mut url = reqwest::Url::parse(value).map_err(|_| PassRefusal("endpoint_refused"))?;
    let host = url.host_str().ok_or(PassRefusal("endpoint_refused"))?;
    let loopback = host == "localhost"
        || host
            .trim_matches(['[', ']'])
            .parse::<IpAddr>()
            .is_ok_and(|ip| ip.is_loopback());
    if !matches!(url.scheme(), "http" | "https")
        || !url.username().is_empty()
        || url.password().is_some()
        || url.query().is_some()
        || url.fragment().is_some()
        || (url.scheme() == "http" && !loopback)
    {
        return Err(PassRefusal("endpoint_refused"));
    }
    if !url.path().ends_with('/') {
        url.set_path(&format!("{}/", url.path()));
    }
    Ok(url)
}
/// Collects errors for the two mutually exclusive agent pass sources.
pub(crate) fn validate_configuration(lys: &LysConfig, errors: &mut Vec<String>) {
    let Some(machine) = &lys.machine else {
        return;
    };
    let file = !machine.pass_path.as_os_str().is_empty();
    let dial = !machine.agent_id.is_empty() || !machine.audience.is_empty();
    if file && dial {
        errors.push(
            "auth.lys.machine: pass_path and agent_id/audience are mutually exclusive".into(),
        );
    } else if !file && !dial {
        errors.push("auth.lys.machine: configure pass_path or agent_id and audience".into());
    }
    if dial {
        if !identifier(&machine.agent_id)
            || !machine
                .agent_id
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
        {
            errors.push("auth.lys.machine.agent_id: expected one nonempty route segment".into());
        }
        if !identifier(&machine.audience) {
            errors.push("auth.lys.machine.audience: expected a nonempty audience".into());
        }
        if lys
            .api_url
            .as_deref()
            .is_none_or(|url| api_url(url).is_err())
        {
            errors.push("auth.lys.api_url: agent_id requires HTTPS or loopback HTTP".into());
        }
    }
}

#[derive(Debug)]
struct Current {
    rights: MachineLinkRights,
    expiry: u64,
    renew_at: u64,
    renewed: bool,
}
struct Authority {
    current: Mutex<Current>,
    pass: MachinePass,
    dial: Option<Box<dyn Renewal>>,
    adapter: Arc<LysPassAdapter>,
}
fn verified(adapter: &LysPassAdapter, token: &[u8], now: u64) -> Result<Current, PassRefusal> {
    let observed = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|_| PassRefusal("machine_pass_clock_refused"))?
        .as_secs();
    let now = now.max(observed);
    let pass = adapter
        .verify_offline(token, crate::auth_lys::LIMINAL_PASS_AUDIENCE, now)
        .map_err(|error| named(error.name()))?;
    if pass.verified().claims().holder.kind != "agent" {
        return Err(PassRefusal("agent_holder_refused"));
    }
    let expiry = pass.verified().claims().exp;
    Ok(Current {
        rights: MachineLinkRights::new(adapter, pass),
        expiry,
        renew_at: renewal_at(expiry, now),
        renewed: false,
    })
}
impl Authority {
    fn refusal(
        &self,
        resource: &AccessResource,
        action: AccessAction,
        cause: RefusalCause,
    ) -> AccessDecisionError {
        AccessDecisionError {
            cause,
            refusal: AccessRefusal::new(resource.clone(), action, self.adapter.request_url()),
        }
    }
    fn open(
        &self,
        link: &AccessResource,
        end: LinkAction,
        now: u64,
    ) -> Result<(), AccessDecisionError> {
        let action = end.other();
        self.refresh_expired(now).map_err(|error| {
            let cause = if error.0 == "pass_expired" {
                RefusalCause::Expired
            } else {
                RefusalCause::DeliberateUnavailable
            };
            self.refusal(link, action.access_action(), cause)
        })?;
        let current = self.current.lock().map_err(|_| {
            self.refusal(
                link,
                action.access_action(),
                RefusalCause::DeliberateUnavailable,
            )
        })?;
        current
            .rights
            .holds_resource(action, link, now)
            .map(|_| ())
            .map_err(|mut error| {
                if current.renewed && error.cause == RefusalCause::MissingGrant {
                    error.cause = RefusalCause::RenewedWithoutGrant;
                }
                error
            })
    }
    fn refresh_expired(&self, now: u64) -> Result<(), PassRefusal> {
        let mut current = self
            .current
            .lock()
            .map_err(|_| PassRefusal("pass_holder_refused"))?;
        let expired = current.expiry <= now;
        if !expired && (self.dial.is_none() || current.renew_at > now) {
            return Ok(());
        }
        let dial = self.dial.as_ref().ok_or(PassRefusal("pass_expired"))?;
        // Serialize renewals so rights and the presented token change together.
        let (token, mut renewed) = dial.renew(&self.adapter, now).inspect_err(|error| {
            record_refusal(error, "link_open");
        })?;
        if renewed.expiry <= now {
            return Err(PassRefusal("pass_expired"));
        }
        let mut held = self
            .pass
            .0
            .lock()
            .map_err(|_| PassRefusal("pass_holder_refused"))?;
        renewed.renewed = true;
        held.token = token;
        *current = renewed;
        drop(held);
        drop(current);
        Ok(())
    }
}
#[derive(Debug)]
struct Rights(Arc<Authority>);
impl LinkRights for Rights {
    fn holds(&self, action: LinkAction, subject: &SubjectBinding, now: u64) -> GrantAnswer {
        let current = self.0.current.lock().map_err(|_| {
            self.0.refusal(
                subject.resource(),
                action.access_action(),
                RefusalCause::DeliberateUnavailable,
            )
        })?;
        current.rights.holds(action, subject, now)
    }
}
#[derive(Debug)]
struct Admitter {
    inner: Arc<dyn LysAdmitter>,
    authority: Arc<Authority>,
}
impl LysAdmitter for Admitter {
    fn admit(&self, pass: &[u8], now: u64) -> Result<Box<dyn LysSession>, LysAdmissionRefusal> {
        Ok(Box::new(Session {
            inner: self.inner.admit(pass, now)?,
            authority: Arc::clone(&self.authority),
        }))
    }
}
#[derive(Debug)]
struct Session {
    inner: Box<dyn LysSession>,
    authority: Arc<Authority>,
}
impl LysSession for Session {
    fn holder(&self) -> &str {
        self.inner.holder()
    }
    fn holder_kind(&self) -> Option<&str> {
        self.inner.holder_kind()
    }
    fn issued_at(&self) -> Option<u64> {
        self.inner.issued_at()
    }
    fn decide(&self, subject: &SubjectBinding, action: HotAction, now: u64) -> GrantAnswer {
        self.inner.decide(subject, action, now)
    }
    fn decide_link(&self, subject: &SubjectBinding, action: LinkAction, now: u64) -> GrantAnswer {
        self.inner.decide_link(subject, action, now)
    }
    fn open_link(&self, link: &AccessResource, end: LinkAction, now: u64) -> LinkAnswer {
        self.authority.open(link, end, now)?;
        self.inner.open_link(link, end, now)
    }
    fn decide_live(&self, target: &AccessResource, action: AccessAction, now: u64) -> LinkAnswer {
        self.inner.decide_live(target, action, now)
    }
}
pub(crate) struct PassInstall {
    pub host: Option<Arc<LinkHost>>,
    pub admitter: Arc<dyn LysAdmitter>,
}
/// Verifies the configured pass before creating any link host.
pub(crate) fn configured(
    lys: &LysConfig,
    adapter: Arc<LysPassAdapter>,
    handle: Option<tokio::runtime::Handle>,
    now: u64,
) -> Result<PassInstall, ServerError> {
    let mut install = PassInstall {
        host: None,
        admitter: Arc::new(ConsumerAdmitter::new(Arc::clone(&adapter))),
    };
    let Some(machine) = &lys.machine else {
        return Ok(install);
    };
    let mut errors = Vec::new();
    validate_configuration(lys, &mut errors);
    if !errors.is_empty() {
        return Err(ServerError::ConfigValidation {
            message: errors.join("; "),
        });
    }
    match build(lys, machine, adapter, handle, now) {
        Ok((host, authority)) => {
            install.host = Some(Arc::new(host));
            install.admitter = Arc::new(Admitter {
                inner: install.admitter,
                authority,
            });
        }
        Err(error) if !machine.agent_id.is_empty() => record_refusal(&error, "boot"),
        Err(error) => {
            return Err(ServerError::ConfigValidation {
                message: format!("auth.lys.machine: {error}"),
            });
        }
    }
    Ok(install)
}
fn hex_key(digits: &str) -> Result<Zeroizing<[u8; 32]>, PassRefusal> {
    let mut key = Zeroizing::new([0; 32]);
    hex::decode_to_slice(digits.trim(), &mut *key)
        .map_err(|_| PassRefusal("machine_key_refused"))?;
    Ok(key)
}
fn build(
    lys: &LysConfig,
    machine: &MachineConfig,
    adapter: Arc<LysPassAdapter>,
    handle: Option<tokio::runtime::Handle>,
    now: u64,
) -> Result<(LinkHost, Arc<Authority>), PassRefusal> {
    let digits = Zeroizing::new(
        std::fs::read_to_string(&machine.identity_path)
            .map_err(|_| PassRefusal("machine_identity_refused"))?,
    );
    let seed = hex_key(&digits)?;
    let local = LocalMachine::new(Ed25519Identity::from_seed(&seed));
    let dial = if machine.agent_id.is_empty() {
        None
    } else {
        Some(Dial::new(
            lys.api_url
                .as_deref()
                .ok_or(PassRefusal("endpoint_refused"))?,
            machine,
            Ed25519Identity::from_seed(&seed),
            handle.ok_or(PassRefusal("lys_ask_runtime_absent"))?,
        )?)
    };
    let (token, current) = if let Some(dial) = &dial {
        let issued = dial.ask()?;
        let current = dial.verified(&adapter, &issued, now)?;
        (issued.token, current)
    } else {
        let token = Zeroizing::new(
            std::fs::read_to_string(&machine.pass_path)
                .map_err(|_| PassRefusal("machine_pass_path_refused"))?,
        );
        let current = verified(&adapter, token.as_bytes(), now)?;
        (token, current)
    };
    let pass = MachinePass::hold(machine, Some(token))?;
    let authority = Arc::new(Authority {
        current: Mutex::new(current),
        pass,
        dial: dial.map(|dial| Box::new(dial) as Box<dyn Renewal>),
        adapter,
    });
    authority.pass.attach(&authority)?;
    let recorded = machine
        .machines
        .iter()
        .map(|(holder, key)| Ok((holder.clone(), MachineIdentity::new(*hex_key(key)?))))
        .collect::<Result<_, PassRefusal>>()?;
    Ok((
        LinkHost::new(local, Box::new(Rights(Arc::clone(&authority))), recorded),
        authority,
    ))
}

fn renewal_at(expiry: u64, now: u64) -> u64 {
    expiry.saturating_sub((expiry.saturating_sub(now) / 10).clamp(1, 30))
}

#[cfg(test)]
pub(crate) mod fixture;
#[cfg(test)]
mod open_tests;
#[cfg(test)]
mod renewal_tests {
    #[test]
    fn short_lived_agent_pass_renews_before_expiry() {
        for lifetime in [1, 2, 9, 10, 300, 3600] {
            let expiry = 100 + lifetime;
            let renewal = super::renewal_at(expiry, 100);
            assert!(renewal < expiry, "lifetime {lifetime} renews at expiry");
            assert!(renewal >= 100, "renewal precedes issuance");
        }
    }
}