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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
use std::convert::TryFrom;
use std::ops::Deref;
use std::sync::Arc;
use std::{collections::HashMap, vec};

use bytes::Bytes;
use chrono::Duration;

use rpki::{
    cert::{Cert, KeyUsage, Overclaim, TbsCert},
    crypto::{KeyIdentifier, PublicKey},
    rta::RtaBuilder,
    uri,
    x509::{Serial, Time, Validity},
};

use crate::{
    commons::{
        api::{
            self, CertAuthInfo, ChildHandle, EntitlementClass, Entitlements, Handle, IdCertPem, IssuanceRequest,
            IssuedCert, ObjectName, ParentCaContact, ParentHandle, RcvdCert, RepoInfo, RepositoryContact,
            RequestResourceLimit, ResourceClassName, ResourceSet, Revocation, RevocationRequest, RevocationResponse,
            RoaDefinition, RtaList, RtaName, RtaPrepResponse, SigningCert, StorableCaCommand, TaCertDetails,
            TrustAnchorLocator,
        },
        crypto::{CsrInfo, IdCert, IdCertBuilder, KrillSigner, ProtocolCms, ProtocolCmsBuilder},
        error::{Error, RoaDeltaError},
        eventsourcing::{Aggregate, StoredEvent},
        remote::{rfc6492, rfc8183},
        KrillResult,
    },
    constants::test_mode_enabled,
    daemon::{
        ca::{
            events::ChildCertificateUpdates, ta_handle, CaEvt, CaEvtDet, ChildDetails, Cmd, CmdDet, Ini, PreparedRta,
            ResourceClass, ResourceTaggedAttestation, RouteAuthorization, RouteAuthorizationUpdates, Routes,
            RtaContentRequest, RtaPrepareRequest, Rtas, SignedRta,
        },
        config::{Config, IssuanceTimingConfig},
    },
};

//------------ Rfc8183Id ---------------------------------------------------

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

impl Rfc8183Id {
    pub fn new(cert: IdCert) -> Self {
        Rfc8183Id { cert }
    }

    pub fn generate(signer: &KrillSigner) -> KrillResult<Self> {
        let key = signer.create_key()?;
        let cert =
            IdCertBuilder::new_ta_id_cert(&key, signer.deref()).map_err(|e| Error::SignerError(e.to_string()))?;
        Ok(Rfc8183Id { cert })
    }
}

impl Rfc8183Id {
    pub fn key_hash(&self) -> String {
        self.cert.ski_hex()
    }

    pub fn key_id(&self) -> KeyIdentifier {
        self.cert.subject_public_key_info().key_identifier()
    }
}

//------------ CertAuthStatus ----------------------------------------------
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
enum CertAuthStatus {
    Active,
    Deactivated,
}

impl Default for CertAuthStatus {
    fn default() -> Self {
        CertAuthStatus::Active
    }
}

//------------ CertAuth ----------------------------------------------------

/// This type defines a Certification Authority at a slightly higher level
/// than one might expect.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CertAuth {
    handle: Handle,
    version: u64,

    id: Rfc8183Id, // Used for RFC 6492 (up-down) and RFC 8181 (publication)

    repository: Option<RepositoryContact>,
    parents: HashMap<ParentHandle, ParentCaContact>,

    next_class_name: u32,
    resources: HashMap<ResourceClassName, ResourceClass>,

    children: HashMap<ChildHandle, ChildDetails>,
    routes: Routes,

    #[serde(skip_serializing_if = "Rtas::is_empty", default = "Rtas::default")]
    rtas: Rtas,

    #[serde(skip_serializing, default = "CertAuthStatus::default")]
    status: CertAuthStatus,
}

impl Aggregate for CertAuth {
    type Command = Cmd;
    type StorableCommandDetails = StorableCaCommand;
    type Event = CaEvt;
    type InitEvent = Ini;
    type Error = Error;

    fn init(event: Ini) -> KrillResult<Self> {
        let (handle, _version, details) = event.unpack();
        let id = details.unpack();

        let parents = HashMap::new();
        let resources = HashMap::new();
        let next_class_name = 0;
        let children = HashMap::new();
        let routes = Routes::default();
        let rtas = Rtas::default();
        let repository = None;

        Ok(CertAuth {
            handle,
            version: 1,

            id,

            repository,
            parents,

            next_class_name,
            resources,

            children,

            routes,
            rtas,
            status: CertAuthStatus::Active,
        })
    }

    fn version(&self) -> u64 {
        self.version
    }

    fn apply(&mut self, event: CaEvt) {
        self.version += 1;
        match event.into_details() {
            //-----------------------------------------------------------------------
            // Being a trust anchor
            //-----------------------------------------------------------------------
            CaEvtDet::TrustAnchorMade { ta_cert_details } => {
                let key_id = ta_cert_details.cert().subject_key_identifier();
                self.parents.insert(ta_handle(), ParentCaContact::Ta(ta_cert_details));
                let rcn = ResourceClassName::from(self.next_class_name);
                self.next_class_name += 1;
                self.resources.insert(rcn.clone(), ResourceClass::for_ta(rcn, key_id));
            }

            //-----------------------------------------------------------------------
            // Being a parent
            //-----------------------------------------------------------------------
            CaEvtDet::ChildAdded {
                child,
                id_cert,
                resources,
            } => {
                let details = ChildDetails::new(id_cert, resources);
                self.children.insert(child, details);
            }
            CaEvtDet::ChildCertificateIssued {
                child,
                resource_class_name,
                ki,
            } => {
                self.children
                    .get_mut(&child)
                    .unwrap()
                    .add_issue_response(resource_class_name, ki);
            }

            CaEvtDet::ChildKeyRevoked {
                child,
                resource_class_name,
                ki,
            } => {
                self.resources.get_mut(&resource_class_name).unwrap().key_revoked(&ki);
                self.children.get_mut(&child).unwrap().add_revoke_response(ki);
            }

            CaEvtDet::ChildCertificatesUpdated {
                resource_class_name,
                updates,
            } => {
                let rc = self.resources.get_mut(&resource_class_name).unwrap();
                let (issued, removed) = updates.unpack();
                for iss in issued {
                    rc.certificate_issued(iss)
                }
                for rem in removed {
                    rc.key_revoked(&rem);

                    // This loop is inefficient, but certificate revocations are not that common, so it's
                    // not a big deal. Tracking this better would require that track the child handle somehow.
                    // That is a bit hard when this revocation is the result from a republish where we lost
                    // all resources delegated to the child.
                    for child in self.children.values_mut() {
                        if child.is_issued(&rem) {
                            child.add_revoke_response(rem)
                        }
                    }
                }
            }

            CaEvtDet::ChildUpdatedIdCert { child, id_cert } => {
                self.children.get_mut(&child).unwrap().set_id_cert(id_cert)
            }

            CaEvtDet::ChildUpdatedResources { child, resources } => {
                self.children.get_mut(&child).unwrap().set_resources(resources)
            }

            CaEvtDet::ChildRemoved { child } => {
                self.children.remove(&child);
            }

            //-----------------------------------------------------------------------
            // Being a child
            //-----------------------------------------------------------------------
            CaEvtDet::IdUpdated { id } => {
                self.id = id;
            }
            CaEvtDet::ParentAdded { parent, contact } => {
                self.parents.insert(parent, contact);
            }
            CaEvtDet::ParentUpdated { parent, contact } => {
                self.parents.insert(parent, contact);
            }
            CaEvtDet::ParentRemoved { parent } => {
                self.parents.remove(&parent);
                self.resources.retain(|_, rc| rc.parent_handle() != &parent);
            }

            CaEvtDet::ResourceClassAdded {
                resource_class_name,
                parent,
                parent_resource_class_name,
                pending_key,
            } => {
                self.next_class_name += 1;
                let ns = resource_class_name.to_string();
                let rc = ResourceClass::create(
                    resource_class_name.clone(),
                    ns,
                    parent,
                    parent_resource_class_name,
                    pending_key,
                );
                self.resources.insert(resource_class_name, rc);
            }
            CaEvtDet::ResourceClassRemoved {
                resource_class_name, ..
            } => {
                self.resources.remove(&resource_class_name);
            }
            CaEvtDet::CertificateRequested {
                resource_class_name,
                req,
                ki,
            } => {
                self.resources
                    .get_mut(&resource_class_name)
                    .unwrap()
                    .add_request(ki, req);
            }
            CaEvtDet::CertificateReceived {
                resource_class_name,
                ki,
                rcvd_cert,
            } => {
                self.resources
                    .get_mut(&resource_class_name)
                    .unwrap()
                    .received_cert(ki, rcvd_cert);
            }

            //-----------------------------------------------------------------------
            // Key Life Cycle
            //-----------------------------------------------------------------------
            CaEvtDet::KeyRollPendingKeyAdded {
                resource_class_name,
                pending_key_id: pending_key,
            } => {
                self.resources
                    .get_mut(&resource_class_name)
                    .unwrap()
                    .pending_key_id_added(pending_key);
            }
            CaEvtDet::KeyPendingToNew {
                resource_class_name,
                new_key,
            } => {
                self.resources
                    .get_mut(&resource_class_name)
                    .unwrap()
                    .pending_key_to_new(new_key);
            }
            CaEvtDet::KeyPendingToActive {
                resource_class_name,
                current_key,
            } => {
                self.resources
                    .get_mut(&resource_class_name)
                    .unwrap()
                    .pending_key_to_active(current_key);
            }
            CaEvtDet::KeyRollActivated {
                resource_class_name,
                revoke_req,
            } => {
                self.resources
                    .get_mut(&resource_class_name)
                    .unwrap()
                    .new_key_activated(revoke_req);
            }
            CaEvtDet::KeyRollFinished { resource_class_name } => {
                self.resources.get_mut(&resource_class_name).unwrap().old_key_removed();
            }
            CaEvtDet::UnexpectedKeyFound { .. } => {
                // no action needed, this is marked to flag that a key may be removed on the
                // server side. The revocation requests are picked up by the `MessageQueue`
                // listener.
            }

            //-----------------------------------------------------------------------
            // Route Authorizations
            //-----------------------------------------------------------------------
            CaEvtDet::RouteAuthorizationAdded { auth } => self.routes.add(auth),
            CaEvtDet::RouteAuthorizationRemoved { auth } => {
                self.routes.remove(&auth);
            }
            CaEvtDet::RoasUpdated {
                resource_class_name,
                updates,
            } => self
                .resources
                .get_mut(&resource_class_name)
                .unwrap()
                .roas_updated(updates),

            //-----------------------------------------------------------------------
            // Publication
            //-----------------------------------------------------------------------
            CaEvtDet::RepoUpdated { contact } => {
                if let Some(current) = &self.repository {
                    for rc in self.resources.values_mut() {
                        rc.set_old_repo(current.repo_info());
                    }
                }
                self.repository = Some(contact);
            }

            //-----------------------------------------------------------------------
            // Resource Tagged Attestations
            //-----------------------------------------------------------------------
            CaEvtDet::RtaPrepared { name, prepared } => {
                self.rtas.add_prepared(name, prepared);
            }
            CaEvtDet::RtaSigned { name, rta } => {
                self.rtas.add_signed(name, rta);
            }
        }
    }

    fn process_command(&self, command: Cmd) -> KrillResult<Vec<CaEvt>> {
        if log_enabled!(log::Level::Trace) {
            trace!(
                "Sending command to CA '{}', version: {}: {}",
                self.handle,
                self.version,
                command
            );
        }

        match command.into_details() {
            // trust anchor
            CmdDet::MakeTrustAnchor(uris, signer) => self.trust_anchor_make(uris, signer),

            // being a parent
            CmdDet::ChildAdd(child, id_cert, resources) => self.child_add(child, id_cert, resources),
            CmdDet::ChildUpdateResources(child, res) => self.child_update_resources(&child, res),
            CmdDet::ChildUpdateId(child, id) => self.child_update_id(&child, id),
            CmdDet::ChildCertify(child, request, config, signer) => self.child_certify(child, request, &config, signer),
            CmdDet::ChildRevokeKey(child, request) => self.child_revoke_key(child, request),
            CmdDet::ChildRemove(child) => self.child_remove(&child),

            // being a child
            CmdDet::GenerateNewIdKey(signer) => self.generate_new_id_key(signer),
            CmdDet::AddParent(parent, info) => self.add_parent(parent, info),
            CmdDet::UpdateParentContact(parent, info) => self.update_parent(parent, info),
            CmdDet::RemoveParent(parent) => self.remove_parent(parent),

            CmdDet::UpdateEntitlements(parent, entitlements, signer) => {
                self.update_entitlements(parent, entitlements, signer)
            }
            CmdDet::UpdateRcvdCert(class_name, rcvd_cert, config, signer) => {
                self.update_received_cert(class_name, rcvd_cert, &config, signer)
            }

            // Key rolls
            CmdDet::KeyRollInitiate(duration, signer) => self.keyroll_initiate(duration, signer),
            CmdDet::KeyRollActivate(duration, config, signer) => self.keyroll_activate(duration, config, signer),
            CmdDet::KeyRollFinish(rcn, response) => self.keyroll_finish(rcn, response),

            // Route Authorizations
            CmdDet::RouteAuthorizationsUpdate(updates, config, signer) => {
                self.route_authorizations_update(updates, &config, signer)
            }
            CmdDet::RouteAuthorizationsRenew(config, signer) => self.route_authorizations_renew(&config, &signer),

            // Republish
            CmdDet::RepoUpdate(contact, signer) => self.update_repo(contact, &signer),

            // Resource Tagged Attestations
            CmdDet::RtaMultiPrepare(name, request, signer) => self.rta_multi_prep(name, request, signer.deref()),
            CmdDet::RtaCoSign(name, rta, signer) => self.rta_cosign(name, rta, signer.deref()),
            CmdDet::RtaSign(name, request, signer) => self.rta_sign(name, request, signer.deref()),
        }
    }
}

/// # Data presentation
///
impl CertAuth {
    // For many commands with multiple resulting events, it's easier to build a list of event *details*
    // and worry about numbering the versions here.
    fn events_from_details(&self, event_details: Vec<CaEvtDet>) -> Vec<CaEvt> {
        let mut res = vec![];
        let mut version = self.version;
        for event in event_details {
            res.push(StoredEvent::new(&self.handle, version, event));
            version += 1;
        }
        res
    }
}

/// # Data presentation
///
impl CertAuth {
    /// Returns a `CertAuthInfo` for this, which includes a data representation
    /// of the internal structure, in particular with regards to parent, children,
    /// resource classes and keys.
    pub fn as_ca_info(&self) -> CertAuthInfo {
        let handle = self.handle.clone();
        let repo_info = self.repository.as_ref().map(|repo| repo.repo_info().clone());

        let parents = self.parents.clone();

        let mut resources = HashMap::new();

        for (name, rc) in &self.resources {
            resources.insert(name.clone(), rc.as_info());
        }
        let children: Vec<ChildHandle> = self.children.keys().cloned().collect();

        let id_cert_pem = IdCertPem::from(&self.id.cert);

        CertAuthInfo::new(handle, id_cert_pem, repo_info, parents, resources, children)
    }

    /// Returns the current RoaDefinitions for this, i.e. the intended authorized
    /// prefixes. Provided that the resources are held by this `CertAuth` one can
    /// expect that corresponding ROA **objects** are created by the system.
    pub fn roa_definitions(&self) -> Vec<RoaDefinition> {
        self.routes.authorizations().map(|a| a.as_ref()).cloned().collect()
    }

    /// Returns an RFC 8183 Child Request - which can be represented as XML to a
    /// parent of this `CertAuth`
    pub fn child_request(&self) -> rfc8183::ChildRequest {
        rfc8183::ChildRequest::new(self.handle.clone(), self.id.cert.clone())
    }

    /// Returns an RFC 8183 Publisher Request - which can be represented as XML to a
    /// repository for this `CertAuth`
    pub fn publisher_request(&self) -> rfc8183::PublisherRequest {
        rfc8183::PublisherRequest::new(None, self.handle.clone(), self.id_cert().clone())
    }

    pub fn id_cert(&self) -> &IdCert {
        &self.id.cert
    }

    pub fn id_key(&self) -> KeyIdentifier {
        self.id.cert.subject_public_key_info().key_identifier()
    }
    pub fn handle(&self) -> &Handle {
        &self.handle
    }

    /// Returns the complete set of all currently received resources, under all parents, for
    /// this `CertAuth`
    pub fn all_resources(&self) -> ResourceSet {
        let mut resources = ResourceSet::default();
        for rc in self.resources.values() {
            if let Some(rc_resources) = rc.current_resources() {
                resources = resources.union(rc_resources);
            }
        }
        resources
    }
}

/// # Publishing
///
impl CertAuth {
    pub fn repository_contact(&self) -> KrillResult<&RepositoryContact> {
        self.repository.as_ref().ok_or(Error::RepoNotSet)
    }

    pub fn repository_info(&self) -> KrillResult<&RepoInfo> {
        self.repository_contact().map(|contact| contact.repo_info())
    }
}

/// # Being a Trust Anchor
///
impl CertAuth {
    fn trust_anchor_make(&self, uris: Vec<uri::Https>, signer: Arc<KrillSigner>) -> KrillResult<Vec<CaEvt>> {
        if !self.resources.is_empty() {
            return Err(Error::custom("Cannot turn CA with resources into TA"));
        }

        let repo_info = self.repository_contact()?.repo_info();

        let key = signer.create_key()?;

        let resources = ResourceSet::all_resources();

        let cert = {
            let serial: Serial = signer.random_serial()?;

            let pub_key = signer.get_key_info(&key).map_err(Error::signer)?;
            let name = pub_key.to_subject_name();

            let mut cert = TbsCert::new(
                serial,
                name.clone(),
                Validity::new(Time::five_minutes_ago(), Time::years_from_now(100)),
                Some(name),
                pub_key.clone(),
                KeyUsage::Ca,
                Overclaim::Refuse,
            );

            cert.set_basic_ca(Some(true));

            let ns = ResourceClassName::default().to_string();

            cert.set_ca_repository(Some(repo_info.ca_repository(&ns)));
            cert.set_rpki_manifest(Some(repo_info.rpki_manifest(&ns, &pub_key.key_identifier())));
            cert.set_rpki_notify(Some(repo_info.rpki_notify()));

            cert.set_as_resources(resources.to_as_resources());
            cert.set_v4_resources(resources.to_ip_resources_v4());
            cert.set_v6_resources(resources.to_ip_resources_v6());

            signer.sign_cert(cert, &key)?
        };

        let tal = TrustAnchorLocator::new(uris, &cert);

        let ta_cert_details = TaCertDetails::new(cert, resources, tal);

        info!("Created Trust Anchor");

        Ok(vec![StoredEvent::new(
            &self.handle,
            self.version,
            CaEvtDet::TrustAnchorMade { ta_cert_details },
        )])
    }
}

/// # Being a parent
///
impl CertAuth {
    pub fn verify_rfc6492(&self, msg: ProtocolCms) -> KrillResult<rfc6492::Message> {
        let content = rfc6492::Message::from_signed_message(&msg)?;

        let child_handle = content.sender();
        let child = self.get_child(child_handle)?;

        msg.validate(child.id_cert())
            .map_err(|_| Error::Rfc6492SignatureInvalid)?;

        Ok(content)
    }

    pub fn sign_rfc6492_response(&self, msg: rfc6492::Message, signer: &KrillSigner) -> KrillResult<Bytes> {
        let key = &self.id.key_id();
        Ok(ProtocolCmsBuilder::create(key, signer, msg.into_bytes())
            .map_err(Error::signer)?
            .as_bytes())
    }

    /// List entitlements (section 3.3.2 of RFC6492). Return an error if
    /// the child is not authorized -- or unknown etc.
    pub fn list(
        &self,
        child_handle: &Handle,
        issuance_timing: &IssuanceTimingConfig,
    ) -> KrillResult<api::Entitlements> {
        let mut classes = vec![];

        for rcn in self.resources.keys() {
            if let Some(class) = self.entitlement_class(child_handle, rcn, issuance_timing) {
                classes.push(class);
            }
        }

        Ok(Entitlements::new(classes))
    }

    /// Returns an issuance response for a child and a specific resource
    /// class name and public key for the issued certificate.
    pub fn issuance_response(
        &self,
        child_handle: &Handle,
        class_name: &ResourceClassName,
        pub_key: &PublicKey,
        issuance_timing: &IssuanceTimingConfig,
    ) -> KrillResult<api::IssuanceResponse> {
        let entitlement_class = self
            .entitlement_class(child_handle, class_name, issuance_timing)
            .ok_or(Error::KeyUseNoIssuedCert)?;

        entitlement_class
            .into_issuance_response(pub_key)
            .ok_or(Error::KeyUseNoIssuedCert)
    }

    /// Returns the EntitlementClass for this child for the given class name.
    fn entitlement_class(
        &self,
        child_handle: &Handle,
        rcn: &ResourceClassName,
        issuance_timing: &IssuanceTimingConfig,
    ) -> Option<api::EntitlementClass> {
        let my_rc = match self.resources.get(rcn) {
            Some(rc) => rc,
            None => return None,
        };

        let my_current_key = match my_rc.current_key() {
            Some(key) => key,
            None => return None,
        };

        let my_rcvd_cert = my_current_key.incoming_cert();
        let issuer = SigningCert::new(my_rcvd_cert.uri().clone(), my_rcvd_cert.cert().clone());

        let child = match self.get_child(child_handle) {
            Ok(child) => child,
            Err(_) => return None,
        };

        let child_resources = my_rcvd_cert.resources().intersection(child.resources());
        if child_resources.is_empty() {
            return None;
        }

        let child_keys = child.issued(rcn);

        let mut issued_certs = vec![];
        let mut not_after = Time::now();
        for ki in child_keys {
            if let Some(issued) = my_rc.issued(&ki) {
                issued_certs.push(issued.clone());
                let eligible_not_after = Self::child_cert_eligible_not_after(issued, issuance_timing);
                if eligible_not_after > not_after {
                    not_after = eligible_not_after
                }
            }
        }

        Some(EntitlementClass::new(
            rcn.clone(),
            issuer,
            child_resources,
            not_after,
            issued_certs,
        ))
    }

    fn child_cert_eligible_not_after(issued: &IssuedCert, issuance_timing: &IssuanceTimingConfig) -> Time {
        let expiration_time = issued.validity().not_after();
        if expiration_time
            > Time::now() + chrono::Duration::weeks(issuance_timing.timing_child_certificate_reissue_weeks_before)
        {
            expiration_time
        } else {
            Time::now() + chrono::Duration::weeks(issuance_timing.timing_child_certificate_valid_weeks)
        }
    }

    /// Returns a child, or an error if the child is unknown.
    pub fn get_child(&self, child: &Handle) -> KrillResult<&ChildDetails> {
        match self.children.get(child) {
            None => Err(Error::CaChildUnknown(self.handle.clone(), child.clone())),
            Some(child) => Ok(child),
        }
    }

    /// Returns an iterator for the handles of all children under this CA.
    pub fn children(&self) -> impl Iterator<Item = &ChildHandle> {
        self.children.keys()
    }

    /// Adds the child, returns an error if the child is a duplicate,
    /// or if the resources are empty, or not held by this CA.
    fn child_add(&self, child: ChildHandle, id_cert: IdCert, resources: ResourceSet) -> KrillResult<Vec<CaEvt>> {
        if resources.is_empty() {
            Err(Error::CaChildMustHaveResources(self.handle.clone(), child))
        } else if !self.all_resources().contains(&resources) {
            Err(Error::CaChildExtraResources(self.handle.clone(), child))
        } else if self.has_child(&child) {
            Err(Error::CaChildDuplicate(self.handle.clone(), child))
        } else {
            info!(
                "CA '{}' added child '{}' with resources '{}'",
                self.handle, child, resources
            );

            Ok(vec![CaEvtDet::child_added(
                &self.handle,
                self.version,
                child,
                id_cert,
                resources,
            )])
        }
    }

    /// Certifies a child, unless:
    /// = the child is unknown,
    /// = the child is not authorized,
    /// = the csr is invalid,
    /// = the limit exceeds the child allocation,
    /// = the signer throws up..
    fn child_certify(
        &self,
        child: Handle,
        request: IssuanceRequest,
        config: &Config,
        signer: Arc<KrillSigner>,
    ) -> KrillResult<Vec<CaEvt>> {
        let (rcn, limit, csr) = request.unpack();
        let csr_info = CsrInfo::try_from(&csr)?;

        if !csr_info.global_uris() && !test_mode_enabled() {
            return Err(Error::invalid_csr(
                "MUST use hostnames in URIs for certificate requests.",
            ));
        }

        let issued =
            self.issue_child_certificate(&child, rcn.clone(), csr_info, limit, &config.issuance_timing, &signer)?;

        let cert_name = ObjectName::from(issued.cert());
        info!(
            "CA '{}' issued certificate '{}' to child '{}'",
            self.handle, cert_name, child
        );

        let issued_event = CaEvtDet::child_certificate_issued(
            &self.handle,
            self.version,
            child,
            rcn.clone(),
            issued.subject_key_identifier(),
        );

        let mut cert_updates = ChildCertificateUpdates::default();
        cert_updates.issue(issued);
        let child_certs_updated =
            CaEvtDet::child_certificates_updated(&self.handle, self.version + 1, rcn, cert_updates);

        Ok(vec![issued_event, child_certs_updated])
    }

    /// Issue a new child certificate.
    fn issue_child_certificate(
        &self,
        child: &ChildHandle,
        rcn: ResourceClassName,
        csr_info: CsrInfo,
        limit: RequestResourceLimit,
        issuance_timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<IssuedCert> {
        let my_rc = self.resources.get(&rcn).ok_or(Error::ResourceClassUnknown(rcn))?;

        let child = self.get_child(&child)?;
        child.resources().apply_limit(&limit)?;

        my_rc.issue_cert(csr_info, child.resources(), limit, issuance_timing, signer)
    }

    /// Updates child Resource entitlements.
    ///
    /// This does not yet revoke / reissue / republish anything.
    /// Also, this is a no-op if the child already has these resources.
    fn child_update_resources(&self, child_handle: &Handle, resources: ResourceSet) -> KrillResult<Vec<CaEvt>> {
        if !self.all_resources().contains(&resources) {
            Err(Error::CaChildExtraResources(self.handle.clone(), child_handle.clone()))
        } else {
            let child = self.get_child(child_handle)?;

            let resources_diff = resources.difference(child.resources());

            if !resources_diff.is_empty() {
                info!(
                    "CA '{}' update child '{}' resources: {}",
                    self.handle, child_handle, resources_diff
                );

                Ok(vec![CaEvtDet::child_updated_resources(
                    &self.handle,
                    self.version,
                    child_handle.clone(),
                    resources,
                )])
            } else {
                // Using 'debug' here, because there are possible use cases where updating the child resources to some expected
                // resource set should be considered a no-op without complaints. E.g. if there is a background job calling
                // the API and setting entitlements.
                debug!(
                    "CA '{}' update child '{}' resources has no effect, child already holds all resources",
                    self.handle, child_handle
                );
                Ok(vec![])
            }
        }
    }

    /// Updates child IdCert
    fn child_update_id(&self, child_handle: &Handle, id_cert: IdCert) -> KrillResult<Vec<CaEvt>> {
        let child = self.get_child(child_handle)?;

        if &id_cert != child.id_cert() {
            info!(
                "CA '{}' updated child '{}' cert. New key id: {}",
                self.handle,
                child_handle,
                id_cert.subject_public_key_info().key_identifier()
            );

            Ok(vec![CaEvtDet::child_updated_cert(
                &self.handle,
                self.version,
                child_handle.clone(),
                id_cert,
            )])
        } else {
            // Using 'debug' here, because of possible no-op use cases where the API is called from a background job.
            debug!(
                "CA '{}' updated child '{}' cert had no effect. Child ID certificate is identical",
                self.handle, child_handle
            );
            Ok(vec![])
        }
    }

    /// Revokes a key for a child. So, add the last cert for the key to the CRL, and withdraw
    /// the .cer file for it.
    fn child_revoke_key(&self, child_handle: ChildHandle, request: RevocationRequest) -> KrillResult<Vec<CaEvt>> {
        let (rcn, key) = request.unpack();

        let child = self.get_child(&child_handle)?;

        if !child.is_issued(&key) {
            return Err(Error::KeyUseNoIssuedCert);
        }

        let handle = &self.handle;
        let version = self.version;

        let mut child_certificate_updates = ChildCertificateUpdates::default();
        child_certificate_updates.remove(key);

        let cert_name = ObjectName::new(&key, "cer");
        info!(
            "CA '{}' revoked certificate '{}' for child '{}'",
            handle, cert_name, child_handle
        );

        let rev = CaEvtDet::child_revoke_key(handle, version, child_handle, rcn.clone(), key);
        let upd = CaEvtDet::child_certificates_updated(handle, version + 1, rcn, child_certificate_updates);

        Ok(vec![rev, upd])
    }

    fn child_remove(&self, child_handle: &ChildHandle) -> KrillResult<Vec<CaEvt>> {
        let child = self.get_child(&child_handle)?;

        let mut version = self.version;
        let handle = &self.handle;

        let mut res = vec![];

        // Find all the certs in all RCs for this child and revoke, and withdraw them.
        for (rcn, rc) in self.resources.iter() {
            let certified_keys = child.issued(rcn);

            if certified_keys.is_empty() {
                continue;
            }

            let mut issued_certs = vec![];
            for key in certified_keys {
                if let Some(issued) = rc.issued(&key) {
                    issued_certs.push(issued);
                }
            }

            let mut cert_updates = ChildCertificateUpdates::default();
            for issued in issued_certs {
                let cert_name = ObjectName::from(issued.cert());
                info!(
                    "CA '{}' revoked certificate '{}' for child '{}'",
                    handle, cert_name, child_handle
                );
                cert_updates.remove(issued.subject_key_identifier())
            }
            res.push(CaEvtDet::child_certificates_updated(
                handle,
                version,
                rcn.clone(),
                cert_updates,
            ));
            version += 1;
        }

        info!("CA '{}' removed child '{}'", handle, child_handle);
        res.push(CaEvtDet::child_removed(handle, version, child_handle.clone()));

        Ok(res)
    }

    /// Returns `true` if the child is known, `false` otherwise. No errors.
    fn has_child(&self, child_handle: &Handle) -> bool {
        self.children.contains_key(child_handle)
    }
}

/// # Being a child
///
impl CertAuth {
    /// Generates a new ID key for this CA.
    fn generate_new_id_key(&self, signer: Arc<KrillSigner>) -> KrillResult<Vec<CaEvt>> {
        let id = Rfc8183Id::generate(&signer)?;

        info!(
            "CA '{}' generated new ID certificate with key id: {}",
            self.handle,
            id.key_id()
        );
        Ok(vec![CaEvtDet::id_updated(&self.handle, self.version, id)])
    }

    /// List all parents
    pub fn parents(&self) -> impl Iterator<Item = &ParentHandle> {
        self.parents.keys()
    }

    pub fn parent_known(&self, parent: &ParentHandle) -> bool {
        self.parents.contains_key(parent)
    }

    fn parent_for_info(&self, info: &ParentCaContact) -> Option<&ParentHandle> {
        for (parent, parent_info) in &self.parents {
            if parent_info == info {
                return Some(parent);
            }
        }
        None
    }

    /// Returns true if this CertAuth is set up as a TA.
    pub fn is_ta(&self) -> bool {
        for info in self.parents.values() {
            if let ParentCaContact::Ta(_) = info {
                return true;
            }
        }

        false
    }

    /// Gets the ParentCaContact for this ParentHandle. Returns an Err when the
    /// parent does not exist.
    pub fn parent(&self, parent: &ParentHandle) -> KrillResult<&ParentCaContact> {
        self.parents
            .get(parent)
            .ok_or_else(|| Error::CaParentUnknown(self.handle.clone(), parent.clone()))
    }

    /// Find the parent for a given resource class name.
    pub fn parent_for_rc(&self, rcn: &ResourceClassName) -> KrillResult<&ParentHandle> {
        let rc = self
            .resources
            .get(rcn)
            .ok_or_else(|| Error::ResourceClassUnknown(rcn.clone()))?;
        Ok(rc.parent_handle())
    }

    /// Adds a parent. This method will return an error in case a parent
    /// by this name (handle) is already known. Or in case the same response
    /// is used for more than one parent.
    fn add_parent(&self, parent: Handle, info: ParentCaContact) -> KrillResult<Vec<CaEvt>> {
        if self.parent_known(&parent) {
            Err(Error::CaParentDuplicateName(self.handle.clone(), parent))
        } else if let Some(other) = self.parent_for_info(&info) {
            Err(Error::CaParentDuplicateInfo(self.handle.clone(), other.clone()))
        } else if self.is_ta() {
            Err(Error::TaNotAllowed)
        } else {
            info!("CA '{}' added parent '{}'", self.handle, parent);
            Ok(vec![CaEvtDet::parent_added(&self.handle, self.version, parent, info)])
        }
    }

    /// Removes a parent. Returns an error if it doesn't exist.
    fn remove_parent(&self, parent: Handle) -> KrillResult<Vec<CaEvt>> {
        if !self.parent_known(&parent) {
            Err(Error::CaParentUnknown(self.handle.clone(), parent))
        } else {
            let mut event_details = vec![];

            info!("CA '{}' removed parent '{}'", self.handle, parent);

            for (rcn, rc) in &self.resources {
                if rc.parent_handle() == &parent {
                    event_details.push(CaEvtDet::ResourceClassRemoved {
                        resource_class_name: rcn.clone(),
                        parent: parent.clone(),
                        revoke_requests: vec![], // We will do a best effort revoke request, but not triggered through this event
                    });
                }
            }

            event_details.push(CaEvtDet::ParentRemoved { parent });

            Ok(self.events_from_details(event_details))
        }
    }

    /// Updates an existing parent's contact. This will return an error if
    /// the parent is not known.
    fn update_parent(&self, parent: Handle, info: ParentCaContact) -> KrillResult<Vec<CaEvt>> {
        if !self.parent_known(&parent) {
            Err(Error::CaParentUnknown(self.handle.clone(), parent))
        } else if self.is_ta() {
            Err(Error::TaNotAllowed)
        } else {
            info!("CA '{}' updated contact info for parent '{}'", self.handle, parent);
            Ok(vec![CaEvtDet::parent_updated(&self.handle, self.version, parent, info)])
        }
    }

    /// Maps a parent and parent's resource class name to a ResourceClassName and
    /// ResourceClass of our own.
    fn find_parent_rc(&self, parent: &ParentHandle, parent_rcn: &ResourceClassName) -> Option<&ResourceClass> {
        for rc in self.resources.values() {
            if rc.parent_handle() == parent && rc.parent_rc_name() == parent_rcn {
                return Some(rc);
            }
        }
        None
    }

    /// Get all the current open certificate requests for a parent.
    /// Returns an empty list if the parent is not found.
    pub fn cert_requests(&self, parent_handle: &ParentHandle) -> HashMap<ResourceClassName, Vec<IssuanceRequest>> {
        let mut res = HashMap::new();

        for (name, rc) in self.resources.iter() {
            if rc.parent_handle() == parent_handle {
                res.insert(name.clone(), rc.cert_requests());
            }
        }

        res
    }

    fn make_request_events(
        &self,
        entitlement: &EntitlementClass,
        rc: &ResourceClass,
        signer: &KrillSigner,
    ) -> KrillResult<Vec<CaEvtDet>> {
        let repo = self.repository_contact()?;
        rc.make_entitlement_events(self.handle(), entitlement, repo.repo_info(), signer)
    }

    /// Returns the open revocation requests for the given parent.
    pub fn revoke_requests(&self, parent: &ParentHandle) -> HashMap<ResourceClassName, Vec<RevocationRequest>> {
        let mut res = HashMap::new();
        for (name, rc) in self.resources.iter() {
            let mut revokes = vec![];
            if let Some(req) = rc.revoke_request() {
                if rc.parent_handle() == parent {
                    revokes.push(req.clone())
                }
            }
            res.insert(name.clone(), revokes);
        }
        res
    }

    /// Returns whether the CA has any pending requests for a parent
    pub fn has_pending_requests(&self, parent: &ParentHandle) -> bool {
        for rc in self.resources.values() {
            if rc.parent_handle() == parent && rc.has_pending_requests() {
                return true;
            }
        }
        false
    }

    /// This processes entitlements from a parent, and updates the resource
    /// classes for this CA as needed. I.e.
    ///
    /// 1) It removes lost RCs, and requests revocation of the key(s). Note
    ///    that this revocation request may result in an error because the
    ///    parent already revoked these keys - or not - we don't know.
    ///
    /// 2) For any new RCs in the entitlements new RCs will be created, each
    ///    with a pending key and an open certificate sign request.
    ///
    /// 3) For RCs that exist both for the CA and in the entitlements, new
    ///    certificates will be requested in case resource entitlements, or
    ///    validity times (not after) changed.
    ///
    /// Note that when we receive the updated certificate, we will republish
    /// and shrink/revoke child certificates and ROAs as needed.
    fn update_entitlements(
        &self,
        parent_handle: Handle,
        entitlements: Entitlements,
        signer: Arc<KrillSigner>,
    ) -> KrillResult<Vec<CaEvt>> {
        let mut event_details: Vec<CaEvtDet> = vec![];

        // Check if there is a resource class for each entitlement

        // Check if there are any current resource classes, now removed
        // from the entitlements. In which case we will have to clean them
        // up and un-publish everything there was.
        let current_resource_classes = &self.resources;

        let entitled_classes: Vec<&ResourceClassName> = entitlements.classes().iter().map(|c| c.class_name()).collect();

        for (rcn, rc) in current_resource_classes.iter().filter(|(_name, class)| {
            // Find the classes for this parent, not included
            // in the entitlements now received.
            class.parent_handle() == &parent_handle && !entitled_classes.contains(&class.parent_rc_name())
        }) {
            let revoke_requests = rc.revoke(signer.deref())?;

            info!("Updating Entitlements for CA: {}, Removing RC: {}", &self.handle, &rcn);

            event_details.push(CaEvtDet::ResourceClassRemoved {
                resource_class_name: rcn.clone(),
                parent: parent_handle.clone(),
                revoke_requests,
            });
        }

        // Now check all the entitlements and either create an RC for them, or update.
        let mut next_class_name = self.next_class_name;

        for ent in entitlements.classes() {
            let parent_rc_name = ent.class_name();

            match self.find_parent_rc(&parent_handle, &parent_rc_name) {
                Some(rc) => {
                    // We have a matching RC, make requests (note this may be a no-op).
                    event_details.append(&mut self.make_request_events(ent, rc, signer.deref())?);
                }
                None => {
                    // Create a resource class with a pending key
                    let pending_key = signer.create_key()?;

                    let resource_class_name = ResourceClassName::from(next_class_name);
                    next_class_name += 1;

                    info!("CA '{}' received entitlement under parent '{}', created resource class '{}' and made certificate request", self.handle, parent_handle, resource_class_name);

                    let ns = resource_class_name.to_string();

                    let rc = ResourceClass::create(
                        resource_class_name.clone(),
                        ns,
                        parent_handle.clone(),
                        parent_rc_name.clone(),
                        pending_key,
                    );

                    let added = CaEvtDet::ResourceClassAdded {
                        resource_class_name,
                        parent: parent_handle.clone(),
                        parent_resource_class_name: parent_rc_name.clone(),
                        pending_key,
                    };
                    let mut request_events = self.make_request_events(ent, &rc, signer.deref())?;

                    event_details.push(added);
                    event_details.append(&mut request_events);
                }
            }
        }

        Ok(self.events_from_details(event_details))
    }

    /// This method updates the received certificate for the given parent
    /// and resource class, and will return an error if either is unknown.
    ///
    /// It will generate an event for the certificate that is received, and
    /// if it was received for a pending key it will return an event to promote
    /// the pending key appropriately, finally it will also return a
    /// publication event for the matching key if publication is needed.
    ///
    /// This will also generate appropriate events for changes affecting
    /// issued ROAs and delegated certificates - if because resources were
    //  lost and ROAs/Certs would be become invalid.
    fn update_received_cert(
        &self,
        rcn: ResourceClassName,
        rcvd_cert: RcvdCert,
        config: &Config,
        signer: Arc<KrillSigner>,
    ) -> KrillResult<Vec<CaEvt>> {
        debug!("CA {}: Updating received cert for class: {}", self.handle, rcn);

        let rc = self.resources.get(&rcn).ok_or(Error::ResourceClassUnknown(rcn))?;

        let evt_details = rc.update_received_cert(self.handle(), rcvd_cert, &self.routes, config, signer.deref())?;

        let mut res = vec![];
        let mut version = self.version;

        for details in evt_details.into_iter() {
            res.push(StoredEvent::new(&self.handle, version, details));
            version += 1;
        }

        Ok(res)
    }
}

/// # Key Rolls
///
impl CertAuth {
    fn keyroll_initiate(&self, duration: Duration, signer: Arc<KrillSigner>) -> KrillResult<Vec<CaEvt>> {
        if self.is_ta() {
            return Ok(vec![]);
        }

        let mut version = self.version;
        let mut res = vec![];

        for (rcn, rc) in self.resources.iter() {
            let mut started = false;
            let repo = self.repository_contact()?;
            for details in rc.keyroll_initiate(repo.repo_info(), duration, &signer)?.into_iter() {
                started = true;
                res.push(StoredEvent::new(self.handle(), version, details));
                version += 1;
            }

            if started {
                info!(
                    "Started key roll for ca: {}, rc: {}, under parent: {}",
                    &self.handle,
                    rcn,
                    rc.parent_handle()
                );
            }
        }

        Ok(res)
    }

    fn keyroll_activate(
        &self,
        staging_time: Duration,
        config: Arc<Config>,
        signer: Arc<KrillSigner>,
    ) -> KrillResult<Vec<CaEvt>> {
        if self.is_ta() {
            return Ok(vec![]);
        }

        let mut version = self.version;
        let mut res = vec![];

        for (rcn, rc) in self.resources.iter() {
            let mut activated = false;

            for details in rc
                .keyroll_activate(staging_time, &config.issuance_timing, signer.deref())?
                .into_iter()
            {
                activated = true;
                res.push(StoredEvent::new(self.handle(), version, details));
                version += 1;
            }

            if activated {
                info!(
                    "Activated key for ca: {}, rc: {}, under parent: {}",
                    &self.handle,
                    rcn,
                    rc.parent_handle()
                );
            }
        }

        Ok(res)
    }

    fn keyroll_finish(&self, rcn: ResourceClassName, _response: RevocationResponse) -> KrillResult<Vec<CaEvt>> {
        if self.is_ta() {
            return Ok(vec![]);
        }
        let my_rc = self
            .resources
            .get(&rcn)
            .ok_or_else(|| Error::ResourceClassUnknown(rcn.clone()))?;

        let finish_details = my_rc.keyroll_finish()?;

        info!(
            "Finished key roll for ca: {}, rc: {}, under parent: {}",
            &self.handle,
            rcn,
            my_rc.parent_handle()
        );

        Ok(vec![StoredEvent::new(self.handle(), self.version, finish_details)])
    }
}

/// # Publishing
///
impl CertAuth {
    /// Update repository:
    ///    - Will return an error in case the repo is already set (issue 481)
    ///    - Will support migrations using key rollover in future (issue 480)
    ///    - Assumes that the repository can be reached (this is checked by CaManager before issuing the command to this CA)
    pub fn update_repo(&self, contact: RepositoryContact, _signer: &KrillSigner) -> KrillResult<Vec<CaEvt>> {
        if let Some(_existing_contact) = &self.repository {
            // Disallow, see issue 481
            return Err(Error::CaRepoAlreadyConfigured(self.handle.clone()));
            // TODO: check that it is indeed different and then allow (issue 480)
            // if existing_contact == &contact {
            //     return Err(Error::CaRepoInUse(self.handle.clone()));
            // }
            // // Initiate rolls in all RCs so we can use the new repo in the new key.
            // let info = contact.repo_info().clone();
            // for rc in self.resources.values() {
            //     // If we are in any keyroll, reject.. because we will need to
            //     // introduce the change as a key roll (new key, new repo, etc),
            //     // and we can only do one roll at a time.
            //     if !rc.key_roll_possible() {
            //         // If we can't roll... well then we have to bail out.
            //         // Note: none of these events are committed in that case.
            //         return Err(Error::KeyRollNotAllowed);
            //     }
            //     evt_dets.append(&mut rc.keyroll_initiate(&info, Duration::seconds(0), &signer)?);
            // }
        }

        // register updated repo
        info!(
            "CA '{}' updated repository. Service URI will be: {}",
            self.handle,
            contact.service_uri()
        );

        let evt_dets = vec![CaEvtDet::RepoUpdated { contact }];
        Ok(self.events_from_details(evt_dets))
    }
}

/// # Managing Route Authorizations
///
impl CertAuth {
    /// Updates the route authorizations for this CA, and update ROAs. Will return
    /// an error in case authorizations are added for which this CA does not hold
    /// the prefix.
    fn route_authorizations_update(
        &self,
        route_auth_updates: RouteAuthorizationUpdates,
        config: &Config,
        signer: Arc<KrillSigner>,
    ) -> KrillResult<Vec<CaEvt>> {
        let route_auth_updates = route_auth_updates.into_explicit();

        let (routes, mut evt_dets) = self.update_authorizations(&route_auth_updates)?;

        // for rc in self.resources
        for (rcn, rc) in self.resources.iter() {
            let updates = rc.update_roas(&routes, None, config, signer.deref())?;
            if updates.contains_changes() {
                info!("CA '{}' under RC '{}' updated ROAs: {}", self.handle, rcn, updates);

                evt_dets.push(CaEvtDet::RoasUpdated {
                    resource_class_name: rcn.clone(),
                    updates,
                });
            }
        }

        Ok(self.events_from_details(evt_dets))
    }

    /// Renew existing ROA objects if needed.
    pub fn route_authorizations_renew(&self, config: &Config, signer: &KrillSigner) -> KrillResult<Vec<CaEvt>> {
        let mut evt_dets = vec![];

        for (rcn, rc) in self.resources.iter() {
            let updates = rc.renew_roas(&config.issuance_timing, signer)?;
            if updates.contains_changes() {
                info!(
                    "CA '{}' reissued ROAs under RC '{}' before they would expire: {}",
                    self.handle, rcn, updates
                );

                evt_dets.push(CaEvtDet::RoasUpdated {
                    resource_class_name: rcn.clone(),
                    updates,
                });
            }
        }

        Ok(self.events_from_details(evt_dets))
    }

    /// Verifies that the updates are correct, i.e.:
    /// - additions are for prefixes held by this CA
    /// - removals are for known authorizations
    /// - additions are new
    ///   - no duplicates, or
    ///   - not covered by remaining after the removals
    ///
    /// Returns the desired Routes and the event details for
    /// persisting the changes, or an error in case of issues.
    ///
    /// Note: this does not re-issue the actual ROAs, this
    ///       can be used for the 'dry-run' option.
    pub fn update_authorizations(&self, updates: &RouteAuthorizationUpdates) -> KrillResult<(Routes, Vec<CaEvtDet>)> {
        let mut delta_errors = RoaDeltaError::default();
        let mut res = vec![];

        let all_resources = self.all_resources();

        let mut desired_routes = self.routes.clone();

        // make sure that all removals are held
        for auth in updates.removed() {
            if desired_routes.remove(auth) {
                res.push(CaEvtDet::RouteAuthorizationRemoved { auth: *auth });
            } else {
                delta_errors.add_unknown((*auth).into())
            }
        }

        // make sure that all new additions are allowed
        for addition in updates.added() {
            let roa_def: RoaDefinition = (*addition).into();
            let authorizations: Vec<&RouteAuthorization> = desired_routes.authorizations().collect();

            if !addition.max_length_valid() {
                // The (max) length is invalid for this prefix
                delta_errors.add_invalid_length(roa_def);
            } else if !all_resources.contains_roa_address(&addition.as_roa_ip_address()) {
                // We do not hold the prefix
                delta_errors.add_notheld(roa_def);
            } else if authorizations.iter().any(|existing| *existing == addition) {
                // A duplicate ROA already exists
                delta_errors.add_duplicate(roa_def);
            } else {
                // Ok, this seems okay now
                desired_routes.add(*addition);
                res.push(CaEvtDet::RouteAuthorizationAdded { auth: *addition });
            }
        }

        if !delta_errors.is_empty() {
            Err(Error::RoaDeltaError(delta_errors))
        } else {
            Ok((desired_routes, res))
        }
    }
}

/// # Resource Tagged Attestations
///
impl CertAuth {
    pub fn rta_list(&self) -> RtaList {
        self.rtas.list()
    }

    pub fn rta_show(&self, name: &str) -> KrillResult<ResourceTaggedAttestation> {
        self.rtas.signed_rta(name)
    }

    pub fn rta_prep_response(&self, name: &str) -> KrillResult<RtaPrepResponse> {
        self.rtas
            .prepared_rta(name)
            .map(|prepped| RtaPrepResponse::new(prepped.keys()))
    }

    /// Sign a new RTA
    fn rta_sign(&self, name: RtaName, request: RtaContentRequest, signer: &KrillSigner) -> KrillResult<Vec<CaEvt>> {
        let (resources, validity, mut keys, content) = request.unpack();

        if self.rtas.has(&name) {
            return Err(Error::Custom(format!("RTA with name '{}' already exists", name)));
        }

        let rc2ee = self.rta_ee_map_single(&resources, validity, &mut keys, signer)?;
        let builder = ResourceTaggedAttestation::rta_builder(&resources, content, keys)?;

        self.rta_sign_with_ee(name, resources, rc2ee, builder, signer)
    }

    /// Co-sign an existing RTA, will fail if there is no existing matching prepared RTA
    fn rta_cosign(
        &self,
        name: RtaName,
        rta: ResourceTaggedAttestation,
        signer: &KrillSigner,
    ) -> KrillResult<Vec<CaEvt>> {
        let builder = rta.to_builder()?;

        let resources = {
            let asns = builder.content().as_resources().clone();
            let v4 = builder.content().v4_resources().clone();
            let v6 = builder.content().v6_resources().clone();
            ResourceSet::new(asns, v4, v6)
        };

        let keys = builder.content().subject_keys();
        let rc2ee = self.rta_ee_map_prepared(&name, &resources, keys, signer)?;

        self.rta_sign_with_ee(name, resources, rc2ee, builder, signer)
    }

    fn rta_sign_with_ee(
        &self,
        name: RtaName,
        resources: ResourceSet,
        rc_ee: HashMap<ResourceClassName, Cert>,
        mut rta_builder: RtaBuilder,
        signer: &KrillSigner,
    ) -> KrillResult<Vec<CaEvt>> {
        let revocation_info = rc_ee
            .iter()
            .map(|(rcn, ee)| (rcn.clone(), Revocation::from(ee)))
            .collect();

        // Then sign the content with all those RCs and all keys (including submitted keys) and add the cert
        for (_rcn, ee) in rc_ee.into_iter() {
            let ee_key = ee.subject_key_identifier();
            signer.sign_rta(&mut rta_builder, ee)?;
            signer.destroy_key(&ee_key)?;
        }

        let rta = ResourceTaggedAttestation::finalize(rta_builder);

        let rta = SignedRta::new(resources, revocation_info, rta);

        info!("CA '{}' signed an RTA object named '{}'", self.handle, name);

        // Return the RTA
        Ok(vec![StoredEvent::new(
            self.handle(),
            self.version,
            CaEvtDet::RtaSigned { name, rta },
        )])
    }

    fn rta_ee_map_prepared(
        &self,
        name: &str,
        resources: &ResourceSet,
        keys: &[KeyIdentifier],
        signer: &KrillSigner,
    ) -> KrillResult<HashMap<ResourceClassName, Cert>> {
        let prepared = self.rtas.prepared_rta(name)?;

        let validity = prepared.validity();

        if resources != prepared.resources() {
            return Err(Error::custom("Request to sign prepared RTA with changed resources"));
        }

        // Sign with all prepared keys, error out if one of those keys is removed from the request
        let mut rc_ee: HashMap<ResourceClassName, Cert> = HashMap::new();
        for (rcn, key) in prepared.key_map() {
            if !keys.contains(key) {
                return Err(Error::custom("RTA Request does not include key for prepared RTA"));
            }

            let rc = self
                .resources
                .get(rcn)
                .ok_or_else(|| Error::custom("RC for prepared RTA not found"))?;

            let rc_resources = rc
                .current_resources()
                .ok_or_else(|| Error::custom("RC for RTA has no resources"))?;

            let intersection = rc_resources.intersection(&resources);
            if intersection.is_empty() {
                return Err(Error::custom(
                    "RC for prepared RTA no longer contains relevant resources",
                ));
            }

            let ee = rc.create_rta_ee(&intersection, validity, *key, &signer)?;
            rc_ee.insert(rcn.clone(), ee);
        }

        Ok(rc_ee)
    }

    fn rta_ee_map_single(
        &self,
        resources: &ResourceSet,
        validity: Validity,
        keys: &mut Vec<KeyIdentifier>,
        signer: &KrillSigner,
    ) -> KrillResult<HashMap<ResourceClassName, Cert>> {
        // If there are no other keys supplied, then we MUST have all resources.
        // Otherwise we will just assume that others sign over the resources that
        // we do not have.
        if keys.is_empty() && !self.all_resources().contains(&resources) {
            return Err(Error::RtaResourcesNotHeld);
        }

        // Create an EE for each RC that contains part of the resources
        let mut rc_ee: HashMap<ResourceClassName, Cert> = HashMap::new();
        for (rcn, rc) in self.resources.iter() {
            if let Some(rc_resources) = rc.current_resources() {
                let intersection = resources.intersection(rc_resources);
                if !intersection.is_empty() {
                    let key = signer.create_key()?;
                    let ee = rc.create_rta_ee(&intersection, validity, key, &signer)?;
                    rc_ee.insert(rcn.clone(), ee);
                }
            }
        }

        let one_of_keys: Vec<KeyIdentifier> = rc_ee.values().map(|ee| ee.subject_key_identifier()).collect();

        // Add all one-off keys to the list of Key Identifiers
        // Note that list includes possible keys by other CAs in the RtaRequest
        for key in one_of_keys.iter() {
            keys.push(*key);
        }

        Ok(rc_ee)
    }

    pub fn rta_multi_prep(
        &self,
        name: RtaName,
        request: RtaPrepareRequest,
        signer: &KrillSigner,
    ) -> KrillResult<Vec<CaEvt>> {
        let (resources, validity) = request.unpack();

        if self.all_resources().intersection(&resources).is_empty() {
            return Err(Error::custom("None of the resources for RTA are held by this CA"));
        }

        if self.rtas.has(&name) {
            return Err(Error::Custom(format!("RTA with name '{}' already exists", name)));
        }

        let mut keys = HashMap::new();

        for (rcn, rc) in self.resources.iter() {
            if let Some(rc_resources) = rc.current_resources() {
                if !rc_resources.intersection(&resources).is_empty() {
                    let key = signer.create_key()?;
                    keys.insert(rcn.clone(), key);
                }
            }
        }

        let prepared = PreparedRta::new(resources, validity, keys);

        info!(
            "CA '{}' prepared an RTA object named '{}' for multi-signing",
            self.handle, name
        );

        Ok(vec![StoredEvent::new(
            self.handle(),
            self.version,
            CaEvtDet::RtaPrepared { name, prepared },
        )])
    }
}

/// # Deactivate
///
impl CertAuth {
    pub fn revoke_under_parent(
        &self,
        parent: &ParentHandle,
        signer: &KrillSigner,
    ) -> KrillResult<HashMap<ResourceClassName, Vec<RevocationRequest>>> {
        let mut res = HashMap::new();
        for (rcn, rc) in &self.resources {
            if rc.parent_handle() == parent {
                res.insert(rcn.clone(), rc.revoke(signer)?);
            }
        }
        Ok(res)
    }
}

//------------ Tests ---------------------------------------------------------

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

    #[test]
    fn generate_id_cert() {
        test::test_under_tmp(|d| {
            let signer = KrillSigner::build(&d).unwrap();
            let id = Rfc8183Id::generate(&signer).unwrap();
            id.cert.validate_ta().unwrap();
        });
    }
}