krill 0.9.0

Resource Public Key Infrastructure (RPKI) daemon
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
use std::collections::HashMap;
use std::fmt;

use rpki::crypto::KeyIdentifier;

use crate::{
    commons::{
        api::{
            ChildHandle, Handle, IssuanceRequest, IssuedCert, ObjectName, ParentCaContact, ParentHandle,
            ParentResourceClassName, RcvdCert, RepositoryContact, ResourceClassName, ResourceSet, RevocationRequest,
            RevokedObject, RoaAggregateKey, RtaName, TaCertDetails,
        },
        crypto::{IdCert, KrillSigner},
        eventsourcing::StoredEvent,
        KrillResult,
    },
    daemon::ca::{
        AggregateRoaInfo, CertifiedKey, PreparedRta, PublishedRoa, Rfc8183Id, RoaInfo, RouteAuthorization, SignedRta,
    },
};

//------------ Ini -----------------------------------------------------------

pub type Ini = StoredEvent<IniDet>;

//------------ IniDet --------------------------------------------------------

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct IniDet {
    id: Rfc8183Id,
}

impl IniDet {
    pub fn unpack(self) -> Rfc8183Id {
        self.id
    }
}

impl IniDet {
    pub fn new(handle: &Handle, id: Rfc8183Id) -> Ini {
        Ini::new(handle, 0, IniDet { id })
    }

    pub fn init(handle: &Handle, signer: &KrillSigner) -> KrillResult<Ini> {
        let id = Rfc8183Id::generate(signer)?;
        Ok(Self::new(handle, id))
    }
}

impl fmt::Display for IniDet {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Initialized with ID key hash: {}", self.id.key_hash())?;
        Ok(())
    }
}

//------------ RoaUpdates --------------------------------------------------

/// Describes an update to the set of ROAs under a ResourceClass.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RoaUpdates {
    #[serde(
        skip_serializing_if = "HashMap::is_empty",
        default = "HashMap::new",
        with = "updated_sorted_map"
    )]
    updated: HashMap<RouteAuthorization, RoaInfo>,

    #[serde(
        skip_serializing_if = "HashMap::is_empty",
        default = "HashMap::new",
        with = "removed_sorted_map"
    )]
    removed: HashMap<RouteAuthorization, RevokedObject>,

    #[serde(
        skip_serializing_if = "HashMap::is_empty",
        default = "HashMap::new",
        with = "aggregate_updated_sorted_map"
    )]
    aggregate_updated: HashMap<RoaAggregateKey, AggregateRoaInfo>,

    #[serde(
        skip_serializing_if = "HashMap::is_empty",
        default = "HashMap::new",
        with = "aggregate_removed_sorted_map"
    )]
    aggregate_removed: HashMap<RoaAggregateKey, RevokedObject>,
}

mod updated_sorted_map {
    use super::*;

    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;

    #[derive(Debug, Deserialize)]
    struct Item {
        auth: RouteAuthorization,
        roa: RoaInfo,
    }

    #[derive(Debug, Serialize)]
    struct ItemRef<'a> {
        auth: &'a RouteAuthorization,
        roa: &'a RoaInfo,
    }

    pub fn serialize<S>(map: &HashMap<RouteAuthorization, RoaInfo>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sorted_vec: Vec<ItemRef> = map.iter().map(|(auth, roa)| ItemRef { auth, roa }).collect();
        sorted_vec.sort_by_key(|el| el.auth);

        serializer.collect_seq(sorted_vec)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<RouteAuthorization, RoaInfo>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut map = HashMap::new();
        for item in Vec::<Item>::deserialize(deserializer)? {
            map.insert(item.auth, item.roa);
        }
        Ok(map)
    }
}

mod aggregate_updated_sorted_map {
    use super::*;

    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;

    #[derive(Debug, Deserialize)]
    struct Item {
        agg: RoaAggregateKey,
        roa: AggregateRoaInfo,
    }

    #[derive(Debug, Serialize)]
    struct ItemRef<'a> {
        agg: &'a RoaAggregateKey,
        roa: &'a AggregateRoaInfo,
    }

    pub fn serialize<S>(map: &HashMap<RoaAggregateKey, AggregateRoaInfo>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sorted_vec: Vec<ItemRef> = map.iter().map(|(agg, roa)| ItemRef { agg, roa }).collect();
        sorted_vec.sort_by_key(|el| el.agg);

        serializer.collect_seq(sorted_vec)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<RoaAggregateKey, AggregateRoaInfo>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut map = HashMap::new();
        for item in Vec::<Item>::deserialize(deserializer)? {
            map.insert(item.agg, item.roa);
        }
        Ok(map)
    }
}

mod removed_sorted_map {
    use super::*;

    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;

    #[derive(Debug, Deserialize)]
    struct Item {
        auth: RouteAuthorization,
        removed: RevokedObject,
    }

    #[derive(Debug, Serialize)]
    struct ItemRef<'a> {
        auth: &'a RouteAuthorization,
        removed: &'a RevokedObject,
    }

    pub fn serialize<S>(map: &HashMap<RouteAuthorization, RevokedObject>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sorted_vec: Vec<ItemRef> = map.iter().map(|(auth, removed)| ItemRef { auth, removed }).collect();
        sorted_vec.sort_by_key(|el| el.auth);

        serializer.collect_seq(sorted_vec)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<RouteAuthorization, RevokedObject>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut map = HashMap::new();
        for item in Vec::<Item>::deserialize(deserializer)? {
            map.insert(item.auth, item.removed);
        }
        Ok(map)
    }
}

mod aggregate_removed_sorted_map {
    use super::*;

    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;

    #[derive(Debug, Deserialize)]
    struct Item {
        agg: RoaAggregateKey,
        removed: RevokedObject,
    }

    #[derive(Debug, Serialize)]
    struct ItemRef<'a> {
        agg: &'a RoaAggregateKey,
        removed: &'a RevokedObject,
    }

    pub fn serialize<S>(map: &HashMap<RoaAggregateKey, RevokedObject>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sorted_vec: Vec<ItemRef> = map.iter().map(|(agg, removed)| ItemRef { agg, removed }).collect();
        sorted_vec.sort_by_key(|el| el.agg);

        serializer.collect_seq(sorted_vec)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<RoaAggregateKey, RevokedObject>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut map = HashMap::new();
        for item in Vec::<Item>::deserialize(deserializer)? {
            map.insert(item.agg, item.removed);
        }
        Ok(map)
    }
}

impl Default for RoaUpdates {
    fn default() -> Self {
        RoaUpdates {
            updated: HashMap::new(),
            removed: HashMap::new(),
            aggregate_updated: HashMap::new(),
            aggregate_removed: HashMap::new(),
        }
    }
}

impl RoaUpdates {
    pub fn is_empty(&self) -> bool {
        self.updated.is_empty()
            && self.removed.is_empty()
            && self.aggregate_updated.is_empty()
            && self.aggregate_removed.is_empty()
    }

    pub fn contains_changes(&self) -> bool {
        !self.is_empty()
    }

    pub fn update(&mut self, auth: RouteAuthorization, roa: RoaInfo) {
        self.updated.insert(auth, roa);
    }

    pub fn remove(&mut self, auth: RouteAuthorization, revoke: RevokedObject) {
        self.removed.insert(auth, revoke);
    }

    pub fn remove_aggregate(&mut self, key: RoaAggregateKey, revoke: RevokedObject) {
        self.aggregate_removed.insert(key, revoke);
    }

    pub fn update_aggregate(&mut self, key: RoaAggregateKey, aggregate: AggregateRoaInfo) {
        self.aggregate_updated.insert(key, aggregate);
    }

    pub fn added_roas(&self) -> KrillResult<HashMap<ObjectName, PublishedRoa>> {
        let mut res = HashMap::new();

        for (auth, simple) in &self.updated {
            let roa = simple.roa().clone();
            let name = ObjectName::from(auth);

            res.insert(name, PublishedRoa::new(roa));
        }

        for (agg_key, agg_info) in &self.aggregate_updated {
            let roa = agg_info.roa_info().roa().clone();
            let name = ObjectName::from(agg_key);

            res.insert(name, PublishedRoa::new(roa));
        }

        Ok(res)
    }

    pub fn removed_roas(&self) -> Vec<ObjectName> {
        let mut res = vec![];

        for simple in self.removed.keys() {
            res.push(ObjectName::from(simple))
        }

        for agg in self.aggregate_removed.keys() {
            res.push(ObjectName::from(agg))
        }

        res
    }

    #[allow(clippy::type_complexity)]
    pub fn unpack(
        self,
    ) -> (
        HashMap<RouteAuthorization, RoaInfo>,
        HashMap<RouteAuthorization, RevokedObject>,
        HashMap<RoaAggregateKey, AggregateRoaInfo>,
        HashMap<RoaAggregateKey, RevokedObject>,
    ) {
        (
            self.updated,
            self.removed,
            self.aggregate_updated,
            self.aggregate_removed,
        )
    }
}

impl fmt::Display for RoaUpdates {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if !self.updated.is_empty() {
            write!(f, "Added single VRP ROAs: ")?;
            for roa in self.updated.keys() {
                write!(f, "{} ", ObjectName::from(roa))?;
            }
        }
        if !self.removed.is_empty() {
            write!(f, "Removed single VRP ROAs: ")?;
            for roa in self.removed.keys() {
                write!(f, "{} ", ObjectName::from(roa))?;
            }
        }
        if !self.aggregate_updated.is_empty() {
            write!(f, "Added ASN aggregated ROAs: ")?;
            for roa in self.aggregate_updated.keys() {
                write!(f, "{} ", ObjectName::from(roa))?;
            }
        }
        if !self.aggregate_removed.is_empty() {
            write!(f, "Removed ASN aggregated ROAs: ")?;
            for roa in self.aggregate_removed.keys() {
                write!(f, "{} ", ObjectName::from(roa))?;
            }
        }
        Ok(())
    }
}

//------------ ChildCertificateUpdates -------------------------------------

/// Describes an update to the set of ROAs under a ResourceClass.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct ChildCertificateUpdates {
    issued: Vec<IssuedCert>,
    removed: Vec<KeyIdentifier>,
}

impl ChildCertificateUpdates {
    pub fn new(issued: Vec<IssuedCert>, removed: Vec<KeyIdentifier>) -> Self {
        ChildCertificateUpdates { issued, removed }
    }

    pub fn is_empty(&self) -> bool {
        self.issued.is_empty() && self.removed.is_empty()
    }
    pub fn issue(&mut self, new: IssuedCert) {
        self.issued.push(new);
    }
    pub fn remove(&mut self, ki: KeyIdentifier) {
        self.removed.push(ki);
    }

    pub fn issued(&self) -> &Vec<IssuedCert> {
        &self.issued
    }
    pub fn removed(&self) -> &Vec<KeyIdentifier> {
        &self.removed
    }
    pub fn unpack(self) -> (Vec<IssuedCert>, Vec<KeyIdentifier>) {
        (self.issued, self.removed)
    }
}

//------------ Evt ---------------------------------------------------------

pub type CaEvt = StoredEvent<CaEvtDet>;

//------------ EvtDet -------------------------------------------------------

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[allow(clippy::large_enum_variant)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "type")]
pub enum CaEvtDet {
    // Being a Trust Anchor
    TrustAnchorMade {
        ta_cert_details: TaCertDetails,
    },

    // Being a parent Events
    ChildAdded {
        child: ChildHandle,
        id_cert: IdCert,
        resources: ResourceSet,
    },
    ChildCertificateIssued {
        child: ChildHandle,
        resource_class_name: ResourceClassName,
        ki: KeyIdentifier,
    },
    ChildKeyRevoked {
        child: ChildHandle,
        resource_class_name: ResourceClassName,
        ki: KeyIdentifier,
    },
    ChildCertificatesUpdated {
        resource_class_name: ResourceClassName,
        updates: ChildCertificateUpdates,
    },
    ChildUpdatedIdCert {
        child: ChildHandle,
        id_cert: IdCert,
    },
    ChildUpdatedResources {
        child: ChildHandle,
        resources: ResourceSet,
    },
    ChildRemoved {
        child: ChildHandle,
    },

    // Being a child Events
    IdUpdated {
        id: Rfc8183Id,
    },
    ParentAdded {
        parent: ParentHandle,
        contact: ParentCaContact,
    },
    ParentUpdated {
        parent: ParentHandle,
        contact: ParentCaContact,
    },
    ParentRemoved {
        parent: ParentHandle,
    },
    ResourceClassAdded {
        resource_class_name: ResourceClassName,
        parent: ParentHandle,
        parent_resource_class_name: ParentResourceClassName,
        pending_key: KeyIdentifier,
    },
    ResourceClassRemoved {
        resource_class_name: ResourceClassName,
        parent: ParentHandle,
        revoke_requests: Vec<RevocationRequest>,
    },
    CertificateRequested {
        resource_class_name: ResourceClassName,
        req: IssuanceRequest,
        ki: KeyIdentifier, // Also contained in request. Drop?
    },
    CertificateReceived {
        resource_class_name: ResourceClassName,
        rcvd_cert: RcvdCert,
        ki: KeyIdentifier, // Also in received cert. Drop?
    },

    // Key life cycle
    KeyRollPendingKeyAdded {
        // A pending key is added to an existing resource class in order to initiate
        // a key roll. Note that there will be a separate 'CertificateRequested' event for
        // this key.
        resource_class_name: ResourceClassName,
        pending_key_id: KeyIdentifier,
    },
    KeyPendingToNew {
        // A pending key is marked as 'new' when it has received its (first) certificate.
        // This means that the key is staged and a mft and crl will be published. According
        // to RFC 6489 this key should be staged for 24 hours before it is promoted to
        // become the active key. However, in practice this time can be shortened.
        resource_class_name: ResourceClassName,
        new_key: CertifiedKey, // pending key which received a certificate becomes 'new', i.e. it is staged.
    },
    KeyPendingToActive {
        // When a new resource class is created it will have a single pending key only which
        // is promoted to become the active (current) key for the resource class immediately
        // after receiving its first certificate. Technically this is not a roll, but a simple
        // first activation.
        resource_class_name: ResourceClassName,
        current_key: CertifiedKey, // there was no current key, pending becomes active without staging when cert is received.
    },
    KeyRollActivated {
        // When a 'new' key is activated (becomes current), the previous current key will be
        // marked as old and we will request its revocation. Note that any current ROAs and/or
        // delegated certificates will also be re-issued under the new 'current' key. These changes
        // are tracked in separate `RoasUpdated` and `ChildCertificatesUpdated` events.
        resource_class_name: ResourceClassName,
        revoke_req: RevocationRequest,
    },
    KeyRollFinished {
        // The key roll is finished when the parent confirms that the old key is revoked.
        // We can remove it and stop publishing its mft and crl.
        resource_class_name: ResourceClassName,
    },
    UnexpectedKeyFound {
        // This event is generated in case our parent reports keys to us that we do not
        // believe we have. This should not happen in practice, but this is tracked so that
        // we can recover from this situation. We can request revocation for all these keys
        // and create new keys in the RC as needed.
        resource_class_name: ResourceClassName,
        revoke_req: RevocationRequest,
    },

    // Route Authorizations
    RouteAuthorizationAdded {
        // Tracks a single authorization (VRP) which is added. Note that (1) a command to
        // update ROAs can contain multiple changes in which case multiple events will
        // result, and (2) we do not have a 'modify' event. Modifications of e.g. the
        // max length are expressed as a 'removed' and 'added' event in a single transaction.
        auth: RouteAuthorization,
    },
    RouteAuthorizationRemoved {
        // Tracks a single authorization (VRP) which is removed. See remark for RouteAuthorizationAdded.
        auth: RouteAuthorization,
    },
    RoasUpdated {
        // Tracks ROA *objects* which are (re-)issued in a resource class.
        resource_class_name: ResourceClassName,
        updates: RoaUpdates,
    },

    // Publishing
    RepoUpdated {
        // Adds the repository contact for this CA so that publication can commence,
        // and certificates can be requested from parents. Note: the CA can only start
        // requesting certificates when it knows which URIs it can use.
        contact: RepositoryContact,
    },

    // Rta
    //
    // NOTE RTA support is still experimental and incomplete.
    RtaSigned {
        // Adds a signed RTA. The RTA can be single signed, or it can
        // be a multi-signed RTA based on an existing 'PreparedRta'.
        name: RtaName,
        rta: SignedRta,
    },
    RtaPrepared {
        // Adds a 'prepared' RTA. I.e. the context of keys which need to be included
        // in a multi-signed RTA.
        name: RtaName,
        prepared: PreparedRta,
    },
}

impl CaEvtDet {
    /// This marks the RFC8183Id as updated
    pub(super) fn id_updated(handle: &Handle, version: u64, id: Rfc8183Id) -> CaEvt {
        StoredEvent::new(handle, version, CaEvtDet::IdUpdated { id })
    }

    /// This marks a parent as added to the CA.
    pub(super) fn parent_added(handle: &Handle, version: u64, parent: ParentHandle, contact: ParentCaContact) -> CaEvt {
        StoredEvent::new(handle, version, CaEvtDet::ParentAdded { parent, contact })
    }

    /// This marks a parent contact as updated
    pub(super) fn parent_updated(
        handle: &Handle,
        version: u64,
        parent: ParentHandle,
        contact: ParentCaContact,
    ) -> CaEvt {
        StoredEvent::new(handle, version, CaEvtDet::ParentUpdated { parent, contact })
    }

    pub(super) fn child_added(
        handle: &Handle,
        version: u64,
        child: ChildHandle,
        id_cert: IdCert,
        resources: ResourceSet,
    ) -> CaEvt {
        StoredEvent::new(
            handle,
            version,
            CaEvtDet::ChildAdded {
                child,
                id_cert,
                resources,
            },
        )
    }

    pub(super) fn child_updated_cert(handle: &Handle, version: u64, child: ChildHandle, id_cert: IdCert) -> CaEvt {
        StoredEvent::new(handle, version, CaEvtDet::ChildUpdatedIdCert { child, id_cert })
    }

    pub(super) fn child_updated_resources(
        handle: &Handle,
        version: u64,
        child: ChildHandle,
        resources: ResourceSet,
    ) -> CaEvt {
        StoredEvent::new(handle, version, CaEvtDet::ChildUpdatedResources { child, resources })
    }

    pub(super) fn child_certificate_issued(
        handle: &Handle,
        version: u64,
        child: ChildHandle,
        resource_class_name: ResourceClassName,
        ki: KeyIdentifier,
    ) -> CaEvt {
        StoredEvent::new(
            handle,
            version,
            CaEvtDet::ChildCertificateIssued {
                child,
                resource_class_name,
                ki,
            },
        )
    }

    pub(super) fn child_revoke_key(
        handle: &Handle,
        version: u64,
        child: ChildHandle,
        resource_class_name: ResourceClassName,
        ki: KeyIdentifier,
    ) -> CaEvt {
        StoredEvent::new(
            handle,
            version,
            CaEvtDet::ChildKeyRevoked {
                child,
                resource_class_name,
                ki,
            },
        )
    }

    pub(super) fn child_certificates_updated(
        handle: &Handle,
        version: u64,
        resource_class_name: ResourceClassName,
        updates: ChildCertificateUpdates,
    ) -> CaEvt {
        StoredEvent::new(
            handle,
            version,
            CaEvtDet::ChildCertificatesUpdated {
                resource_class_name,
                updates,
            },
        )
    }

    pub(super) fn child_removed(handle: &Handle, version: u64, child: ChildHandle) -> CaEvt {
        StoredEvent::new(handle, version, CaEvtDet::ChildRemoved { child })
    }
}

impl fmt::Display for CaEvtDet {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            // Being a Trust Anchor
            CaEvtDet::TrustAnchorMade { ta_cert_details } => write!(
                f,
                "turn into TA with key (hash) {}",
                ta_cert_details.cert().subject_key_identifier()
            ),

            // Being a parent Events
            CaEvtDet::ChildAdded {
                child,
                id_cert,
                resources,
            } => {
                write!(
                    f,
                    "added child '{}' with resources '{}, id (hash): {}",
                    child,
                    resources,
                    id_cert.ski_hex()
                )
            }
            CaEvtDet::ChildCertificateIssued {
                child,
                resource_class_name,
                ki,
            } => write!(
                f,
                "issued certificate to child '{}' for class '{}' and pub key '{}'",
                child, resource_class_name, ki
            ),
            CaEvtDet::ChildCertificatesUpdated {
                resource_class_name,
                updates,
            } => {
                write!(
                    f,
                    "updated child certificates in resource class {}",
                    resource_class_name
                )?;
                let issued = updates.issued();
                if !issued.is_empty() {
                    write!(f, " (re-)issued keys: ")?;
                    for iss in issued {
                        write!(f, " {}", iss.subject_key_identifier())?;
                    }
                }
                let revoked = updates.removed();
                if !revoked.is_empty() {
                    write!(f, " revoked keys: ")?;
                    for rev in revoked {
                        write!(f, " {}", rev)?;
                    }
                }
                Ok(())
            }
            CaEvtDet::ChildKeyRevoked {
                child,
                resource_class_name,
                ki,
            } => write!(
                f,
                "revoked certificate for child '{}' in resource class '{}' with key(hash) '{}'",
                child, resource_class_name, ki
            ),
            CaEvtDet::ChildUpdatedIdCert { child, id_cert } => {
                write!(f, "updated child '{}' id (hash) '{}'", child, id_cert.ski_hex())
            }
            CaEvtDet::ChildUpdatedResources { child, resources } => {
                write!(f, "updated child '{}' resources to '{}'", child, resources)
            }
            CaEvtDet::ChildRemoved { child } => write!(f, "removed child '{}'", child),

            // Being a child Events
            CaEvtDet::IdUpdated { id } => write!(f, "updated RFC8183 id to key '{}'", id.key_hash()),
            CaEvtDet::ParentAdded { parent, contact } => {
                let contact_str = match contact {
                    ParentCaContact::Ta(_) => "TA proxy",
                    ParentCaContact::Rfc6492(_) => "RFC6492",
                };
                write!(f, "added {} parent '{}' ", contact_str, parent)
            }
            CaEvtDet::ParentUpdated { parent, contact } => {
                let contact_str = match contact {
                    ParentCaContact::Ta(_) => "TA proxy",
                    ParentCaContact::Rfc6492(_) => "RFC6492",
                };
                write!(f, "updated parent '{}' contact to '{}' ", parent, contact_str)
            }
            CaEvtDet::ParentRemoved { parent } => write!(f, "removed parent '{}'", parent),

            CaEvtDet::ResourceClassAdded {
                resource_class_name, ..
            } => write!(f, "added resource class with name '{}'", resource_class_name),
            CaEvtDet::ResourceClassRemoved {
                resource_class_name,
                parent,
                ..
            } => write!(
                f,
                "removed resource class with name '{}' under parent '{}'",
                resource_class_name, parent
            ),
            CaEvtDet::CertificateRequested {
                resource_class_name,
                ki,
                ..
            } => write!(
                f,
                "requested certificate for key (hash) '{}' under resource class '{}'",
                ki, resource_class_name
            ),
            CaEvtDet::CertificateReceived {
                resource_class_name,
                ki,
                ..
            } => write!(
                f,
                "received certificate for key (hash) '{}' under resource class '{}'",
                ki, resource_class_name
            ),

            // Key life cycle
            CaEvtDet::KeyRollPendingKeyAdded {
                resource_class_name,
                pending_key_id,
            } => {
                write!(
                    f,
                    "key roll: added pending key '{}' under resource class '{}'",
                    pending_key_id, resource_class_name
                )
            }
            CaEvtDet::KeyPendingToNew {
                resource_class_name,
                new_key,
            } => write!(
                f,
                "key roll: moving pending key '{}' to new state under resource class '{}'",
                new_key.key_id(),
                resource_class_name
            ),
            CaEvtDet::KeyPendingToActive {
                resource_class_name,
                current_key,
            } => write!(
                f,
                "activating pending key '{}' under resource class '{}'",
                current_key.key_id(),
                resource_class_name
            ),
            CaEvtDet::KeyRollActivated {
                resource_class_name,
                revoke_req,
            } => write!(
                f,
                "key roll: activated new key, requested revocation of '{}' under resource class '{}'",
                revoke_req.key(),
                resource_class_name
            ),
            CaEvtDet::KeyRollFinished { resource_class_name } => {
                write!(f, "key roll: finished for resource class '{}'", resource_class_name)
            }
            CaEvtDet::UnexpectedKeyFound {
                resource_class_name,
                revoke_req,
            } => write!(
                f,
                "Found unexpected key in resource class '{}', will try to revoke key id: '{}'",
                resource_class_name,
                revoke_req.key()
            ),

            // Route Authorizations
            CaEvtDet::RouteAuthorizationAdded { auth } => write!(f, "added ROA: '{}'", auth),
            CaEvtDet::RouteAuthorizationRemoved { auth } => write!(f, "removed ROA: '{}'", auth),
            CaEvtDet::RoasUpdated {
                resource_class_name,
                updates,
            } => {
                write!(f, "updated ROAs under resource class '{}'", resource_class_name)?;
                if !updates.updated.is_empty() {
                    write!(f, " added: ")?;
                    for auth in updates.updated.keys() {
                        write!(f, "{} ", auth)?;
                    }
                }
                if !updates.removed.is_empty() {
                    write!(f, " removed: ")?;
                    for auth in updates.removed.keys() {
                        write!(f, "{} ", auth)?;
                    }
                }
                Ok(())
            }

            // Publishing
            CaEvtDet::RepoUpdated { contact } => {
                write!(f, "updated repository to remote server: {}", contact.service_uri())
            }

            // Rta
            CaEvtDet::RtaPrepared { name, prepared } => {
                write!(f, "Prepared RTA '{}' for resources: {}", name, prepared.resources())
            }
            CaEvtDet::RtaSigned { name, rta } => {
                write!(f, "Signed RTA '{}' for resources: {}", name, rta.resources())
            }
        }
    }
}