liminal-server 0.8.2

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
//! Receipt/provenance production-path tests (gap-closure fix round).
//!
//! Each test drives the live dispatch seam with real wire frames over a real
//! on-disk store and pins the contract's bounded-provenance register rows:
//! independent enrollment/attach deadline pairs, the `result_generation`
//! carried by a deadline-provenance replay, the `Superseded` terminal reason
//! of a replaced receipt, and exact live-receipt replay with the invalidated
//! old secret (contract row 4). Deadline passage is real wall clock against
//! short configured TTLs — the production path reads its admitted clock, so
//! these tests wait out the signed windows rather than faking time.

use std::error::Error;
use std::thread::sleep;
use std::time::Duration;

use liminal_protocol::wire::{
    AttachAttemptToken, AttachBound, AttachSecret, ClientRequest, ConnectionIncarnation,
    CredentialAttachRequest, DetachAttemptToken, DetachRequest, EnrollmentRequest, EnrollmentToken,
    Generation, ReceiptExpired, ReceiptExpiryReason, ReceiptReplay, ServerValue,
    StaleOrUnknownReceipt,
};

use crate::config::types::ParticipantConfig;

use super::ProductionParticipantHandler;
use super::tests::{dispatch, open_disk_store_for_tests, test_participant_config};

/// Config whose receipt/provenance TTLs are short enough to wait out.
pub(super) const fn short_ttl_config(
    attach_receipt_ttl_ms: u64,
    receipt_provenance_ttl_ms: u64,
) -> ParticipantConfig {
    let mut config = test_participant_config();
    config.attach_receipt_ttl_ms = attach_receipt_ttl_ms;
    config.receipt_provenance_ttl_ms = receipt_provenance_ttl_ms;
    config
}

pub(super) fn enroll(
    handler: &ProductionParticipantHandler,
    incarnation: ConnectionIncarnation,
    conversation_id: u64,
    token: [u8; 16],
) -> Result<liminal_protocol::wire::EnrollBound, Box<dyn Error>> {
    let enrolled = dispatch(
        handler,
        incarnation,
        ClientRequest::Enrollment(EnrollmentRequest {
            conversation_id,
            enrollment_token: EnrollmentToken::new(token),
        }),
    )?;
    let ServerValue::EnrollBound(receipt) = enrolled else {
        return Err(format!("enrollment did not bind: {enrolled:?}").into());
    };
    Ok(receipt)
}

pub(super) fn detach(
    handler: &ProductionParticipantHandler,
    incarnation: ConnectionIncarnation,
    conversation_id: u64,
    participant_id: u64,
    generation: Generation,
    token: [u8; 16],
) -> Result<(), Box<dyn Error>> {
    let detached = dispatch(
        handler,
        incarnation,
        ClientRequest::Detach(DetachRequest {
            conversation_id,
            participant_id,
            capability_generation: generation,
            detach_attempt_token: DetachAttemptToken::new(token),
        }),
    )?;
    if !matches!(detached, ServerValue::DetachCommitted(_)) {
        return Err(format!("detach did not commit: {detached:?}").into());
    }
    Ok(())
}

pub(super) fn attach_request(
    conversation_id: u64,
    participant_id: u64,
    generation: Generation,
    secret: AttachSecret,
    token: [u8; 16],
) -> ClientRequest {
    ClientRequest::CredentialAttach(CredentialAttachRequest {
        conversation_id,
        participant_id,
        capability_generation: generation,
        attach_secret: secret,
        attach_attempt_token: AttachAttemptToken::new(token),
        accept_marker_delivery_seq: None,
    })
}

pub(super) fn attach(
    handler: &ProductionParticipantHandler,
    incarnation: ConnectionIncarnation,
    request: ClientRequest,
) -> Result<AttachBound, Box<dyn Error>> {
    let attached = dispatch(handler, incarnation, request)?;
    let ServerValue::AttachBound(receipt) = attached else {
        return Err(format!("attach did not bind: {attached:?}").into());
    };
    Ok(receipt)
}

pub(super) const GEN_ONE: Generation = Generation::ONE;

pub(super) fn generation(value: u64) -> Result<Generation, Box<dyn Error>> {
    Generation::new(value).ok_or_else(|| "zero generation in test fixture".into())
}

/// One enrolled participant whose enrollment fingerprint is RETAINED, because
/// possession of the secret that receipt minted has been proven.
pub(super) struct ProvenEnrollment {
    pub(super) participant_id: u64,
    /// Secret minted by the proving attach (generation 2).
    pub(super) attach_secret: AttachSecret,
}

/// Enrolls one participant and proves possession of the secret its enrollment
/// receipt minted — the event that makes that fingerprint occupy a stage-8
/// provenance slot.
///
/// Board #37: provenance is retained only for receipts whose delivery was
/// OBSERVED, and a committed credential attach IS the proof of delivery for
/// the receipt whose secret it presented (only a fresh attempt token verified
/// against `slot.attach_secret` reaches a commit). A bare `enroll` therefore
/// leaves NOTHING occupying the provenance scopes; every fixture that needs a
/// retained fingerprint has to earn one through this helper.
///
/// Leaves the participant bound at generation 2 holding exactly one retained
/// fingerprint (its enrollment's — the attach receipt just minted is itself
/// still unproven).
pub(super) fn enroll_proving_provenance(
    handler: &ProductionParticipantHandler,
    incarnation: ConnectionIncarnation,
    conversation_id: u64,
    tokens: [[u8; 16]; 3],
) -> Result<ProvenEnrollment, Box<dyn Error>> {
    let [enrollment_token, detach_token, attach_token] = tokens;
    let receipt = enroll(handler, incarnation, conversation_id, enrollment_token)?;
    let participant_id = receipt.participant_id();
    detach(
        handler,
        incarnation,
        conversation_id,
        participant_id,
        GEN_ONE,
        detach_token,
    )?;
    let bound = attach(
        handler,
        incarnation,
        attach_request(
            conversation_id,
            participant_id,
            GEN_ONE,
            receipt.attach_secret(),
            attach_token,
        ),
    )?;
    Ok(ProvenEnrollment {
        participant_id,
        attach_secret: bound.attach_secret(),
    })
}

/// A deadline-provenance replay of an attach token carries the RESULT
/// generation (presented + 1), not the presented one.
#[test]
fn attach_deadline_provenance_replay_carries_result_generation() -> Result<(), Box<dyn Error>> {
    let home = tempfile::tempdir()?;
    let data_dir = home.path().join("durability");
    let incarnation = ConnectionIncarnation::new(62, 1);
    let store = open_disk_store_for_tests(&data_dir)?;
    // Receipt dies after 300ms; provenance stays open long after.
    let handler = ProductionParticipantHandler::new(store, short_ttl_config(300, 600_000))?;
    let conversation_id = 602;

    let receipt = enroll(&handler, incarnation, conversation_id, [64; 16])?;
    let participant_id = receipt.participant_id();
    detach(
        &handler,
        incarnation,
        conversation_id,
        participant_id,
        GEN_ONE,
        [65; 16],
    )?;
    let attach_token = [66; 16];
    let request = attach_request(
        conversation_id,
        participant_id,
        GEN_ONE,
        receipt.attach_secret(),
        attach_token,
    );
    let attached = attach(&handler, incarnation, request.clone())?;
    assert_eq!(attached.capability_generation(), generation(2)?);
    // Wait out the receipt window, staying inside the provenance window.
    sleep(Duration::from_millis(500));

    let replayed = dispatch(&handler, incarnation, request)?;
    let ServerValue::ReceiptExpired(ReceiptExpired::CredentialAttach {
        token,
        presented_generation,
        result_generation,
        current_generation,
        reason,
        ..
    }) = replayed
    else {
        return Err(
            format!("expected the ReceiptExpired provenance row, got: {replayed:?}").into(),
        );
    };
    assert_eq!(token, AttachAttemptToken::new(attach_token));
    assert_eq!(presented_generation, GEN_ONE);
    assert_eq!(
        result_generation,
        generation(2)?,
        "the provenance row must carry the minted RESULT generation"
    );
    assert_eq!(current_generation, generation(2)?);
    assert_eq!(reason, ReceiptExpiryReason::Deadline);
    Ok(())
}

/// A receipt replaced by a newer rotation keeps a bounded provenance record:
/// inside its window the exact old token answers `ReceiptExpired` with reason
/// `Superseded`; after the window it answers `StaleOrUnknownReceipt` — never
/// the false no-commit proof `StaleAuthority`.
///
/// Time is driven deterministically through the harness-owned clock seam
/// ([`ProductionParticipantHandler::pin_clock_ms`]) rather than the wall
/// clock: `T0` and the second rotation are both stamped at a pinned base, so
/// the rotation provably lands inside the first receipt's live receipt window
/// (yielding `Superseded`); the in-window read is stepped to a fixed instant
/// past the receipt window but inside the provenance window; and the
/// after-window read is stepped past the provenance deadline. No wall-clock
/// race and no sleep survive, so a loaded suite cannot elapse a window out
/// from under an assertion. TTLs are tightened accordingly (never widened).
#[test]
fn superseded_receipt_keeps_provenance_then_degrades_to_stale_or_unknown()
-> Result<(), Box<dyn Error>> {
    // Pinned base and tightened windows: the receipt (secret) window closes at
    // BASE + RECEIPT_TTL_MS, the provenance window at BASE + PROVENANCE_TTL_MS.
    const BASE_MS: u64 = 1_000_000_000;
    const RECEIPT_TTL_MS: u64 = 1_000;
    const PROVENANCE_TTL_MS: u64 = 2_000;

    let home = tempfile::tempdir()?;
    let data_dir = home.path().join("durability");
    let incarnation = ConnectionIncarnation::new(63, 1);
    let store = open_disk_store_for_tests(&data_dir)?;
    let handler = ProductionParticipantHandler::new(
        store,
        short_ttl_config(RECEIPT_TTL_MS, PROVENANCE_TTL_MS),
    )?;
    let conversation_id = 603;

    // Pin the clock at the base for the whole build: enrollment, first attach
    // (mints the first receipt at T0 = BASE), the second detach, and the
    // second attach (supersedes at T1 = BASE) all read the same instant, so
    // T1 < T0 + RECEIPT_TTL_MS holds by construction and the retired first
    // receipt is recorded with reason Superseded — never a load-dependent
    // Deadline.
    handler.pin_clock_ms(BASE_MS);

    let receipt = enroll(&handler, incarnation, conversation_id, [67; 16])?;
    let participant_id = receipt.participant_id();
    detach(
        &handler,
        incarnation,
        conversation_id,
        participant_id,
        GEN_ONE,
        [68; 16],
    )?;
    let first_token = [69; 16];
    let first_request = attach_request(
        conversation_id,
        participant_id,
        GEN_ONE,
        receipt.attach_secret(),
        first_token,
    );
    let first = attach(&handler, incarnation, first_request.clone())?;
    assert_eq!(first.capability_generation(), generation(2)?);
    // Rotate again while the first receipt is still LIVE: detach the second
    // epoch, then attach with the second-generation secret.
    detach(
        &handler,
        incarnation,
        conversation_id,
        participant_id,
        generation(2)?,
        [70; 16],
    )?;
    let second = attach(
        &handler,
        incarnation,
        attach_request(
            conversation_id,
            participant_id,
            generation(2)?,
            first.attach_secret(),
            [71; 16],
        ),
    )?;
    assert_eq!(second.capability_generation(), generation(3)?);

    // Step to a fixed instant past the receipt (secret) window but inside the
    // provenance window: the exact committed old token returns the exact
    // ReceiptExpired payload with Superseded. Deterministic — no wall clock.
    handler.pin_clock_ms(BASE_MS + RECEIPT_TTL_MS + 1);
    let in_window = dispatch(&handler, incarnation, first_request.clone())?;
    let ServerValue::ReceiptExpired(ReceiptExpired::CredentialAttach {
        token,
        presented_generation,
        result_generation,
        current_generation,
        reason,
        ..
    }) = in_window
    else {
        return Err(format!(
            "superseded token inside its window must answer ReceiptExpired, got: {in_window:?}"
        )
        .into());
    };
    assert_eq!(token, AttachAttemptToken::new(first_token));
    assert_eq!(presented_generation, GEN_ONE);
    assert_eq!(result_generation, generation(2)?);
    assert_eq!(current_generation, generation(3)?);
    assert_eq!(reason, ReceiptExpiryReason::Superseded);

    // Step past the provenance deadline: exact-old degrades to the
    // intentionally ambiguous StaleOrUnknownReceipt (no no-commit claim).
    // Deterministic — the window is a pinned instant, not an elapsed sleep.
    handler.pin_clock_ms(BASE_MS + PROVENANCE_TTL_MS + 1);
    let after_window = dispatch(&handler, incarnation, first_request)?;
    let ServerValue::StaleOrUnknownReceipt(StaleOrUnknownReceipt {
        token,
        presented_generation,
        current_generation,
        ..
    }) = after_window
    else {
        return Err(format!(
            "superseded token after its window must answer StaleOrUnknownReceipt, got: \
             {after_window:?}"
        )
        .into());
    };
    assert_eq!(token, AttachAttemptToken::new(first_token));
    assert_eq!(presented_generation, GEN_ONE);
    assert_eq!(current_generation, generation(3)?);
    Ok(())
}

/// Lost-rotation recovery (contract row 4): the exact committed attach token
/// replays with the INVALIDATED old secret while its receipt is live and
/// returns the byte-identical committed result; a wrong secret on the same
/// token stays `StaleAuthority`.
#[test]
fn live_receipt_replays_with_invalidated_old_secret() -> Result<(), Box<dyn Error>> {
    let home = tempfile::tempdir()?;
    let data_dir = home.path().join("durability");
    let incarnation = ConnectionIncarnation::new(64, 1);
    let store = open_disk_store_for_tests(&data_dir)?;
    let handler = ProductionParticipantHandler::new(store, test_participant_config())?;
    let conversation_id = 604;

    let receipt = enroll(&handler, incarnation, conversation_id, [72; 16])?;
    let participant_id = receipt.participant_id();
    detach(
        &handler,
        incarnation,
        conversation_id,
        participant_id,
        GEN_ONE,
        [73; 16],
    )?;
    let old_secret = receipt.attach_secret();
    let request = attach_request(
        conversation_id,
        participant_id,
        GEN_ONE,
        old_secret,
        [74; 16],
    );
    let attached = attach(&handler, incarnation, request.clone())?;
    assert_ne!(
        attached.attach_secret(),
        old_secret,
        "rotation must invalidate the presented secret"
    );

    // Exact replay with the invalidated OLD secret, same connection: the
    // origin slot still holds this binding epoch, so the replay is Bound and
    // byte-identical to the committed result.
    let replayed = dispatch(&handler, incarnation, request)?;
    let ServerValue::Bound(ReceiptReplay::CredentialAttach(replay)) = replayed else {
        return Err(format!("live receipt replay must answer Bound, got: {replayed:?}").into());
    };
    assert_eq!(
        replay, attached,
        "replay must be the exact committed result"
    );

    // Same token with a WRONG secret is StaleAuthority, not a replay.
    let forged = dispatch(
        &handler,
        incarnation,
        attach_request(
            conversation_id,
            participant_id,
            GEN_ONE,
            AttachSecret::new([0xEE; 32]),
            [74; 16],
        ),
    )?;
    assert!(
        matches!(forged, ServerValue::StaleAuthority(_)),
        "wrong-secret replay of a live token must be StaleAuthority: {forged:?}"
    );
    Ok(())
}