liminal-server 0.25.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
//! The existing operator HTTP listener dispatches this exact route.
//!
//! Signed passes carry expanded actions, not relation names. The schema's
//! dedicated pull action must belong only to network administrator and operator;
//! an unrelated call/deploy grant cannot be mistaken for either relation.

use std::num::NonZeroUsize;
use std::sync::Arc;

use lys_pass::{Decision, Target};
use serde_json::{Value, json};

use crate::auth_lys::LysPassConsumer;
use crate::auth_lys::live::drafts::{
    AtomicDraftStore, DraftError, DraftExecutor, DraftLimits, PullReport, PullSignal,
    valid_metadata, validate_bounds,
};
use crate::auth_lys::lys_pass_adapter::LysPassAdapter;

/// One read-only administrative pull, after the person approves in Lys.
pub const PULL_PATH: &str = "/admin/drafts/pull";
/// A person's outright agent act, taken at once rather than held by draft.
pub const CREATE_PATH: &str = "/admin/agents/create";
/// This action is granted only by the network's administrator/operator relations.
pub const PULL_ACTION: &str = "pull_drafts";

/// Explicit HTTP input bounds, without a timer or an implicit default.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AdminLimits {
    /// Bounds one bearer before signature verification and allocation.
    pub credential_bytes: NonZeroUsize,
    /// Bounds the empty-object request body, refusing extra authority fields.
    pub body_bytes: NonZeroUsize,
}

/// Borrowed from the HTTP parser; diagnostics never include its bearer or body.
pub struct AdminRequest<'a> {
    /// The parsed request method.
    pub method: &'a str,
    /// The exact path, with no accepted query parameters.
    pub path: &'a str,
    /// The one Authorization header; the HTTP parser refuses duplicates.
    pub authorization: Option<&'a str>,
    /// Empty bytes or an empty JSON object.
    pub body: &'a [u8],
    /// The server's operation time, never a caller's body field.
    pub at_ms: u64,
}

/// A response containing counts or a stable refusal, never prepared bytes.
pub struct AdminResponse {
    /// HTTP status.
    pub status: u16,
    /// JSON response body.
    pub body: Value,
}

/// The route uses its server-configured network and borrowed machine connector.
pub struct AdminDrafts<S> {
    puller: DraftPuller<S>,
    adapter: Arc<LysPassAdapter>,
    network: String,
    limits: AdminLimits,
    ask: Option<String>,
}

impl<S: AtomicDraftStore> AdminDrafts<S> {
    pub(crate) async fn signal(
        &mut self,
        connector: &str,
        signal: PullSignal,
        at_ms: u64,
    ) -> Result<PullReport, DraftError> {
        self.puller.pull(connector, signal, at_ms).await
    }

    /// Uses the same pass verifier and exact network as the wire admission.
    ///
    /// # Errors
    /// The configured network is absent, controlled or oversized.
    pub fn new(
        puller: DraftPuller<S>,
        adapter: Arc<LysPassAdapter>,
        network: String,
        limits: AdminLimits,
    ) -> Result<Self, DraftError> {
        if network.is_empty()
            || network.chars().any(char::is_control)
            || network.len() > limits.credential_bytes.get()
        {
            return Err(DraftError::Bound);
        }
        Ok(Self {
            puller,
            adapter,
            network,
            limits,
            ask: None,
        })
    }

    /// Asks Lys at the configured API address (`api_url`) rather than the
    /// issuer origin a pass names, as every other Lys call this server makes.
    #[must_use]
    pub fn asking_at(mut self, api_url: Option<String>) -> Self {
        self.ask = api_url;
        self
    }

    /// Handles the route without accepting authority or credentials in JSON.
    /// A held right is refused; this read cannot create another approval draft.
    /// The person's pass authorizes the pull, while only the machine connector
    /// reaches the product draft endpoints.
    ///
    /// # Errors
    /// An admitted pull failed; the endpoint must return this named failure,
    /// never a success response or a timer-based retry.
    pub async fn handle(
        &mut self,
        request: AdminRequest<'_>,
        connector_pass: &str,
    ) -> Result<AdminResponse, DraftError> {
        if request.path != PULL_PATH {
            return Ok(refused(404, "draft_pull_route_unknown"));
        }
        if request.method != "POST" {
            return Ok(refused(405, "draft_pull_method_refused"));
        }
        if request.body.len() > self.limits.body_bytes.get() {
            return Ok(refused(413, "draft_pull_body_bound"));
        }
        if !request.body.is_empty() {
            let body: Value = match serde_json::from_slice(request.body) {
                Ok(body) => body,
                Err(_) => return Ok(refused(400, "draft_pull_body_invalid")),
            };
            if !body.as_object().is_some_and(serde_json::Map::is_empty) {
                return Ok(refused(400, "draft_pull_body_invalid"));
            }
        }
        let Some(pass) = request
            .authorization
            .and_then(|header| header.strip_prefix("Bearer "))
        else {
            return Ok(refused(401, "draft_pull_pass_missing"));
        };
        if pass.is_empty()
            || pass.len() > self.limits.credential_bytes.get()
            || pass.chars().any(char::is_whitespace)
            || pass.chars().any(char::is_control)
        {
            return Ok(refused(401, "draft_pull_pass_invalid"));
        }
        let now = request.at_ms / 1000;
        let Ok(verified) = self.adapter.verify_offline(pass.as_bytes(), "liminal", now) else {
            return Ok(refused(401, "draft_pull_pass_invalid"));
        };
        match verified
            .verified()
            .evaluate("liminal.network", &self.network, PULL_ACTION, now)
        {
            Ok(Decision::Allowed { .. }) => {}
            Ok(Decision::Held { .. } | Decision::Refused) => {
                return Ok(refused(403, "draft_pull_network_operator_required"));
            }
            Err(_) => return Ok(refused(401, "draft_pull_pass_invalid")),
        }
        // Check the current grant, so revocation cannot be bypassed by an
        // otherwise unexpired offline pass on the administration plane.
        let http = reqwest::Client::builder()
            .no_proxy()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|_| DraftError::Lys("transport_failed".to_owned()))?;
        let issuer = crate::auth_lys::live::lys_origin(
            self.ask.as_deref().unwrap_or_else(|| self.adapter.issuer()),
        )
        .map_err(|_| DraftError::Contract)?;
        let client = lys_pass::Client::new(http, issuer)
            .map_err(|error| DraftError::Lys(error.name().to_owned()))?;
        let target = Target::new("liminal.network", &self.network, PULL_ACTION)
            .map_err(|_| DraftError::Contract)?;
        let answer = client
            // Lys's live check takes the app's own credential (lys-app), never
            // the person's pass, whose holder is named as the subject instead.
            .check_batch(connector_pass, verified.holder(), &[target], None)
            .await
            .map_err(|error| DraftError::Lys(error.name().to_owned()))?;
        let Some(result) = answer.results.first() else {
            return Err(DraftError::Contract);
        };
        if answer.degraded.is_some() || result.degraded.is_some() {
            return Ok(refused(503, "draft_pull_permission_degraded"));
        }
        if !result.allowed || result.mode != Some(lys_pass::Mode::Outright) {
            if let Some(name) = &result.refusal {
                return Ok(AdminResponse {
                    status: 403,
                    body: json!({"refusal":name, "reason":result.reason}),
                });
            }
            return Ok(refused(403, "draft_pull_network_operator_required"));
        }
        let report = self
            .puller
            .pull(connector_pass, PullSignal::Console, request.at_ms)
            .await?;
        Ok(AdminResponse {
            status: 200,
            body: serde_json::to_value(report).map_err(|_| DraftError::Store)?,
        })
    }
}

#[path = "admin_outright.rs"]
mod outright;
pub use outright::OutrightAsk;

fn refused(status: u16, name: &str) -> AdminResponse {
    AdminResponse {
        status,
        body: json!({"refusal":name}),
    }
}

use lys_pass::drafts::{ApprovedDraft, Execution, Executor, execute_once};
use std::collections::BTreeSet;
/// One serialized owner. Borrow its machine credential for each told pull;
/// nothing here holds a person's session or starts work in the background.
pub struct DraftPuller<S> {
    client: lys_pass::Client,
    pub(crate) executor: DraftExecutor<S>,
    startup_seen: bool,
}

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

impl<S: AtomicDraftStore> DraftPuller<S> {
    /// Connects only to the configured issuer; redirects and environment
    /// proxies cannot route its machine credential elsewhere.
    ///
    /// # Errors
    /// The issuer or HTTP client could not be constructed.
    pub fn new(issuer: &str, store: S, limits: DraftLimits) -> Result<Self, DraftError> {
        let http = reqwest::Client::builder()
            .no_proxy()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|_| DraftError::Lys("transport_failed".to_owned()))?;
        let issuer = crate::auth_lys::live::lys_origin(issuer).map_err(|_| DraftError::Contract)?;
        let client = lys_pass::Client::new(http, issuer)
            .map_err(|error| DraftError::Lys(error.name().to_owned()))?;
        Ok(Self {
            client,
            executor: DraftExecutor {
                store,
                limits,
                at_ms: 0,
            },
            startup_seen: false,
        })
    }

    /// Pulls and closes approved drafts only on an explicit signal. An error
    /// ends the pull; a later caller may reuse the durable receipt. No automatic
    /// retry is scheduled. The target store revalidates stale prepared acts.
    ///
    /// # Errors
    /// Lys, immutable contract, configured bounds, target storage or delivery.
    pub async fn pull(
        &mut self,
        connector_pass: &str,
        signal: PullSignal,
        at_ms: u64,
    ) -> Result<PullReport, DraftError> {
        let limits = self.executor.limits;
        if !valid_metadata(connector_pass, limits.metadata_bytes) {
            return Err(DraftError::Bound);
        }
        if signal == PullSignal::Startup {
            if self.startup_seen {
                return Err(DraftError::StartupRepeated);
            }
            self.startup_seen = true;
        }
        self.executor.at_ms = at_ms;
        let mut report = PullReport::default();
        let mut after: Option<String> = None;
        let mut cursors = BTreeSet::new();
        let mut ids = BTreeSet::new();
        let pending = self
            .acknowledge_pending(connector_pass, &mut report, &mut ids)
            .await?;
        loop {
            if report.pages >= limits.pages.get() {
                return Err(DraftError::Bound);
            }
            let page = self
                .client
                .approved_drafts(connector_pass, crate::auth_lys::LYS_APP, after.as_deref())
                .await
                .map_err(|error| DraftError::Lys(error.name().to_owned()))?;
            report.pages += 1;
            let mut page_ids = BTreeSet::new();
            for draft in &page.drafts {
                validate_bounds(draft, limits)?;
                if !page_ids.insert(&draft.id) {
                    return Err(DraftError::IdRepeated);
                }
            }
            let additional = page
                .drafts
                .iter()
                .filter(|draft| !ids.contains(&draft.id))
                .count();
            if ids.len().saturating_add(additional) > limits.drafts.get() {
                return Err(DraftError::Bound);
            }
            if let Some(next) = &page.next {
                if !valid_metadata(next, limits.metadata_bytes) {
                    return Err(DraftError::Bound);
                }
                if !cursors.insert(next.clone()) {
                    return Err(DraftError::CursorRepeated);
                }
            }
            for draft in &page.drafts {
                if pending.contains(&draft.id) {
                    self.execution(draft)?;
                    continue;
                }
                if !ids.insert(draft.id.clone()) {
                    return Err(DraftError::IdRepeated);
                }
                let replay = self.executor.receipt(&draft.id)?.is_some();
                let receipt = self.execution(draft)?;
                self.executor.store.deliver_outcome(draft, &receipt)?;
                if replay {
                    report.replayed += 1;
                } else {
                    match &receipt {
                        Execution::Executed { .. } => report.executed += 1,
                        Execution::RefusedOnExecution { .. } => report.refused += 1,
                    }
                }
                if !self.executor.store.acknowledged(&draft.id)? {
                    self.client
                        .record_execution(connector_pass, draft, &receipt)
                        .await
                        .map_err(|error| DraftError::Acknowledgment {
                            draft: draft.id.clone(),
                            name: error.name().to_owned(),
                        })?;
                    self.executor.store.acknowledge(&draft.id, &receipt)?;
                    report.acknowledged += 1;
                }
            }
            match page.next {
                Some(next) => after = Some(next),
                None => return Ok(report),
            }
        }
    }
    fn execution(&mut self, draft: &ApprovedDraft) -> Result<Execution, DraftError> {
        execute_once(draft, &mut self.executor).map_err(|error| match error {
            lys_pass::drafts::ExecuteError::DigestMismatch => DraftError::ReceiptMismatch,
            lys_pass::drafts::ExecuteError::Product(error) => error,
            lys_pass::drafts::ExecuteError::Contract(_) => DraftError::Contract,
        })
    }

    async fn acknowledge_pending(
        &mut self,
        pass: &str,
        report: &mut PullReport,
        ids: &mut BTreeSet<String>,
    ) -> Result<BTreeSet<String>, DraftError> {
        let limits = self.executor.limits;
        loop {
            let pending = self.executor.store.pending_acknowledgments(limits.drafts)?;
            if pending.is_empty() {
                return Ok(ids.clone());
            }
            if ids.len().saturating_add(pending.len()) > limits.drafts.get() {
                return Err(DraftError::Bound);
            }
            for draft in pending {
                validate_bounds(&draft, limits)?;
                if !ids.insert(draft.id.clone()) {
                    return Err(DraftError::IdRepeated);
                }
                if self.executor.receipt(&draft.id)?.is_none() {
                    return Err(DraftError::ReceiptMismatch);
                }
                let receipt = self.execution(&draft)?;
                self.executor.store.deliver_outcome(&draft, &receipt)?;
                self.client
                    .record_execution(pass, &draft, &receipt)
                    .await
                    .map_err(|error| DraftError::Acknowledgment {
                        draft: draft.id.clone(),
                        name: error.name().to_owned(),
                    })?;
                self.executor.store.acknowledge(&draft.id, &receipt)?;
                report.replayed += 1;
                report.acknowledged += 1;
            }
        }
    }
}

#[cfg(test)]
#[path = "admin_drafts_fixture.rs"]
mod fixture;
#[cfg(test)]
pub(crate) use fixture::fixture_site_drafts;

#[cfg(test)]
#[path = "admin_drafts_tests.rs"]
pub(crate) mod tests;

#[cfg(test)]
mod signal_tests {
    use super::*;
    type TestResult = Result<(), Box<dyn std::error::Error>>;
    use crate::auth_lys::live::drafts::tests::{Issuer, TargetStore, limits};
    #[tokio::test]
    async fn startup_is_one_signal_and_unknown_stream_rows_do_not_pull() -> TestResult {
        let dir = tempfile::tempdir()?;
        let issuer = Issuer::new(vec![(
            200,
            serde_json::json!({"drafts":[],"next":null,"total":0}),
        )])?;
        let mut puller = DraftPuller::new(
            &issuer.api,
            TargetStore::new(dir.path().join("site.json")),
            limits()?,
        )?;
        assert_eq!(issuer.calls()?, 0);
        puller
            .pull("connector-fixture", PullSignal::Startup, 1)
            .await?;
        assert!(matches!(
            puller
                .pull("connector-fixture", PullSignal::Startup, 2)
                .await,
            Err(DraftError::StartupRepeated)
        ));
        assert_eq!(
            crate::auth_lys::live::drafts::stream_signal("placement"),
            None
        );
        assert_eq!(
            crate::auth_lys::live::drafts::stream_signal("new_unknown_kind"),
            None
        );
        assert_eq!(issuer.calls()?, 1);
        issuer.finish()
    }
}