batpak 0.9.0

Event sourcing with causal graphs and caller-defined gates. Sync API, no async runtime.
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
use crate::coordinate::Coordinate;
use crate::event::EventKind;
use crate::store::append::{signing_downgrade_extension_key, SigningDowngradeBody};
use crate::store::{
    AppendReceipt, DenialReceipt, ExtensionKey, ReceiptVerification, ReceiptVerificationError,
    StoreError,
};
use ed25519_compact::{KeyPair, PublicKey, Seed, Signature};
use std::collections::BTreeMap;
use std::sync::Arc;
use zeroize::Zeroizing;

const COVER_VERSION_V1: u8 = 0x01;

/// Opt-in Ed25519 signing key for receipt signatures.
#[derive(Clone)]
pub struct SigningKey {
    seed: Zeroizing<[u8; 32]>,
}

impl SigningKey {
    /// Construct a signing key from 32 seed bytes.
    #[must_use]
    pub fn from_bytes(bytes: [u8; 32]) -> Self {
        Self {
            seed: Zeroizing::new(bytes),
        }
    }

    pub(crate) fn key_id(&self) -> [u8; 32] {
        match self.public_key_bytes() {
            Some(bytes) => key_id_for_public_key(&bytes),
            None => [0; 32],
        }
    }

    fn key_pair(&self) -> KeyPair {
        KeyPair::from_seed(Seed::new(*self.seed))
    }

    fn public_key_bytes(&self) -> Option<[u8; 32]> {
        <[u8; 32]>::try_from(self.key_pair().pk.as_ref()).ok()
    }

    fn sign_cover(&self, cover: [u8; 32]) -> [u8; 64] {
        let signature = self.key_pair().sk.sign(cover, None);
        let mut bytes = [0u8; 64];
        bytes.copy_from_slice(signature.as_ref());
        bytes
    }
}

impl std::fmt::Debug for SigningKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SigningKey")
            .field("key_id", &self.key_id())
            .finish()
    }
}

#[derive(Clone, Default)]
pub(crate) struct ReceiptSigningRegistry {
    current: Option<Arc<SigningKey>>,
    verifying_keys: Arc<BTreeMap<[u8; 32], [u8; 32]>>,
    /// When a signer is configured but its cover cannot be built, permit a
    /// best-effort downgrade to unsigned instead of failing the append.
    allow_downgrade: bool,
}

impl ReceiptSigningRegistry {
    /// Build a signing registry from a key list.
    ///
    /// Every key with a public half is registered as a *verifying* key. The
    /// **active signer** is the LAST key in `keys` that carries a public half —
    /// i.e. ordering is significant: re-ordering the `with_signing_key` calls
    /// that produce this slice silently changes which key signs new receipts.
    /// This is the intended key-rotation mechanism (append the new active key
    /// last); callers must not treat the order as cosmetic.
    pub(crate) fn from_keys(keys: &[SigningKey], allow_downgrade: bool) -> Self {
        let mut verifying_keys = BTreeMap::new();
        let mut current = None;
        for key in keys {
            let key = Arc::new(key.clone());
            if let Some(public_key_bytes) = key.public_key_bytes() {
                verifying_keys.insert(key.key_id(), public_key_bytes);
                current = Some(key);
            }
        }
        Self {
            current,
            verifying_keys: Arc::new(verifying_keys),
            allow_downgrade,
        }
    }

    pub(crate) fn sign_append_receipt(
        &self,
        receipt: &mut AppendReceipt,
        coord: &Coordinate,
        kind: EventKind,
        prev_hash: [u8; 32],
    ) -> Result<(), StoreError> {
        let Some(current) = &self.current else {
            // No active signer: the receipt stays unsigned. No cover is needed,
            // and there is nothing to downgrade.
            receipt.key_id = [0; 32];
            receipt.signature = None;
            return Ok(());
        };
        let cover = match cover_bytes(
            {
                use crate::id::EntityIdType;
                receipt.event_id.as_u128()
            },
            receipt.global_sequence,
            coord,
            kind,
            prev_hash,
            receipt.content_hash,
            &receipt.extensions,
        ) {
            Ok(cover) => cover,
            Err(error) => {
                // A signer is configured but its cover cannot be built. Fail the
                // append closed rather than silently committing an unsigned
                // receipt — unless downgrade is explicitly permitted.
                if cover_failure_fails_closed(self.allow_downgrade) {
                    return Err(StoreError::ser_msg(&format!(
                        "receipt signature cover could not be built: {error}"
                    )));
                }
                tracing::error!(error = %error, "receipt signing downgraded to unsigned (signing_downgrade_allowed)");
                downgrade_receipt_signing(receipt, error.to_string());
                return Ok(());
            }
        };
        receipt.key_id = current.key_id();
        receipt.signature = Some(current.sign_cover(cover));
        Ok(())
    }

    pub(crate) fn verify_append_receipt(
        &self,
        receipt: &AppendReceipt,
        coord: &Coordinate,
        kind: EventKind,
        prev_hash: [u8; 32],
    ) -> ReceiptVerification {
        // Sentinel-signed receipts (no signature, no key) bypass the cover
        // rebuild: signing was either not configured or it downgraded due to
        // a coordinate/extension encoding failure. Their validity is a
        // property of the registry state, not of any computed cover.
        if receipt.signature.is_none() && receipt.key_id == [0; 32] {
            return if self.verifying_keys.is_empty() {
                ReceiptVerification::UnsignedAccepted
            } else {
                ReceiptVerification::Invalid(ReceiptVerificationError::UnsignedReceiptRejected)
            };
        }
        let cover = match cover_bytes(
            {
                use crate::id::EntityIdType;
                receipt.event_id.as_u128()
            },
            receipt.global_sequence,
            coord,
            kind,
            prev_hash,
            receipt.content_hash,
            &receipt.extensions,
        ) {
            Ok(cover) => cover,
            Err(error) => {
                tracing::error!(error = %error, "failed to rebuild append receipt signature cover");
                return ReceiptVerification::Invalid(ReceiptVerificationError::CoverBuildFailed {
                    reason: error.to_string(),
                });
            }
        };
        self.verify_signature(receipt.key_id, receipt.signature, cover)
    }

    pub(crate) fn verify_denial_receipt(
        &self,
        receipt: &DenialReceipt,
        coord: &Coordinate,
        kind: EventKind,
        prev_hash: [u8; 32],
    ) -> ReceiptVerification {
        if receipt.signature.is_none() && receipt.key_id == [0; 32] {
            return if self.verifying_keys.is_empty() {
                ReceiptVerification::UnsignedAccepted
            } else {
                ReceiptVerification::Invalid(ReceiptVerificationError::UnsignedReceiptRejected)
            };
        }
        let cover = match cover_bytes(
            {
                use crate::id::EntityIdType;
                receipt.event_id.as_u128()
            },
            receipt.global_sequence,
            coord,
            kind,
            prev_hash,
            receipt.content_hash,
            &receipt.extensions,
        ) {
            Ok(cover) => cover,
            Err(error) => {
                tracing::error!(error = %error, "failed to rebuild denial receipt signature cover");
                return ReceiptVerification::Invalid(ReceiptVerificationError::CoverBuildFailed {
                    reason: error.to_string(),
                });
            }
        };
        self.verify_signature(receipt.key_id, receipt.signature, cover)
    }

    fn verify_signature(
        &self,
        key_id: [u8; 32],
        signature: Option<[u8; 64]>,
        cover: [u8; 32],
    ) -> ReceiptVerification {
        let Some(signature_bytes) = signature else {
            return if key_id == [0; 32] && self.verifying_keys.is_empty() {
                ReceiptVerification::UnsignedAccepted
            } else if key_id == [0; 32] {
                ReceiptVerification::Invalid(ReceiptVerificationError::UnsignedReceiptRejected)
            } else {
                ReceiptVerification::Invalid(ReceiptVerificationError::MissingSignature)
            };
        };
        if key_id == [0; 32] {
            return ReceiptVerification::Invalid(ReceiptVerificationError::ZeroKeyWithSignature);
        };
        let Some(public_key_bytes) = self.verifying_keys.get(&key_id) else {
            return ReceiptVerification::Invalid(ReceiptVerificationError::UnknownSigningKey);
        };
        let signature = Signature::new(signature_bytes);
        if PublicKey::new(*public_key_bytes)
            .verify(cover, &signature)
            .is_ok()
        {
            ReceiptVerification::Signed
        } else {
            ReceiptVerification::Invalid(ReceiptVerificationError::InvalidSignature)
        }
    }
}

/// A configured signer fails the append closed on cover-build failure unless
/// downgrade is explicitly permitted. The cover-build failure is itself a
/// defensive guard — it requires the coordinate/extension MessagePack encoding
/// to fail, which does not occur for valid inputs — so this disposition is the
/// directly unit-tested policy.
const fn cover_failure_fails_closed(allow_downgrade: bool) -> bool {
    !allow_downgrade
}

fn downgrade_receipt_signing(receipt: &mut AppendReceipt, error: impl Into<String>) {
    let body = SigningDowngradeBody::cover_build_failed(error);
    match body.encode_extension() {
        Ok(bytes) => {
            receipt
                .extensions
                .insert(signing_downgrade_extension_key(), bytes);
        }
        Err(error) => {
            tracing::error!(
                error = %error,
                "failed to encode signing downgrade receipt extension"
            );
        }
    }
    receipt.key_id = [0; 32];
    receipt.signature = None;
}

#[derive(Debug)]
enum CoverBuildError {
    CoordinateEncoding(rmp_serde::encode::Error),
    ExtensionsEncoding(rmp_serde::encode::Error),
}

impl std::fmt::Display for CoverBuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CoordinateEncoding(error) => {
                write!(
                    f,
                    "coordinate encoding failed while building receipt cover: {error}"
                )
            }
            Self::ExtensionsEncoding(error) => {
                write!(
                    f,
                    "extension encoding failed while building receipt cover: {error}"
                )
            }
        }
    }
}

impl std::error::Error for CoverBuildError {}

fn key_id_for_public_key(public_key: &[u8; 32]) -> [u8; 32] {
    crate::event::hash::compute_hash(public_key)
}

fn cover_bytes(
    event_id: u128,
    sequence: u64,
    coord: &Coordinate,
    kind: EventKind,
    prev_hash: [u8; 32],
    content_hash: [u8; 32],
    extensions: &BTreeMap<ExtensionKey, Vec<u8>>,
) -> Result<[u8; 32], CoverBuildError> {
    let mut cover = Vec::new();
    cover.push(COVER_VERSION_V1);
    cover.extend_from_slice(&event_id.to_le_bytes());
    cover.extend_from_slice(&sequence.to_le_bytes());
    let coord_bytes =
        crate::canonical::to_bytes(coord).map_err(CoverBuildError::CoordinateEncoding)?;
    cover.extend_from_slice(&coord_bytes);
    let raw_kind = kind.as_raw_u16();
    cover.extend_from_slice(&raw_kind.to_le_bytes());
    cover.extend_from_slice(&prev_hash);
    cover.extend_from_slice(&content_hash);
    let extension_bytes =
        crate::canonical::to_bytes(extensions).map_err(CoverBuildError::ExtensionsEncoding)?;
    cover.extend_from_slice(&extension_bytes);
    Ok(crate::event::hash::compute_hash(&cover))
}

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

    #[test]
    fn cover_failure_is_fatal_unless_downgrade_allowed() {
        // Default: a configured signer that cannot build its cover FAILS the
        // append closed (never silently emits an unsigned receipt).
        assert!(cover_failure_fails_closed(false));
        // Opt-in: best-effort downgrade is permitted only when explicitly asked.
        assert!(!cover_failure_fails_closed(true));
    }

    #[test]
    fn cover_bytes_separates_event_kind_category_and_type_bits() {
        let coord = Coordinate::new("receipt:cover", "scope:test").expect("coordinate");
        let extensions = BTreeMap::new();

        let cover_a = cover_bytes(
            1,
            1,
            &coord,
            EventKind::custom(0xF, 0x055),
            [0x11; 32],
            [0x22; 32],
            &extensions,
        )
        .expect("cover A");
        let cover_b = cover_bytes(
            1,
            1,
            &coord,
            EventKind::custom(0xE, 0x055),
            [0x11; 32],
            [0x22; 32],
            &extensions,
        )
        .expect("cover B");
        let cover_c = cover_bytes(
            1,
            1,
            &coord,
            EventKind::custom(0xF, 0x056),
            [0x11; 32],
            [0x22; 32],
            &extensions,
        )
        .expect("cover C");

        assert_ne!(
            cover_a, cover_b,
            "PROPERTY: receipt signature cover must include the EventKind category bits"
        );
        assert_ne!(
            cover_a, cover_c,
            "PROPERTY: receipt signature cover must include the EventKind type-id bits"
        );
    }

    #[test]
    fn cover_build_failure_adds_signing_downgrade_extension() {
        let mut receipt = AppendReceipt {
            event_id: crate::id::EventId::from(7u128),
            global_sequence: 9,
            disk_pos: crate::store::index::DiskPos {
                segment_id: 1,
                offset: 2,
                length: 3,
            },
            content_hash: [0x22; 32],
            key_id: [0xAA; 32],
            signature: Some([0xBB; 64]),
            extensions: BTreeMap::new(),
        };

        downgrade_receipt_signing(&mut receipt, "synthetic cover failure");

        assert_eq!(receipt.key_id, [0; 32]);
        assert!(receipt.signature.is_none());
        let downgrade = receipt
            .signing_downgrade()
            .expect("downgrade extension should decode");
        assert!(matches!(
            downgrade.reason,
            crate::store::SigningDowngradeReason::CoverBuildFailed { ref encoding_error }
                if encoding_error == "synthetic cover failure"
        ));
    }
}

/// Cure island for the receipt-verification sentinel/unsigned dispositions and
/// the Debug/Display renderers. Split from the island above to stay within the
/// inline test-island budget.
#[cfg(test)]
mod verify_cure_tests {
    use super::*;
    use crate::store::index::DiskPos;

    fn receipt(key_id: [u8; 32], signature: Option<[u8; 64]>) -> AppendReceipt {
        AppendReceipt {
            event_id: crate::id::EventId::from(3u128),
            global_sequence: 1,
            disk_pos: DiskPos::new(1, 0, 1),
            content_hash: [0x11; 32],
            key_id,
            signature,
            extensions: BTreeMap::new(),
        }
    }

    fn denial(key_id: [u8; 32], signature: Option<[u8; 64]>) -> DenialReceipt {
        DenialReceipt {
            event_id: crate::id::EventId::from(4u128),
            global_sequence: 2,
            disk_pos: DiskPos::new(1, 0, 1),
            content_hash: [0x22; 32],
            key_id,
            signature,
            extensions: BTreeMap::new(),
        }
    }

    #[test]
    fn verify_append_receipt_unsigned_with_nonsentinel_key_is_missing_signature() {
        let registry = ReceiptSigningRegistry::from_keys(&[], false);
        let coord = Coordinate::new("entity:sig", "scope:sig").expect("coord");
        // signature.is_none() is true but key_id is NOT the sentinel, so the
        // unsigned bypass must NOT trigger; the receipt falls through to
        // signature checking and is MissingSignature. `&& -> ||` and `== -> !=`
        // both wrongly take the bypass and return UnsignedAccepted.
        assert_eq!(
            registry.verify_append_receipt(
                &receipt([0xAA; 32], None),
                &coord,
                EventKind::custom(0xF, 1),
                [0; 32],
            ),
            ReceiptVerification::Invalid(ReceiptVerificationError::MissingSignature),
        );
    }

    #[test]
    fn verify_denial_receipt_unsigned_with_nonsentinel_key_is_missing_signature() {
        let registry = ReceiptSigningRegistry::from_keys(&[], false);
        let coord = Coordinate::new("entity:sig-d", "scope:sig").expect("coord");
        assert_eq!(
            registry.verify_denial_receipt(
                &denial([0xBB; 32], None),
                &coord,
                EventKind::custom(0xF, 2),
                [0; 32],
            ),
            ReceiptVerification::Invalid(ReceiptVerificationError::MissingSignature),
        );
    }

    #[test]
    fn verify_signature_unsigned_dispositions_match_key_and_registry_state() {
        let empty = ReceiptSigningRegistry::from_keys(&[], false);
        let keyed = ReceiptSigningRegistry::from_keys(&[SigningKey::from_bytes([7u8; 32])], false);
        let cover = [0u8; 32];
        // Sentinel key + empty registry -> UnsignedAccepted. Kills `== -> !=` (227).
        assert_eq!(
            empty.verify_signature([0; 32], None, cover),
            ReceiptVerification::UnsignedAccepted,
        );
        // Non-sentinel key + empty registry -> MissingSignature. Kills `&& -> ||` (227).
        assert_eq!(
            empty.verify_signature([0xAA; 32], None, cover),
            ReceiptVerification::Invalid(ReceiptVerificationError::MissingSignature),
        );
        // Sentinel key + NON-empty registry -> UnsignedReceiptRejected. Kills `== -> !=` (229).
        assert_eq!(
            keyed.verify_signature([0; 32], None, cover),
            ReceiptVerification::Invalid(ReceiptVerificationError::UnsignedReceiptRejected),
        );
    }

    #[test]
    fn cover_build_error_display_renders_the_stage_and_is_never_empty() {
        use serde::ser::Error as _;
        // A synthetic rmp encode error carried by the CoordinateEncoding variant.
        let encode_err = rmp_serde::encode::Error::custom("boom");
        let display = format!("{}", CoverBuildError::CoordinateEncoding(encode_err));
        // Kills the body-stub `Ok(())` mutant, which renders an empty string.
        assert!(
            display.contains("coordinate encoding failed while building receipt cover"),
            "Display must render the coordinate-encoding cover-build failure, got {display:?}"
        );
    }

    #[test]
    fn signing_key_debug_names_the_struct_and_key_id() {
        let debug = format!("{:?}", SigningKey::from_bytes([7u8; 32]));
        // Kills the body-stub `Ok(())` mutant, which renders an empty string.
        assert!(
            debug.contains("SigningKey") && debug.contains("key_id"),
            "Debug must render the SigningKey struct with its key_id field, got {debug:?}"
        );
    }
}