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
//! Support for signing mft, crl, certificates, roas..
//! Common objects for TAs and CAs
use std::{
    borrow::BorrowMut,
    collections::HashMap,
    ops::{Deref, DerefMut},
    str::FromStr,
    sync::{Arc, RwLock},
};

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

use rpki::{
    cert::Cert,
    crl::{Crl, TbsCertList},
    crypto::{DigestAlgorithm, KeyIdentifier, PublicKey},
    manifest::{FileAndHash, Manifest, ManifestContent},
    roa::Roa,
    sigobj::SignedObjectBuilder,
    x509::{Name, Serial, Time, Validity},
};

use crate::{
    commons::{
        api::{
            rrdp::PublishElement, Base64, Handle, IssuedCert, ObjectName, RcvdCert, RepositoryContact,
            ResourceClassName, Revocation, Revocations,
        },
        crypto::KrillSigner,
        error::Error,
        eventsourcing::{KeyStoreKey, KeyValueStore, PreSaveEventListener},
        KrillResult,
    },
    constants::CA_OBJECTS_DIR,
    daemon::{
        ca::{CaEvt, CertAuth},
        config::{Config, IssuanceTimingConfig},
    },
};

use super::{CertifiedKey, ChildCertificateUpdates, RoaUpdates};

//------------ CaObjectsStore ----------------------------------------------

/// This component is responsible for storing the latest objects for each CA.
///
/// By using a stateful store for this purpose we can generate Manifests and
/// CRLs outside of the normal event-sourcing framework used to track the
/// history and state of CAs. I.e. we treat the frequent republish cycle as
/// something that does not intrinsically modify the CA itself.
///
/// In earlier generations of Krill the simple republish operation to generate
/// new Manifests and CRLs was done through the event sourcing framework. However,
/// this led to excessive use of disk space, makes the history more difficult to
/// inspect, and causes issues with regards to replaying CA state from scratch.
#[derive(Clone, Debug)]
pub struct CaObjectsStore {
    store: Arc<RwLock<KeyValueStore>>,
    signer: Arc<KrillSigner>,
    config: Arc<Config>,
}

/// # Construct
impl CaObjectsStore {
    pub fn disk(config: Arc<Config>, signer: Arc<KrillSigner>) -> KrillResult<Self> {
        let work_dir = &config.data_dir;
        let store = KeyValueStore::disk(work_dir, CA_OBJECTS_DIR)?;
        let store = Arc::new(RwLock::new(store));
        Ok(CaObjectsStore { store, signer, config })
    }
}

/// # Process new objects as they are being produced
impl PreSaveEventListener<CertAuth> for CaObjectsStore {
    fn listen(&self, ca: &CertAuth, events: &[CaEvt]) -> KrillResult<()> {
        // Note that the `CertAuth` which is passed in has already been
        // updated with the state changes contained in the event.

        let timing = &self.config.issuance_timing;
        let signer = &self.signer;

        self.with_ca_objects(ca.handle(), |objects| {
            for event in events {
                match event.details() {
                    super::CaEvtDet::RoasUpdated {
                        resource_class_name,
                        updates,
                    } => {
                        objects.update_roas(resource_class_name, updates, timing, signer)?;
                    }
                    super::CaEvtDet::ChildCertificatesUpdated {
                        resource_class_name,
                        updates,
                    } => {
                        objects.update_certs(resource_class_name, updates, timing, signer)?;
                    }
                    super::CaEvtDet::KeyPendingToActive {
                        resource_class_name,
                        current_key,
                    } => {
                        objects.add_class(resource_class_name, current_key, timing, signer)?;
                    }
                    super::CaEvtDet::KeyPendingToNew {
                        resource_class_name,
                        new_key,
                    } => {
                        objects.keyroll_stage(resource_class_name, new_key, timing, signer)?;
                    }
                    super::CaEvtDet::KeyRollActivated {
                        resource_class_name, ..
                    } => {
                        objects.keyroll_activate(resource_class_name, timing, signer)?;
                    }
                    super::CaEvtDet::KeyRollFinished { resource_class_name } => {
                        objects.keyroll_finish(resource_class_name)?;
                    }
                    super::CaEvtDet::CertificateReceived {
                        resource_class_name,
                        rcvd_cert,
                        ..
                    } => {
                        // Update the received certificate if needed. If the URIs changed we may need to re-issue things
                        objects.update_received_cert(resource_class_name, rcvd_cert)?;
                        objects.re_issue_if_required(&self.config.issuance_timing, &self.signer)?;
                    }
                    super::CaEvtDet::ResourceClassRemoved {
                        resource_class_name, ..
                    } => {
                        objects.remove_class(resource_class_name);
                    }
                    super::CaEvtDet::RepoUpdated { contact } => {
                        objects.update_repo(contact);
                    }
                    _ => {}
                }
            }
            Ok(())
        })
    }
}

impl CaObjectsStore {
    fn key(ca: &Handle) -> KeyStoreKey {
        KeyStoreKey::simple(format!("{}.json", ca))
    }

    fn cas(&self) -> KrillResult<Vec<Handle>> {
        let cas = self
            .store
            .read()
            .unwrap()
            .keys(None, ".json")?
            .iter()
            .flat_map(|k| {
                // Only add entries that end with .json AND for which the first part can be parsed as a handle
                let mut res = None;
                if let Some(name) = k.name().strip_suffix(".json") {
                    if let Ok(handle) = Handle::from_str(name) {
                        res = Some(handle)
                    }
                }
                res
            })
            .collect();
        Ok(cas)
    }

    /// Get objects for this CA, create a new empty CaObjects if there is none.
    pub fn ca_objects(&self, ca: &Handle) -> KrillResult<CaObjects> {
        let key = Self::key(ca);

        match self.store.read().unwrap().get(&key).map_err(Error::KeyValueError)? {
            None => {
                let objects = CaObjects::new(ca.clone(), None, HashMap::new());
                Ok(objects)
            }
            Some(objects) => Ok(objects),
        }
    }

    /// Perform an action (closure) on a mutable instance of the CaObjects for a
    /// CA. If the CA did not have any CaObjects yet, one will be created. The
    /// closure is executed within a write lock.
    pub fn with_ca_objects<F>(&self, ca: &Handle, op: F) -> KrillResult<()>
    where
        F: FnOnce(&mut CaObjects) -> KrillResult<()>,
    {
        let lock = self.store.write().unwrap();

        let key = Self::key(ca);

        let mut objects = lock
            .get(&key)
            .map_err(Error::KeyValueError)?
            .unwrap_or_else(|| CaObjects::new(ca.clone(), None, HashMap::new()));

        op(&mut objects)?;

        lock.store(&key, &objects).map_err(Error::KeyValueError)?;

        Ok(())
    }

    pub fn put_ca_objects(&self, ca: &Handle, objects: &CaObjects) -> KrillResult<()> {
        self.store
            .write()
            .unwrap()
            .store(&Self::key(ca), objects)
            .map_err(Error::KeyValueError)
    }

    // Re-issue MFT and CRL for all CAs *if needed*, returns all CAs which were
    // updated.
    pub fn reissue_all(&self) -> KrillResult<Vec<Handle>> {
        let mut res = vec![];
        for ca in self.cas()? {
            self.with_ca_objects(&ca, |objects| {
                if objects.re_issue_if_required(&self.config.issuance_timing, &self.signer)? {
                    res.push(ca.clone())
                }
                Ok(())
            })?;
        }
        Ok(res)
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CaObjects {
    ca: Handle,
    repo: Option<RepositoryContact>,

    #[serde(with = "ca_objects_classes_serde")]
    classes: HashMap<ResourceClassName, ResourceClassObjects>,

    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    deprecated_repos: Vec<DeprecatedRepository>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DeprecatedRepository {
    contact: RepositoryContact,
    clean_attempts: usize,
}

impl DeprecatedRepository {
    pub fn new(contact: RepositoryContact, clean_attempts: usize) -> Self {
        DeprecatedRepository {
            contact,
            clean_attempts,
        }
    }

    pub fn contact(&self) -> &RepositoryContact {
        &self.contact
    }

    pub fn clean_attempts(&self) -> usize {
        self.clean_attempts
    }

    pub fn inc_clean_attempts(&mut self) {
        self.clean_attempts += 1;
    }
}

impl From<DeprecatedRepository> for RepositoryContact {
    fn from(deprecated: DeprecatedRepository) -> Self {
        deprecated.contact
    }
}

mod ca_objects_classes_serde {

    use super::*;

    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;
    #[derive(Debug, Deserialize)]
    struct ClassesItem {
        class_name: ResourceClassName,
        objects: ResourceClassObjects,
    }

    #[derive(Debug, Serialize)]
    struct ClassesItemRef<'a> {
        class_name: &'a ResourceClassName,
        objects: &'a ResourceClassObjects,
    }

    pub fn serialize<S>(
        map: &HashMap<ResourceClassName, ResourceClassObjects>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_seq(
            map.iter()
                .map(|(class_name, objects)| ClassesItemRef { class_name, objects }),
        )
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<ResourceClassName, ResourceClassObjects>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut map = HashMap::new();
        for item in Vec::<ClassesItem>::deserialize(deserializer)? {
            map.insert(item.class_name, item.objects);
        }
        Ok(map)
    }
}

impl CaObjects {
    pub fn new(
        ca: Handle,
        repo: Option<RepositoryContact>,
        classes: HashMap<ResourceClassName, ResourceClassObjects>,
    ) -> Self {
        CaObjects {
            ca,
            repo,
            classes,
            deprecated_repos: vec![],
        }
    }

    #[allow(clippy::clippy::mutable_key_type)]
    /// Returns all PublishedElements mapped to each RepositoryContact.
    /// There could be more than one repository - although usually there isn't.
    pub fn repo_elements_map(&self) -> HashMap<RepositoryContact, Vec<PublishElement>> {
        let mut res = HashMap::new();

        if let Some(repo) = &self.repo {
            res.insert(repo.clone(), vec![]);

            for rco in self.classes.values() {
                // Note the map 'res' will get entries for other (old) repositories
                // if there are any keys with such repositories.
                rco.add_elements(&mut res, repo);
            }
        }

        res
    }

    /// Returns all PublishElements in all repositories (if there is more than one).
    pub fn all_publish_elements(&self) -> Vec<PublishElement> {
        let mut all_elements = vec![];

        // slightly inefficient since we drop the RepositoryContact keys again, but this leverages existing code.
        for elements in self.repo_elements_map().values_mut() {
            all_elements.append(elements);
        }

        all_elements
    }

    pub fn deprecated_repos(&self) -> &Vec<DeprecatedRepository> {
        &self.deprecated_repos
    }

    pub fn deprecated_repo_remove(&mut self, to_remove: &RepositoryContact) {
        self.deprecated_repos.retain(|current| current.contact() != to_remove);
    }

    pub fn deprecated_repo_inc_clean_attempts(&mut self, contact: &RepositoryContact) {
        for current in self.deprecated_repos.iter_mut() {
            if current.contact() == contact {
                current.inc_clean_attempts()
            }
        }
    }

    /// Add a new resource class, this returns an error in case the class already exists.
    fn add_class(
        &mut self,
        class_name: &ResourceClassName,
        key: &CertifiedKey,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        if self.classes.contains_key(class_name) {
            Err(Error::publishing("Duplicate resource class"))
        } else {
            self.classes
                .insert(class_name.clone(), ResourceClassObjects::create(key, timing, signer)?);
            Ok(())
        }
    }

    fn remove_class(&mut self, class_name: &ResourceClassName) {
        let old_repo_opt = self
            .classes
            .get(class_name)
            .map(|rco| rco.old_repo())
            .flatten()
            .cloned();

        self.classes.remove(class_name);

        if let Some(old_repo) = old_repo_opt {
            self.deprecate_repo_if_no_longer_used(old_repo);
        }
    }

    fn get_class_mut(&mut self, rcn: &ResourceClassName) -> KrillResult<&mut ResourceClassObjects> {
        self.classes
            .get_mut(rcn)
            .ok_or_else(|| Error::publishing("Missing resource class"))
    }

    // Add a staging key to the set, this will fail in case the class is missing, or in case
    // the class is not in state 'current'.
    fn keyroll_stage(
        &mut self,
        rcn: &ResourceClassName,
        key: &CertifiedKey,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        let rco = self.get_class_mut(rcn)?;
        rco.keyroll_stage(key, timing, signer)
    }

    // Activates the keyset by retiring the current set, and promoting
    // the staging set to current.
    fn keyroll_activate(
        &mut self,
        rcn: &ResourceClassName,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        let rco = self.get_class_mut(rcn)?;
        rco.keyroll_activate(timing, signer)
    }

    // Finish a keyroll
    fn keyroll_finish(&mut self, rcn: &ResourceClassName) -> KrillResult<()> {
        let rco = self.get_class_mut(rcn)?;

        // finish the key roll for this rco. This will remove the old key, and return
        // an old_repo if there was one.
        if let Some(old_repo) = rco.keyroll_finish()? {
            self.deprecate_repo_if_no_longer_used(old_repo);
        }

        Ok(())
    }

    // Update the ROAs in the current set
    fn update_roas(
        &mut self,
        rcn: &ResourceClassName,
        roa_updates: &RoaUpdates,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        let rco = self.get_class_mut(rcn)?;
        rco.update_roas(roa_updates, timing, signer)
    }

    // Update the delegated certificates in the current set
    fn update_certs(
        &mut self,
        rcn: &ResourceClassName,
        cert_updates: &ChildCertificateUpdates,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        let rco = self.get_class_mut(rcn)?;
        rco.update_certs(cert_updates, timing, signer)
    }

    // Update the received certificate.
    fn update_received_cert(&mut self, rcn: &ResourceClassName, cert: &RcvdCert) -> KrillResult<()> {
        let rco = self.get_class_mut(rcn)?;
        rco.update_received_cert(cert)
    }

    /// Reissue the MFT and CRL in this set if needed, i.e. if it's close to the next
    /// update time, or in case the AIA has changed.. the latter really should not happen,
    /// but ultimately we have no control over this, so better safe.
    fn re_issue_if_required(&mut self, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<bool> {
        let hours = timing.timing_publish_hours_before_next;
        let mut required = false;

        for (_, rco) in self.classes.iter_mut() {
            if rco.requires_re_issuance(hours) {
                required = true;
                rco.reissue(timing, signer)?;
            }
        }

        Ok(required)
    }

    // Update the repository.
    //
    // If the repository is being migrated, i.e. there already is a current repository,
    // then make sure that the current repository is preserved as the old repository for
    // existing keys.
    fn update_repo(&mut self, repo: &RepositoryContact) {
        if let Some(old) = &self.repo {
            for rco in self.classes.values_mut() {
                rco.set_old_repo(old);
            }
        }
        self.repo = Some(repo.clone());
    }

    fn has_old_repo(&self, old_repo: &RepositoryContact) -> bool {
        self.classes.values().any(|rco| rco.has_old_repo(old_repo))
    }

    // Marks a repository as deprecated unless it's (still) in use by any key
    fn deprecate_repo_if_no_longer_used(&mut self, old_repo: RepositoryContact) {
        if !self.has_old_repo(&old_repo) {
            self.deprecated_repos.push(DeprecatedRepository::new(old_repo, 0));
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ResourceClassObjects {
    keys: ResourceClassKeyState,
}

impl ResourceClassObjects {
    pub fn new(keys: ResourceClassKeyState) -> Self {
        ResourceClassObjects { keys }
    }

    #[allow(clippy::clippy::mutable_key_type)]
    /// Adds all the elements for this resource class to the map which is passed on. It will use
    /// the default repository, or an optional old repository if any of the keys had one as part
    /// of a repository migration.
    fn add_elements(&self, map: &mut HashMap<RepositoryContact, Vec<PublishElement>>, dflt_repo: &RepositoryContact) {
        match &self.keys {
            ResourceClassKeyState::Current(state) => state.current_set.add_elements(map, dflt_repo),
            ResourceClassKeyState::Staging(state) => {
                state.current_set.add_elements(map, dflt_repo);
                state.staging_set.add_elements(map, dflt_repo);
            }
            ResourceClassKeyState::Old(state) => {
                state.current_set.add_elements(map, dflt_repo);
                state.old_set.add_elements(map, dflt_repo);
            }
        }
    }

    fn create(key: &CertifiedKey, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<Self> {
        let current_set = BasicKeyObjectSet::create(key, timing, signer)?.into();

        Ok(ResourceClassObjects {
            keys: ResourceClassKeyState::Current(CurrentKeyState { current_set }),
        })
    }

    fn keyroll_stage(
        &mut self,
        key: &CertifiedKey,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        let current_set = match &self.keys {
            ResourceClassKeyState::Current(state) => state.current_set.clone(),
            _ => return Err(Error::publishing("published resource class in the wrong key state")),
        };

        let staging_set = BasicKeyObjectSet::create(key, timing, signer)?;

        self.keys = ResourceClassKeyState::Staging(StagingKeyState {
            staging_set,
            current_set,
        });

        Ok(())
    }

    fn keyroll_activate(&mut self, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<()> {
        self.keys = match &self.keys {
            ResourceClassKeyState::Staging(state) => {
                let old_set = state.current_set.retire(timing, signer)?;
                let current_set = state.staging_set.clone().into();
                ResourceClassKeyState::Old(OldKeyState { current_set, old_set })
            }
            _ => return Err(Error::publishing("published resource class in the wrong key state")),
        };

        Ok(())
    }

    fn keyroll_finish(&mut self) -> KrillResult<Option<RepositoryContact>> {
        match self.keys.clone() {
            ResourceClassKeyState::Old(old) => {
                let current_set = old.current_set;
                self.keys = ResourceClassKeyState::current(current_set);
                Ok(old.old_set.old_repo)
            }
            _ => Err(Error::publishing("published resource class in the wrong key state")),
        }
    }

    fn update_received_cert(&mut self, updated_cert: &RcvdCert) -> KrillResult<()> {
        self.keys.update_received_cert(updated_cert)
    }

    fn update_roas(
        &mut self,
        roa_updates: &RoaUpdates,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        match self.keys.borrow_mut() {
            ResourceClassKeyState::Current(state) => state.current_set.update_roas(roa_updates, timing, signer),
            ResourceClassKeyState::Staging(state) => state.current_set.update_roas(roa_updates, timing, signer),
            ResourceClassKeyState::Old(state) => state.current_set.update_roas(roa_updates, timing, signer),
        }
    }

    fn update_certs(
        &mut self,
        cert_updates: &ChildCertificateUpdates,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        match self.keys.borrow_mut() {
            ResourceClassKeyState::Current(state) => state.current_set.update_certs(cert_updates, timing, signer),
            ResourceClassKeyState::Staging(state) => state.current_set.update_certs(cert_updates, timing, signer),
            ResourceClassKeyState::Old(state) => state.current_set.update_certs(cert_updates, timing, signer),
        }
    }

    fn requires_re_issuance(&self, hours: i64) -> bool {
        match &self.keys {
            ResourceClassKeyState::Current(state) => state.current_set.requires_reissuance(hours),
            ResourceClassKeyState::Old(state) => {
                state.old_set.requires_reissuance(hours) || state.current_set.requires_reissuance(hours)
            }
            ResourceClassKeyState::Staging(state) => {
                state.staging_set.requires_reissuance(hours) || state.current_set.requires_reissuance(hours)
            }
        }
    }

    fn reissue(&mut self, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<()> {
        match self.keys.borrow_mut() {
            ResourceClassKeyState::Current(state) => state.current_set.reissue(timing, signer),
            ResourceClassKeyState::Staging(state) => {
                state.staging_set.reissue(timing, signer)?;
                state.current_set.reissue(timing, signer)
            }
            ResourceClassKeyState::Old(state) => {
                state.old_set.reissue(timing, signer)?;
                state.current_set.reissue(timing, signer)
            }
        }
    }

    fn set_old_repo(&mut self, repo: &RepositoryContact) {
        match self.keys.borrow_mut() {
            ResourceClassKeyState::Current(state) => state.current_set.set_old_repo(repo),
            ResourceClassKeyState::Staging(state) => {
                state.staging_set.set_old_repo(repo);
                state.current_set.set_old_repo(repo);
            }
            ResourceClassKeyState::Old(state) => {
                state.old_set.set_old_repo(repo);
                state.current_set.set_old_repo(repo);
            }
        }
    }

    fn has_old_repo(&self, repo: &RepositoryContact) -> bool {
        match &self.keys {
            ResourceClassKeyState::Current(state) => state.current_set.old_repo() == Some(repo),
            ResourceClassKeyState::Staging(state) => {
                state.staging_set.old_repo() == Some(repo) || state.current_set.old_repo() == Some(repo)
            }
            ResourceClassKeyState::Old(state) => {
                state.old_set.old_repo() == Some(repo) || state.current_set.old_repo() == Some(repo)
            }
        }
    }

    fn old_repo(&self) -> Option<&RepositoryContact> {
        // Note: we can only have 1 old repo, because new repositories can only be introduced
        // when there is no key roll in progress. So, it's not possible to introduce a second
        // repo until the previous old_repo is rolled out completely.
        match &self.keys {
            ResourceClassKeyState::Current(state) => state.current_set.old_repo(),
            ResourceClassKeyState::Staging(state) => {
                state.staging_set.old_repo().or_else(|| state.current_set.old_repo())
            }
            ResourceClassKeyState::Old(state) => state.old_set.old_repo().or_else(|| state.current_set.old_repo()),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ResourceClassKeyState {
    Current(CurrentKeyState),
    Staging(StagingKeyState),
    Old(OldKeyState),
}

impl ResourceClassKeyState {
    pub fn current(current_set: CurrentKeyObjectSet) -> Self {
        ResourceClassKeyState::Current(CurrentKeyState { current_set })
    }

    pub fn staging(staging_set: BasicKeyObjectSet, current_set: CurrentKeyObjectSet) -> Self {
        ResourceClassKeyState::Staging(StagingKeyState {
            staging_set,
            current_set,
        })
    }

    pub fn old(current_set: CurrentKeyObjectSet, old_set: BasicKeyObjectSet) -> Self {
        ResourceClassKeyState::Old(OldKeyState { current_set, old_set })
    }

    fn update_received_cert(&mut self, cert: &RcvdCert) -> KrillResult<()> {
        match self {
            ResourceClassKeyState::Current(state) => state.current_set.update_signing_cert(cert),
            ResourceClassKeyState::Staging(state) => {
                if state.staging_set.update_signing_cert(cert).is_ok() {
                    Ok(())
                } else {
                    state.current_set.update_signing_cert(cert)
                }
            }
            ResourceClassKeyState::Old(state) => {
                if state.old_set.update_signing_cert(cert).is_ok() {
                    Ok(())
                } else {
                    state.current_set.update_signing_cert(cert)
                }
            }
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CurrentKeyState {
    current_set: CurrentKeyObjectSet,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct StagingKeyState {
    staging_set: BasicKeyObjectSet,
    current_set: CurrentKeyObjectSet,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct OldKeyState {
    current_set: CurrentKeyObjectSet,
    old_set: BasicKeyObjectSet,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CurrentKeyObjectSet {
    #[serde(flatten)]
    basic: BasicKeyObjectSet,
    #[serde(with = "objects_to_roas_serde")]
    roas: HashMap<ObjectName, PublishedRoa>,
    #[serde(with = "objects_to_certs_serde")]
    certs: HashMap<ObjectName, PublishedCert>,
}

impl CurrentKeyObjectSet {
    pub fn new(
        signing_cert: RcvdCert,
        number: u64,
        revocations: Revocations,
        manifest: PublishedManifest,
        crl: PublishedCrl,
        roas: HashMap<ObjectName, PublishedRoa>,
        certs: HashMap<ObjectName, PublishedCert>,
    ) -> Self {
        let basic = BasicKeyObjectSet {
            signing_cert,
            number,
            revocations,
            manifest,
            crl,
            old_repo: None,
        };
        CurrentKeyObjectSet { basic, roas, certs }
    }

    /// Adds all the elements for this set to the map which is passed on. It will use
    /// the default repository unless this key had an old repository set - as part of
    /// repository migration.
    #[allow(clippy::mutable_key_type)]
    fn add_elements(&self, map: &mut HashMap<RepositoryContact, Vec<PublishElement>>, dflt_repo: &RepositoryContact) {
        let repo = self.old_repo.as_ref().unwrap_or(dflt_repo);

        let base_uri = self.signing_cert.ca_repository();
        let mft_uri = base_uri.join(self.manifest.name().as_bytes());
        let crl_uri = base_uri.join(self.crl.name().as_bytes());

        let elements = map.entry(repo.clone()).or_insert_with(Vec::new);
        elements.push(PublishElement::new(Base64::from(&self.manifest.0), mft_uri));
        elements.push(PublishElement::new(Base64::from(&self.crl.0), crl_uri));

        for (name, roa) in &self.roas {
            elements.push(PublishElement::new(
                Base64::from(&roa.0),
                base_uri.join(name.as_bytes()),
            ));
        }

        for (name, cert) in &self.certs {
            elements.push(PublishElement::new(
                Base64::from(cert.as_ref()),
                base_uri.join(name.as_bytes()),
            ));
        }
    }

    fn update_roas(
        &mut self,
        roa_updates: &RoaUpdates,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        for (name, roa) in roa_updates.added_roas()? {
            if let Some(old) = self.roas.insert(name, roa) {
                self.revocations.add(Revocation::from(&old));
            }
        }
        for name in roa_updates.removed_roas() {
            if let Some(old) = self.roas.remove(&name) {
                self.revocations.add(Revocation::from(&old));
            }
        }

        self.reissue(timing, signer)
    }

    fn update_certs(
        &mut self,
        cert_updates: &ChildCertificateUpdates,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<()> {
        for removed in cert_updates.removed() {
            let name = ObjectName::new(removed, "cer");
            if let Some(old) = self.certs.remove(&name) {
                self.revocations.add(Revocation::from(&old));
            }
        }

        for issued in cert_updates.issued() {
            let name = ObjectName::from(issued.cert());
            if let Some(old) = self.certs.insert(name, issued.clone().into()) {
                self.revocations.add(Revocation::from(&old));
            }
        }

        self.reissue(timing, signer)
    }

    fn reissue(&mut self, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<()> {
        self.revocations.purge();

        self.crl = self.reissue_crl(&self.revocations, timing, signer)?;
        self.manifest = self.reissue_mft(&self.crl, timing, signer)?;
        self.number = self.next();

        Ok(())
    }

    fn retire(&self, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<BasicKeyObjectSet> {
        let mut revocations = self.revocations.clone();
        for roa in self.roas.values() {
            revocations.add(roa.into());
        }

        for cert in self.certs.values() {
            revocations.add(cert.into())
        }

        revocations.purge();

        let crl = self.basic.reissue_crl(&revocations, timing, signer)?;
        let manifest = self.basic.reissue_mft(&crl, timing, signer)?;

        Ok(BasicKeyObjectSet {
            signing_cert: self.signing_cert.clone(),
            number: self.next(),
            revocations,
            manifest,
            crl,
            old_repo: self.old_repo.clone(),
        })
    }

    fn reissue_mft(
        &self,
        new_crl: &PublishedCrl,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<PublishedManifest> {
        ManifestBuilder::with_objects(new_crl, &self.roas, &self.certs)
            .build_new_mft(&self.signing_cert, self.next(), timing, signer)
            .map(|m| m.into())
    }
}

impl From<BasicKeyObjectSet> for CurrentKeyObjectSet {
    fn from(basic: BasicKeyObjectSet) -> Self {
        CurrentKeyObjectSet {
            basic,
            roas: HashMap::new(),
            certs: HashMap::new(),
        }
    }
}

impl Deref for CurrentKeyObjectSet {
    type Target = BasicKeyObjectSet;

    fn deref(&self) -> &Self::Target {
        &self.basic
    }
}

impl DerefMut for CurrentKeyObjectSet {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.basic
    }
}

mod objects_to_roas_serde {
    use super::*;

    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;
    #[derive(Debug, Deserialize)]
    struct NameRoaItem {
        name: ObjectName,
        roa: PublishedRoa,
    }

    #[derive(Debug, Serialize)]
    struct NameRoaItemRef<'a> {
        name: &'a ObjectName,
        roa: &'a PublishedRoa,
    }

    pub fn serialize<S>(map: &HashMap<ObjectName, PublishedRoa>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_seq(map.iter().map(|(name, roa)| NameRoaItemRef { name, roa }))
    }

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

mod objects_to_certs_serde {
    use super::*;

    use serde::de::{Deserialize, Deserializer};
    use serde::ser::Serializer;
    #[derive(Debug, Deserialize)]
    struct NameCertItem {
        name: ObjectName,
        issued: PublishedCert,
    }

    #[derive(Debug, Serialize)]
    struct NameCertItemRef<'a> {
        name: &'a ObjectName,
        issued: &'a PublishedCert,
    }

    pub fn serialize<S>(map: &HashMap<ObjectName, PublishedCert>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_seq(map.iter().map(|(name, issued)| NameCertItemRef { name, issued }))
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<ObjectName, PublishedCert>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let mut map = HashMap::new();
        for item in Vec::<NameCertItem>::deserialize(deserializer)? {
            map.insert(item.name, item.issued);
        }
        Ok(map)
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BasicKeyObjectSet {
    signing_cert: RcvdCert,
    number: u64,
    revocations: Revocations,
    manifest: PublishedManifest,
    crl: PublishedCrl,
    #[serde(skip_serializing_if = "Option::is_none")]
    old_repo: Option<RepositoryContact>,
}

impl BasicKeyObjectSet {
    pub fn new(
        signing_cert: RcvdCert,
        number: u64,
        revocations: Revocations,
        manifest: PublishedManifest,
        crl: PublishedCrl,
    ) -> Self {
        BasicKeyObjectSet {
            signing_cert,
            number,
            revocations,
            manifest,
            crl,
            old_repo: None,
        }
    }

    /// Adds all the elements for this set to the map which is passed on. It will use
    /// the default repository unless this key had an old repository set - as part of
    /// repository migration.
    #[allow(clippy::mutable_key_type)]
    fn add_elements(&self, map: &mut HashMap<RepositoryContact, Vec<PublishElement>>, dflt_repo: &RepositoryContact) {
        let repo = self.old_repo.as_ref().unwrap_or(dflt_repo);

        let base_uri = self.signing_cert.ca_repository();
        let mft_uri = base_uri.join(self.manifest.name().as_bytes());
        let crl_uri = base_uri.join(self.crl.name().as_bytes());

        let elements = map.entry(repo.clone()).or_insert_with(Vec::new);
        elements.push(PublishElement::new(Base64::from(&self.manifest.0), mft_uri));
        elements.push(PublishElement::new(Base64::from(&self.crl.0), crl_uri));
    }

    fn create(key: &CertifiedKey, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<Self> {
        let signing_cert = key.incoming_cert().clone();

        let signing_key = signing_cert.subject_public_key_info();
        let issuer = signing_cert.subject().clone();
        let revocations = Revocations::default();
        let number = 1;
        let next_hours = timing.timing_publish_next_hours;

        let crl = CrlBuilder::build(signing_key, issuer, &revocations, number, next_hours, signer)?;

        let manifest = ManifestBuilder::with_crl_only(&crl)
            .build_new_mft(&signing_cert, number, timing, signer)
            .map(|m| m.into())?;

        Ok(BasicKeyObjectSet::new(signing_cert, number, revocations, manifest, crl))
    }

    pub fn requires_reissuance(&self, hours: i64) -> bool {
        Time::now() + Duration::hours(hours) > self.manifest.next_update()
            || Some(self.signing_cert.uri()) != self.manifest.cert().ca_issuer()
    }

    fn next(&self) -> u64 {
        self.number + 1
    }

    // Returns an error in case the KeyIdentifiers don't match.
    fn update_signing_cert(&mut self, cert: &RcvdCert) -> KrillResult<()> {
        if self.signing_cert.subject_key_identifier() == cert.subject_key_identifier() {
            self.signing_cert = cert.clone();
            Ok(())
        } else {
            Err(Error::PublishingObjects(format!(
                "received new cert for unknown key id: {}",
                cert.subject_key_identifier()
            )))
        }
    }

    fn reissue(&self, timing: &IssuanceTimingConfig, signer: &KrillSigner) -> KrillResult<Self> {
        let mut revocations = self.revocations.clone();
        revocations.purge();

        let crl = self.reissue_crl(&revocations, timing, signer)?;
        let manifest = self.reissue_mft(&crl, timing, signer)?;

        Ok(BasicKeyObjectSet {
            signing_cert: self.signing_cert.clone(),
            number: self.next(),
            revocations,
            manifest,
            crl,
            old_repo: self.old_repo.clone(),
        })
    }

    fn reissue_crl(
        &self,
        revocations: &Revocations,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<PublishedCrl> {
        let signing_key = self.signing_cert.subject_public_key_info();
        let issuer = self.crl.issuer().clone();
        let number = self.next();

        let next_hours = timing.timing_publish_next_hours;

        CrlBuilder::build(signing_key, issuer, revocations, number, next_hours, signer)
    }

    fn reissue_mft(
        &self,
        new_crl: &PublishedCrl,
        timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<PublishedManifest> {
        ManifestBuilder::with_crl_only(new_crl)
            .build_new_mft(&self.signing_cert, self.next(), timing, signer)
            .map(|m| m.into())
    }

    fn set_old_repo(&mut self, repo: &RepositoryContact) {
        self.old_repo = Some(repo.clone())
    }

    fn old_repo(&self) -> Option<&RepositoryContact> {
        self.old_repo.as_ref()
    }
}

//------------ PublishedCert -----------------------------------------------
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct PublishedCert(IssuedCert);

impl PublishedCert {
    pub fn to_bytes(&self) -> Bytes {
        self.0.to_captured().into_bytes()
    }

    pub fn mft_hash(&self) -> Bytes {
        mft_hash(self.to_bytes().as_ref())
    }
}

impl From<IssuedCert> for PublishedCert {
    fn from(issued: IssuedCert) -> Self {
        PublishedCert(issued)
    }
}

impl From<&PublishedCert> for Revocation {
    fn from(c: &PublishedCert) -> Self {
        Revocation::from(c.0.cert())
    }
}

impl Deref for PublishedCert {
    type Target = IssuedCert;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl AsRef<Cert> for PublishedCert {
    fn as_ref(&self) -> &Cert {
        &self.0.as_ref()
    }
}

//------------ PublishedRoa -----------------------------------------------

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PublishedRoa(Roa);

impl PublishedRoa {
    pub fn new(roa: Roa) -> Self {
        PublishedRoa(roa)
    }

    pub fn to_bytes(&self) -> Bytes {
        self.0.to_captured().into_bytes()
    }

    pub fn mft_hash(&self) -> Bytes {
        mft_hash(self.to_bytes().as_ref())
    }
}

impl From<&PublishedRoa> for Revocation {
    fn from(r: &PublishedRoa) -> Self {
        Revocation::from(&r.0)
    }
}

impl Deref for PublishedRoa {
    type Target = Roa;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl PartialEq for PublishedRoa {
    fn eq(&self, other: &Self) -> bool {
        self.to_bytes() == other.to_bytes()
    }
}

impl Eq for PublishedRoa {}

//------------ PublishedManifest ------------------------------------------

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PublishedManifest(Manifest);

impl PublishedManifest {
    pub fn to_bytes(&self) -> Bytes {
        self.0.to_captured().into_bytes()
    }

    pub fn name(&self) -> ObjectName {
        ObjectName::from(&self.0)
    }

    pub fn next_update(&self) -> Time {
        self.0.next_update()
    }
}

impl PartialEq for PublishedManifest {
    fn eq(&self, other: &Self) -> bool {
        self.to_bytes() == other.to_bytes()
    }
}

impl Eq for PublishedManifest {}

impl From<Manifest> for PublishedManifest {
    fn from(mft: Manifest) -> Self {
        PublishedManifest(mft)
    }
}

impl Deref for PublishedManifest {
    type Target = Manifest;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

//------------ PublishedCrl ------------------------------------------------

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PublishedCrl(Crl);

impl PublishedCrl {
    pub fn to_bytes(&self) -> Bytes {
        self.0.to_captured().into_bytes()
    }

    pub fn name(&self) -> ObjectName {
        ObjectName::from(&self.0)
    }

    pub fn mft_hash(&self) -> Bytes {
        mft_hash(self.to_bytes().as_ref())
    }
}

impl PartialEq for PublishedCrl {
    fn eq(&self, other: &Self) -> bool {
        self.to_bytes() == other.to_bytes()
    }
}

impl Eq for PublishedCrl {}

impl From<Crl> for PublishedCrl {
    fn from(crl: Crl) -> Self {
        PublishedCrl(crl)
    }
}

impl Deref for PublishedCrl {
    type Target = Crl;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

//------------ CrlBuilder --------------------------------------------------

pub struct CrlBuilder {}

impl CrlBuilder {
    pub fn build(
        signing_key: &PublicKey,
        issuer: Name,
        revocations: &Revocations,
        number: u64,
        next_hours: i64,
        signer: &KrillSigner,
    ) -> KrillResult<PublishedCrl> {
        let aki = KeyIdentifier::from_public_key(signing_key);

        let this_update = Time::five_minutes_ago();
        let next_update = Time::now() + Duration::hours(next_hours);
        let serial_number = Serial::from(number);

        let crl = TbsCertList::new(
            Default::default(),
            issuer,
            this_update,
            next_update,
            revocations.to_crl_entries(),
            aki,
            serial_number,
        );

        let crl = signer.sign_crl(crl, &aki)?;

        Ok(crl.into())
    }
}

#[allow(clippy::mutable_key_type)]
pub struct ManifestBuilder {
    entries: HashMap<Bytes, Bytes>,
}

impl ManifestBuilder {
    #[allow(clippy::mutable_key_type)]
    pub fn with_objects(
        crl: &PublishedCrl,
        roas: &HashMap<ObjectName, PublishedRoa>,
        certs: &HashMap<ObjectName, PublishedCert>,
    ) -> Self {
        let mut entries: HashMap<Bytes, Bytes> = HashMap::new();

        // Add entry for CRL
        entries.insert(crl.name().into(), crl.mft_hash());

        // Add ROAs
        for (name, roa) in roas {
            let hash = roa.mft_hash();
            entries.insert(name.clone().into(), hash);
        }

        // Add all issued certs
        for (name, cert) in certs {
            let hash = cert.mft_hash();
            entries.insert(name.clone().into(), hash);
        }

        ManifestBuilder { entries }
    }

    #[allow(clippy::mutable_key_type)]
    pub fn with_crl_only(crl: &PublishedCrl) -> Self {
        let mut entries: HashMap<Bytes, Bytes> = HashMap::new();
        entries.insert(crl.name().into(), crl.mft_hash());
        ManifestBuilder { entries }
    }

    fn build_new_mft(
        self,
        signing_cert: &RcvdCert,
        number: u64,
        issuance_timing: &IssuanceTimingConfig,
        signer: &KrillSigner,
    ) -> KrillResult<Manifest> {
        let signing_key = signing_cert.cert().subject_public_key_info();

        let mft_uri = signing_cert.mft_uri();
        let crl_uri = signing_cert.crl_uri();

        let aia = signing_cert.uri();
        let aki = KeyIdentifier::from_public_key(signing_key);
        let serial_number = Serial::from(number);

        let this_update = Time::five_minutes_ago();
        let now = Time::now();
        let next_update = Time::now() + Duration::hours(issuance_timing.timing_publish_next_hours);
        let valid_until = Time::now() + Duration::days(issuance_timing.timing_publish_valid_days);

        let entries = self.entries.iter().map(|(k, v)| FileAndHash::new(k, v));

        let manifest: Manifest = {
            let mft_content = ManifestContent::new(
                serial_number,
                this_update,
                next_update,
                DigestAlgorithm::default(),
                entries,
            );
            let mut object_builder = SignedObjectBuilder::new(
                signer.random_serial()?,
                Validity::new(this_update, valid_until),
                crl_uri,
                aia.clone(),
                mft_uri,
            );
            object_builder.set_issuer(Some(signing_cert.cert().subject().clone()));
            object_builder.set_signing_time(Some(now));

            signer.sign_manifest(mft_content, object_builder, &aki)?
        };

        Ok(manifest)
    }
}

fn mft_hash(bytes: &[u8]) -> Bytes {
    let digest = DigestAlgorithm::default().digest(bytes);
    Bytes::copy_from_slice(digest.as_ref())
}

#[cfg(test)]
mod test {

    use super::*;

    #[test]
    pub fn ca_objects_ser_de() {
        let json = include_str!("../../../test-resources/ca_objects_store/ca_objects.json");
        let ca_objects: CaObjects = serde_json::from_str(json).unwrap();

        let serialized = serde_json::to_string(&ca_objects).unwrap();

        let ca_objects_again: CaObjects = serde_json::from_str(&serialized).unwrap();

        assert_eq!(ca_objects, ca_objects_again);
    }
}