saddle-core 0.3.8

Shared contracts for Saddle components
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
use std::{
    net::SocketAddr,
    sync::atomic::{AtomicU64, Ordering},
    time::Duration,
};

use sha2::{Digest, Sha256};

static NEXT_RENDEZVOUS_GENERATION: AtomicU64 = AtomicU64::new(1);

/// Concrete internal issuer for one generated-application/process rendezvous.
///
/// ```compile_fail
/// use saddle_core::BootstrapRendezvousIssuer;
/// fn duplicate(value: BootstrapRendezvousIssuer) { let _ = value.clone(); }
/// ```
///
/// ```compile_fail
/// use saddle_core::{BootstrapRendezvousIssuer, GeneratedApplicationFreezeSource};
/// let issuer = BootstrapRendezvousIssuer::issue();
/// let _first = issuer.freeze_application(GeneratedApplicationFreezeSource::new(
///     "app", b"descriptor", &["route"],
/// ));
/// let _replay = issuer.freeze_application(GeneratedApplicationFreezeSource::new(
///     "app", b"descriptor", &["route"],
/// ));
/// ```
#[doc(hidden)]
pub struct BootstrapRendezvousIssuer {
    generation: u64,
}

/// Typed generated application freeze input. It contains source declarations,
/// never a caller-provided digest or numeric capacity.
#[doc(hidden)]
pub struct GeneratedApplicationFreezeSource {
    application: &'static str,
    descriptor: &'static [u8],
    route_sources: &'static [&'static str],
}

/// Typed listener/startup freeze input.
#[doc(hidden)]
pub struct ListenerStartupFreezeSource<'a> {
    application: &'a str,
    listener: SocketAddr,
    management: SocketAddr,
    request_timeout: Duration,
}

#[doc(hidden)]
pub struct BootstrapApplicationHalf {
    generation: u64,
    application_identity: [u8; 32],
    route_cost_identity: [u8; 32],
}

#[doc(hidden)]
pub struct BootstrapListenerIssuer {
    generation: u64,
    application_name_identity: [u8; 32],
    application_identity: [u8; 32],
    route_cost_identity: [u8; 32],
}

#[doc(hidden)]
pub struct BootstrapListenerHalf {
    generation: u64,
    application_identity: [u8; 32],
    route_cost_identity: [u8; 32],
    listener_startup_identity: [u8; 32],
}

/// The sole concrete value Admission may consume after the two freezes pair.
///
/// ```compile_fail
/// use saddle_core::BootstrapRendezvousWhole;
/// fn duplicate(value: BootstrapRendezvousWhole) { let _ = value.clone(); }
/// ```
///
/// ```compile_fail
/// use saddle_core::BootstrapRendezvousWhole;
/// let _ = BootstrapRendezvousWhole {
///     _generation: 1,
///     _application_identity: [1; 32],
///     _route_cost_identity: [2; 32],
///     _listener_startup_identity: [3; 32],
/// };
/// ```
#[doc(hidden)]
pub struct BootstrapRendezvousWhole {
    binding_id: BootstrapBindingId,
    _application_identity: [u8; 32],
    _route_cost_identity: [u8; 32],
    _listener_startup_identity: [u8; 32],
}

#[derive(Eq, PartialEq)]
struct BootstrapBindingId([u8; 32]);

/// Linear companion issued by the same freeze as the rendezvous whole.
///
/// ```compile_fail
/// use saddle_core::BootstrapBindingReceipt;
/// fn duplicate(value: BootstrapBindingReceipt) { let _ = value.clone(); }
/// ```
#[doc(hidden)]
pub struct BootstrapBindingReceipt {
    binding_id: BootstrapBindingId,
}

/// Runtime's one-shot half of a verified bootstrap binding.
///
/// ```compile_fail
/// use saddle_core::BootstrapRuntimeBindingReceipt;
/// fn replay(value: BootstrapRuntimeBindingReceipt) {
///     saddle_core::take_runtime_bootstrap_receipt(value);
/// }
/// ```
#[doc(hidden)]
pub struct BootstrapRuntimeBindingReceipt {
    binding_id: BootstrapBindingId,
}

/// The budget-side half retained while Runtime moves the receipt half into its
/// verified re-solve transaction.
#[doc(hidden)]
pub struct BootstrapRuntimeBindingRemainder {
    whole: BootstrapRendezvousWhole,
}

/// A consuming proof that the Runtime half and budget-side whole came from the
/// same bootstrap freeze. It exposes no identity material.
#[doc(hidden)]
pub struct VerifiedBootstrapRuntimeBinding {
    whole: BootstrapRendezvousWhole,
    receipt: BootstrapRuntimeBindingReceipt,
}

impl core::fmt::Debug for VerifiedBootstrapRuntimeBinding {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.write_str("VerifiedBootstrapRuntimeBinding(..)")
    }
}

impl PartialEq for VerifiedBootstrapRuntimeBinding {
    fn eq(&self, other: &Self) -> bool {
        self.whole.binding_id == other.whole.binding_id
            && self.receipt.binding_id == other.receipt.binding_id
    }
}

impl Eq for VerifiedBootstrapRuntimeBinding {}

/// A whole whose binding receipt has been checked and consumed.
#[doc(hidden)]
pub struct BoundBootstrapRendezvous {
    _whole: BootstrapRendezvousWhole,
    runtime_receipt: BootstrapRuntimeBindingReceipt,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum BootstrapRendezvousError {
    InvalidSource,
    ForeignSource,
}

impl BootstrapRendezvousIssuer {
    #[doc(hidden)]
    pub fn issue() -> Self {
        Self {
            generation: NEXT_RENDEZVOUS_GENERATION.fetch_add(1, Ordering::Relaxed),
        }
    }

    #[doc(hidden)]
    pub fn freeze_application(
        self,
        source: GeneratedApplicationFreezeSource,
    ) -> Result<(BootstrapApplicationHalf, BootstrapListenerIssuer), BootstrapRendezvousError> {
        if self.generation == 0
            || source.application.is_empty()
            || source.descriptor.is_empty()
            || source.route_sources.is_empty()
            || source.route_sources.iter().any(|route| route.is_empty())
        {
            return Err(BootstrapRendezvousError::InvalidSource);
        }
        let application_identity = identity(&[
            b"saddle-bootstrap-application-v1",
            source.application.as_bytes(),
            source.descriptor,
        ]);
        let application_name_identity = identity(&[
            b"saddle-bootstrap-application-name-v1",
            source.application.as_bytes(),
        ]);
        let mut route_hasher = Sha256::new();
        route_hasher.update(b"saddle-bootstrap-route-cost-source-v1");
        for route in source.route_sources {
            route_hasher.update((route.len() as u64).to_be_bytes());
            route_hasher.update(route.as_bytes());
        }
        let route_cost_identity = route_hasher.finalize().into();
        Ok((
            BootstrapApplicationHalf {
                generation: self.generation,
                application_identity,
                route_cost_identity,
            },
            BootstrapListenerIssuer {
                generation: self.generation,
                application_name_identity,
                application_identity,
                route_cost_identity,
            },
        ))
    }
}

impl GeneratedApplicationFreezeSource {
    #[doc(hidden)]
    pub const fn new(
        application: &'static str,
        descriptor: &'static [u8],
        route_sources: &'static [&'static str],
    ) -> Self {
        Self {
            application,
            descriptor,
            route_sources,
        }
    }
}

impl<'a> ListenerStartupFreezeSource<'a> {
    #[doc(hidden)]
    pub const fn new(
        application: &'a str,
        listener: SocketAddr,
        management: SocketAddr,
        request_timeout: Duration,
    ) -> Self {
        Self {
            application,
            listener,
            management,
            request_timeout,
        }
    }
}

impl BootstrapListenerIssuer {
    #[doc(hidden)]
    pub fn freeze_listener(
        self,
        source: ListenerStartupFreezeSource<'_>,
    ) -> Result<BootstrapListenerHalf, (BootstrapRendezvousError, Self)> {
        if source.application.is_empty() || source.request_timeout.is_zero() {
            return Err((BootstrapRendezvousError::InvalidSource, self));
        }
        let application_name_identity = identity(&[
            b"saddle-bootstrap-application-name-v1",
            source.application.as_bytes(),
        ]);
        if application_name_identity != self.application_name_identity {
            return Err((BootstrapRendezvousError::ForeignSource, self));
        }
        let listener = source.listener.to_string();
        let management = source.management.to_string();
        let timeout = source.request_timeout.as_millis().to_be_bytes();
        let listener_startup_identity = identity(&[
            b"saddle-bootstrap-listener-startup-v1",
            listener.as_bytes(),
            management.as_bytes(),
            &timeout,
        ]);
        Ok(BootstrapListenerHalf {
            generation: self.generation,
            application_identity: self.application_identity,
            route_cost_identity: self.route_cost_identity,
            listener_startup_identity,
        })
    }
}

#[doc(hidden)]
pub fn pair_bootstrap_rendezvous(
    application: BootstrapApplicationHalf,
    listener: BootstrapListenerHalf,
) -> Result<
    (BootstrapRendezvousWhole, BootstrapBindingReceipt),
    (
        BootstrapRendezvousError,
        BootstrapApplicationHalf,
        BootstrapListenerHalf,
    ),
> {
    if application.generation != listener.generation
        || application.application_identity != listener.application_identity
        || application.route_cost_identity != listener.route_cost_identity
    {
        return Err((
            BootstrapRendezvousError::ForeignSource,
            application,
            listener,
        ));
    }
    let binding = identity(&[
        b"saddle-bootstrap-binding-v1",
        &application.generation.to_be_bytes(),
        &application.application_identity,
        &application.route_cost_identity,
        &listener.listener_startup_identity,
    ]);
    Ok((
        BootstrapRendezvousWhole {
            binding_id: BootstrapBindingId(binding),
            _application_identity: application.application_identity,
            _route_cost_identity: application.route_cost_identity,
            _listener_startup_identity: listener.listener_startup_identity,
        },
        BootstrapBindingReceipt {
            binding_id: BootstrapBindingId(binding),
        },
    ))
}

/// Consumes both owners and either binds them or returns both unchanged.
#[doc(hidden)]
pub fn bind_bootstrap_receipt(
    whole: BootstrapRendezvousWhole,
    receipt: BootstrapBindingReceipt,
) -> Result<BoundBootstrapRendezvous, (BootstrapRendezvousWhole, BootstrapBindingReceipt)> {
    if whole.binding_id != receipt.binding_id {
        return Err((whole, receipt));
    }
    let runtime_receipt = BootstrapRuntimeBindingReceipt {
        binding_id: BootstrapBindingId(receipt.binding_id.0),
    };
    Ok(BoundBootstrapRendezvous {
        _whole: whole,
        runtime_receipt,
    })
}

/// One-shot handoff. The whole remains opaque in a linear remainder so a
/// failed Runtime bind can restore the exact original owner.
#[doc(hidden)]
pub fn take_runtime_bootstrap_receipt(
    bound: BoundBootstrapRendezvous,
) -> (
    BootstrapRuntimeBindingRemainder,
    BootstrapRuntimeBindingReceipt,
) {
    (
        BootstrapRuntimeBindingRemainder {
            whole: bound._whole,
        },
        bound.runtime_receipt,
    )
}

/// Consumes both halves and returns them unchanged on a foreign-source bind.
#[doc(hidden)]
pub fn verify_runtime_bootstrap_binding(
    remainder: BootstrapRuntimeBindingRemainder,
    receipt: BootstrapRuntimeBindingReceipt,
) -> Result<
    VerifiedBootstrapRuntimeBinding,
    (
        BootstrapRuntimeBindingRemainder,
        BootstrapRuntimeBindingReceipt,
    ),
> {
    if remainder.whole.binding_id != receipt.binding_id {
        return Err((remainder, receipt));
    }
    Ok(VerifiedBootstrapRuntimeBinding {
        whole: remainder.whole,
        receipt,
    })
}

/// Total rollback from a verified Runtime binding to the original bound whole.
#[doc(hidden)]
pub fn restore_bound_bootstrap_rendezvous(
    verified: VerifiedBootstrapRuntimeBinding,
) -> BoundBootstrapRendezvous {
    BoundBootstrapRendezvous {
        _whole: verified.whole,
        runtime_receipt: verified.receipt,
    }
}

/// Total consuming recovery used when a later Runtime stage fails before
/// publication.
#[doc(hidden)]
pub fn recover_verified_runtime_bootstrap_binding(
    verified: VerifiedBootstrapRuntimeBinding,
) -> (
    BootstrapRuntimeBindingRemainder,
    BootstrapRuntimeBindingReceipt,
) {
    (
        BootstrapRuntimeBindingRemainder {
            whole: verified.whole,
        },
        verified.receipt,
    )
}

fn identity(parts: &[&[u8]]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    for part in parts {
        hasher.update((part.len() as u64).to_be_bytes());
        hasher.update(part);
    }
    hasher.finalize().into()
}

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

    fn halves(
        application: &'static str,
        listener: SocketAddr,
    ) -> (BootstrapApplicationHalf, BootstrapListenerHalf) {
        let (application_half, listener_issuer) = BootstrapRendezvousIssuer::issue()
            .freeze_application(GeneratedApplicationFreezeSource::new(
                application,
                b"descriptor",
                &["lookup|Input|Output|handler"],
            ))
            .unwrap();
        let listener_half = match listener_issuer.freeze_listener(ListenerStartupFreezeSource::new(
            application,
            listener,
            "127.0.0.1:9001".parse().unwrap(),
            Duration::from_millis(5_000),
        )) {
            Ok(listener) => listener,
            Err(_) => panic!("valid listener source rejected"),
        };
        (application_half, listener_half)
    }

    #[test]
    fn same_transaction_pairs_and_foreign_halves_are_returned_whole() {
        let (application_a, listener_a) = halves("app-a", "127.0.0.1:8000".parse().unwrap());
        assert!(pair_bootstrap_rendezvous(application_a, listener_a).is_ok());

        let (application_a, listener_a) = halves("app-a", "127.0.0.1:8000".parse().unwrap());
        let (application_b, listener_b) = halves("app-b", "127.0.0.1:8002".parse().unwrap());
        let (error, application_a, listener_b) =
            match pair_bootstrap_rendezvous(application_a, listener_b) {
                Ok(_) => panic!("foreign halves paired"),
                Err(failure) => failure,
            };
        assert_eq!(error, BootstrapRendezvousError::ForeignSource);
        assert!(pair_bootstrap_rendezvous(application_a, listener_a).is_ok());
        assert!(pair_bootstrap_rendezvous(application_b, listener_b).is_ok());
    }

    #[test]
    fn binding_receipt_rejects_crossed_wholes_and_returns_both_for_retry() {
        let (application_a, listener_a) = halves("app-a", "127.0.0.1:8000".parse().unwrap());
        let (application_b, listener_b) = halves("app-b", "127.0.0.1:8002".parse().unwrap());
        let (whole_a, receipt_a) = match pair_bootstrap_rendezvous(application_a, listener_a) {
            Ok(value) => value,
            Err(_) => panic!("same-source A rejected"),
        };
        let (whole_b, receipt_b) = match pair_bootstrap_rendezvous(application_b, listener_b) {
            Ok(value) => value,
            Err(_) => panic!("same-source B rejected"),
        };

        let (whole_a, receipt_b) = match bind_bootstrap_receipt(whole_a, receipt_b) {
            Ok(_) => panic!("crossed binding accepted"),
            Err(inputs) => inputs,
        };
        let (whole_b, receipt_a) = match bind_bootstrap_receipt(whole_b, receipt_a) {
            Ok(_) => panic!("crossed binding accepted"),
            Err(inputs) => inputs,
        };
        assert!(bind_bootstrap_receipt(whole_a, receipt_a).is_ok());
        assert!(bind_bootstrap_receipt(whole_b, receipt_b).is_ok());
    }

    #[test]
    fn runtime_halves_reject_cross_source_and_original_pairs_retry() {
        let (application_a, listener_a) = halves("app-a", "127.0.0.1:8000".parse().unwrap());
        let (application_b, listener_b) = halves("app-b", "127.0.0.1:8002".parse().unwrap());
        let (whole_a, receipt_a) = match pair_bootstrap_rendezvous(application_a, listener_a) {
            Ok(value) => value,
            Err(_) => panic!("same-source A rejected"),
        };
        let (whole_b, receipt_b) = match pair_bootstrap_rendezvous(application_b, listener_b) {
            Ok(value) => value,
            Err(_) => panic!("same-source B rejected"),
        };
        let bound_a = match bind_bootstrap_receipt(whole_a, receipt_a) {
            Ok(value) => value,
            Err(_) => panic!("same-source A receipt rejected"),
        };
        let bound_b = match bind_bootstrap_receipt(whole_b, receipt_b) {
            Ok(value) => value,
            Err(_) => panic!("same-source B receipt rejected"),
        };
        let (remainder_a, runtime_a) = take_runtime_bootstrap_receipt(bound_a);
        let (remainder_b, runtime_b) = take_runtime_bootstrap_receipt(bound_b);

        let (remainder_a, runtime_b) =
            verify_runtime_bootstrap_binding(remainder_a, runtime_b).unwrap_err();
        let (remainder_b, runtime_a) =
            verify_runtime_bootstrap_binding(remainder_b, runtime_a).unwrap_err();
        let verified_a = match verify_runtime_bootstrap_binding(remainder_a, runtime_a) {
            Ok(value) => value,
            Err(_) => panic!("original A pair rejected"),
        };
        let verified_b = match verify_runtime_bootstrap_binding(remainder_b, runtime_b) {
            Ok(value) => value,
            Err(_) => panic!("original B pair rejected"),
        };

        let (remainder_a, runtime_a) = recover_verified_runtime_bootstrap_binding(verified_a);
        let (remainder_b, runtime_b) = recover_verified_runtime_bootstrap_binding(verified_b);
        assert!(verify_runtime_bootstrap_binding(remainder_a, runtime_a).is_ok());
        assert!(verify_runtime_bootstrap_binding(remainder_b, runtime_b).is_ok());
    }

    #[test]
    fn listener_application_drift_returns_the_issuer() {
        let (_application, listener) = BootstrapRendezvousIssuer::issue()
            .freeze_application(GeneratedApplicationFreezeSource::new(
                "app-a",
                b"descriptor",
                &["route"],
            ))
            .unwrap();
        let (error, _listener) = match listener.freeze_listener(ListenerStartupFreezeSource::new(
            "app-b",
            "127.0.0.1:8000".parse().unwrap(),
            "127.0.0.1:9000".parse().unwrap(),
            Duration::from_millis(5_000),
        )) {
            Ok(_) => panic!("foreign listener application accepted"),
            Err(failure) => failure,
        };
        assert_eq!(error, BootstrapRendezvousError::ForeignSource);
    }
}