krill 0.15.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
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
use std::{
    env, fmt,
    fs::File,
    io::{self, Read},
    net::{IpAddr, Ipv4Addr, SocketAddr},
    path::{Path, PathBuf},
    str::FromStr,
    sync::Arc,
};

use chrono::Duration;
use log::{error, info, warn, LevelFilter};
use rpki::{
    ca::idexchange::PublisherHandle,
    repository::x509::{Time, Validity},
    uri,
};
use serde::de;
use serde::{Deserialize, Deserializer, Serialize};
use url::Url;

#[cfg(unix)]
use syslog::Facility;

use crate::{
    commons::{
        ext_serde,
        crypto::{OpenSslSignerConfig, SignSupport},
        error::{Error, KrillIoError},
        storage::{KeyValueStore, Namespace},
        KrillResult,
    },
    constants::*,
    daemon::{
        http::auth::{Role, RoleMap},
        http::tls_keys::{self, HTTPS_SUB_DIR},
    },
    server::mq::{in_seconds, Priority},
    tasigner::TaTimingConfig,
};
use crate::api::admin::{PublicationServerUris, Token};

#[cfg(feature = "multi-user")]
use crate::daemon::http::auth::providers::{
    config_file::ConfigAuthUsers,
    openid_connect::ConfigAuthOpenIDConnect,
};

#[cfg(feature = "hsm")]
use crate::commons::crypto::{KmipSignerConfig, Pkcs11SignerConfig};

//------------ ConfigDefaults ------------------------------------------------

pub struct ConfigDefaults;

impl ConfigDefaults {
    fn dflt_true() -> bool {
        true
    }

    pub fn ip() -> Vec<IpAddr> {
        vec![IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))]
    }

    pub fn port() -> u16 {
        3000
    }

    pub fn https_mode() -> HttpsMode {
        HttpsMode::Generate
    }

    pub fn storage_uri() -> Url {
        env::var(KRILL_ENV_STORAGE_URI)
            .ok()
            .and_then(|s| Url::parse(&s).ok())
            .unwrap_or_else(|| Url::parse("local://./data").unwrap())
    }

    pub fn log_level() -> LevelFilter {
        match env::var(KRILL_ENV_LOG_LEVEL) {
            Ok(level) => match LevelFilter::from_str(&level) {
                Ok(level) => level,
                Err(_) => {
                    eprintln!(
                        "Unrecognized value for log level in env var {KRILL_ENV_LOG_LEVEL}"
                    );
                    ::std::process::exit(1);
                }
            },
            _ => LevelFilter::Info,
        }
    }

    pub fn log_type() -> LogType {
        match env::var(KRILL_ENV_LOG_TYPE) {
            Ok(log_type) => match LogType::from_str(&log_type) {
                Ok(log_type) => log_type,
                Err(e) => {
                    eprintln!(
                        "Unrecognized value for log type in env var {KRILL_ENV_LOG_TYPE}, {e}"
                    );
                    ::std::process::exit(1);
                }
            },
            _ => LogType::File,
        }
    }

    pub fn log_file() -> Option<PathBuf> {
        Some(PathBuf::from("./krill.log"))
    }

    pub fn syslog_facility() -> String {
        "daemon".to_string()
    }

    pub fn auth_type() -> AuthType {
        AuthType::AdminToken
    }

    pub fn auth_roles() -> Arc<RoleMap> {
        let mut res = RoleMap::new();
        res.add("admin", Role::admin());
        res.add("readwrite", Role::readwrite());
        res.add("readonly", Role::readonly());
        res.into()
    }

    pub fn admin_token() -> Token {
        match env::var(KRILL_ENV_ADMIN_TOKEN) {
            Ok(token) => Token::from(token),
            Err(_) => match env::var(KRILL_ENV_ADMIN_TOKEN_DEPRECATED) {
                Ok(token) => Token::from(token),
                Err(_) => {
                    eprintln!("You MUST provide a value for the \"admin token\", either by setting \"admin_token\" in the config file, or by setting the KRILL_ADMIN_TOKEN environment variable.");
                    ::std::process::exit(1);
                }
            },
        }
    }

    pub fn ca_refresh_seconds() -> u32 {
        24 * 3600 // 24 hours
    }

    pub fn ca_refresh_jitter_seconds() -> u32 {
        12 * 3600 // 12 hours
    }

    pub fn ca_refresh_parents_batch_size() -> usize {
        25
    }

    pub fn post_limit_api() -> u64 {
        256 * 1024 // 256kB
    }

    pub fn post_limit_rfc8181() -> u64 {
        32 * 1024 * 1024 // 32MB (roughly 8000 issued certificates, so a key
                         // roll for nicbr and 100% uptake should be okay)
    }

    pub fn rfc8181_log_dir() -> Option<PathBuf> {
        None
    }

    pub fn post_limit_rfc6492() -> u64 {
        1024 * 1024 // 1MB (for ref. the NIC br cert is about 200kB)
    }

    pub fn rfc6492_log_dir() -> Option<PathBuf> {
        None
    }

    pub fn post_protocol_msg_timeout_seconds() -> u64 {
        240 // 4 minutes by default should be plenty in most cases
    }

    pub fn bgp_api_enabled() -> bool {
        true
    }

    pub fn bgp_api_uri() -> String {
        "https://rest.bgp-api.net".to_string()
    }

    pub fn bgp_api_cache_duration() -> Duration {
        Duration::seconds(30 * 60)
    }

    pub fn roa_aggregate_threshold() -> usize {
        if let Ok(from_env) = env::var("KRILL_ROA_AGGREGATE_THRESHOLD") {
            if let Ok(nr) = usize::from_str(&from_env) {
                return nr;
            }
        }
        100
    }

    pub fn roa_deaggregate_threshold() -> usize {
        if let Ok(from_env) = env::var("KRILL_ROA_DEAGGREGATE_THRESHOLD") {
            if let Ok(nr) = usize::from_str(&from_env) {
                return nr;
            }
        }
        90
    }

    pub fn timing_publish_next_hours() -> u32 {
        24
    }

    pub fn timing_publish_next_jitter_hours() -> u32 {
        4
    }

    pub fn timing_publish_hours_before_next() -> u32 {
        8
    }

    pub fn timing_child_certificate_valid_weeks() -> u32 {
        52
    }

    pub fn timing_child_certificate_reissue_weeks_before() -> u32 {
        4
    }

    pub fn timing_roa_valid_weeks() -> u32 {
        52
    }

    pub fn timing_roa_reissue_weeks_before() -> u32 {
        4
    }

    pub fn timing_aspa_valid_weeks() -> u32 {
        52
    }

    pub fn timing_aspa_reissue_weeks_before() -> u32 {
        4
    }

    pub fn timing_bgpsec_valid_weeks() -> u32 {
        52
    }

    pub fn timing_bgpsec_reissue_weeks_before() -> u32 {
        4
    }

    pub fn openssl_signer_only() -> Vec<SignerConfig> {
        let signer_config = OpenSslSignerConfig {
            keys_storage_uri: None,
        };
        vec![SignerConfig::new(
            DEFAULT_SIGNER_NAME.to_string(),
            SignerType::OpenSsl(signer_config),
        )]
    }

    pub fn signers() -> Vec<SignerConfig> {
        #[cfg(not(any(
            feature = "hsm-tests-kmip",
            feature = "hsm-tests-pkcs11"
        )))]
        {
            Self::openssl_signer_only()
        }

        #[cfg(all(feature = "hsm-tests-kmip", feature = "hsm-tests-pkcs11"))]
        {
            // If we have both enables then just go with openssl.
            // This is because we are using rust features here to drive
            // testing which is not ideal.. should be changes when
            // we remove the feature flags for this.
            Self::openssl_signer_only()
        }

        #[cfg(all(
            feature = "hsm-tests-kmip",
            not(feature = "hsm-tests-pkcs11")
        ))]
        {
            let signer_config = KmipSignerConfig {
                host: "127.0.0.1".to_string(),
                port: 5696,
                username: None,
                password: None,
                insecure: true,
                force: true,
                client_cert_path: Some(
                    PathBuf::from_str("test-resources/pykmip/server.crt")
                        .unwrap(),
                ),
                client_cert_private_key_path: Some(
                    PathBuf::from_str("test-resources/pykmip/server.key")
                        .unwrap(),
                ),
                server_cert_path: Some(
                    PathBuf::from_str("test-resources/pykmip/server.crt")
                        .unwrap(),
                ),
                server_ca_cert_path: Some(
                    PathBuf::from_str("test-resources/pykmip/ca.crt")
                        .unwrap(),
                ),
                retry_seconds: KmipSignerConfig::default_retry_seconds(),
                backoff_multiplier:
                    KmipSignerConfig::default_backoff_multiplier(),
                max_retry_seconds:
                    KmipSignerConfig::default_max_retry_seconds(),
                connect_timeout_seconds:
                    KmipSignerConfig::default_connect_timeout_seconds(),
                read_timeout_seconds:
                    KmipSignerConfig::default_read_timeout_seconds(),
                write_timeout_seconds:
                    KmipSignerConfig::default_write_timeout_seconds(),
                max_lifetime_seconds:
                    KmipSignerConfig::default_max_lifetime_seconds(),
                max_idle_seconds: KmipSignerConfig::default_max_idle_seconds(
                ),
                max_connections: KmipSignerConfig::default_max_connections(),
                max_response_bytes:
                    KmipSignerConfig::default_max_response_bytes(),
            };
            return vec![SignerConfig::new(
                DEFAULT_SIGNER_NAME.to_string(),
                SignerType::Kmip(signer_config),
            )];
        }

        #[cfg(all(
            feature = "hsm-tests-pkcs11",
            not(feature = "hsm-tests-kmip")
        ))]
        {
            use crate::commons::crypto::{
                Pkcs11ConfigurablePrivateKeyAttributes,
                Pkcs11ConfigurablePublicKeyAttributes,
                Pkcs11ConfigurableSecrets, SlotIdOrLabel,
            };

            let signer_config = Pkcs11SignerConfig {
                lib_path: "/usr/lib/softhsm/libsofthsm2.so".to_string(),
                secrets: Pkcs11ConfigurableSecrets {
                    user_pin: Some("1234".to_string().into()),
                },
                slot: SlotIdOrLabel::Label("My token 1".to_string()),
                login: true,
                retry_seconds: Pkcs11SignerConfig::default_retry_seconds(),
                backoff_multiplier:
                    Pkcs11SignerConfig::default_backoff_multiplier(),
                max_retry_seconds:
                    Pkcs11SignerConfig::default_max_retry_seconds(),
                public_key_attributes:
                    Pkcs11ConfigurablePublicKeyAttributes::default(),
                private_key_attributes:
                    Pkcs11ConfigurablePrivateKeyAttributes::default(),
            };
            vec![SignerConfig::new(
                DEFAULT_SIGNER_NAME.to_string(),
                SignerType::Pkcs11(signer_config),
            )]
        }
    }

    pub fn signer_probe_retry_seconds() -> u64 {
        30
    }
}

//------------ SignerReference -----------------------------------------------

#[derive(Clone, Debug)]
pub enum SignerReference {
    /// The name of the `\[signers\]` block being referred to.
    ///
    /// If supplied it must match the name field of one of the `\[signers\]`
    /// blocks defined in the configuration.
    Name(Option<String>),

    /// The index into Config.signers vector that the name was resolved to.
    /// Populated based on the value of 'name' and the contents of
    /// Config.signers after the config file has been parsed.
    Index(usize),
}

pub fn deserialize_signer_ref<'de, D>(
    deserializer: D,
) -> Result<SignerReference, D::Error>
where
    D: Deserializer<'de>,
{
    Ok(SignerReference::new(&String::deserialize(deserializer)?))
}

impl Default for SignerReference {
    fn default() -> Self {
        Self::Name(None)
    }
}

impl SignerReference {
    pub fn new(name: &str) -> SignerReference {
        SignerReference::Name(Some(name.to_string()))
    }

    pub fn name(&self) -> &String {
        match self {
            SignerReference::Name(Some(name)) => name,
            _ => panic!("Signer reference is not named"),
        }
    }

    pub fn idx(&self) -> usize {
        match self {
            SignerReference::Index(idx) => *idx,
            _ => panic!("Signer reference is not resolved"),
        }
    }

    pub fn is_named(&self) -> bool {
        matches!(self, SignerReference::Name(Some(_)))
    }

    pub fn is_set(&self) -> bool {
        match self {
            SignerReference::Name(None) => false,
            SignerReference::Name(Some(_)) => true,
            SignerReference::Index(_) => true,
        }
    }
}

fn deserialize_config_ips<'de, D>(
    deserializer: D,
) -> Result<Vec<IpAddr>, D::Error>
where
    D: Deserializer<'de>,
{
    ext_serde::OneOrMany::<IpAddr>::deserialize(
        deserializer
    ).map(|oom| oom.into())
}

pub fn deserialize_storage_uri<'de, D>(
    deserializer: D,
) -> Result<Url, D::Error>
where
    D: Deserializer<'de>,
{
    let url = String::deserialize(deserializer)?;
    match Url::parse(&url) {
        Ok(url) => Ok(url),
        Err(_) => {
            Url::parse(&format!("local://{url}/")).map_err(de::Error::custom)
        }
    }
}

fn deserialize_seconds_duration<'de, D: Deserializer<'de>>(
    deserializer: D
) -> Result<Duration, D::Error> {
    u32::deserialize(deserializer).map(|secs| Duration::seconds(secs.into()))
}


//------------ Config --------------------------------------------------------

/// Global configuration for the Krill Server.
#[derive(Clone, Debug, Deserialize)]
pub struct Config {
    #[serde(
        default = "ConfigDefaults::ip",
        deserialize_with = "deserialize_config_ips"
    )]
    pub ip: Vec<IpAddr>,

    #[serde(default = "ConfigDefaults::port")]
    pub port: u16,

    #[serde(default = "ConfigDefaults::https_mode")]
    pub https_mode: HttpsMode,

    // Deserialize this field from data_dir or storage_uri
    #[serde(
        alias = "data_dir",
        default = "ConfigDefaults::storage_uri",
        deserialize_with = "deserialize_storage_uri"
    )]
    pub storage_uri: Url,

    #[serde(default = "ConfigDefaults::dflt_true")]
    pub use_history_cache: bool,

    pub tls_keys_dir: Option<PathBuf>,

    pub repo_dir: Option<PathBuf>,

    // default is false
    // implicitly enabled in case of testbed
    // for that reason.. not pub, but fn provided
    #[serde(default)]
    pub ta_support_enabled: bool,

    // default is false
    // implicitly enabled in case of testbed
    // MUST be enabled for ca imports to work,
    // but can be disabled later and signer can
    // be migrated.
    //
    // for that reason.. not pub, but fn provided
    #[serde(default)]
    pub ta_signer_enabled: bool,

    pub pid_file: Option<PathBuf>,

    pub service_uri: Option<uri::Https>,

    #[serde(
        default = "ConfigDefaults::log_level",
        deserialize_with = "ext_serde::de_level_filter"
    )]
    pub log_level: LevelFilter,

    #[serde(default = "ConfigDefaults::log_type")]
    pub log_type: LogType,

    #[serde(default = "ConfigDefaults::log_file")]
    pub log_file: Option<PathBuf>,

    #[serde(default = "ConfigDefaults::syslog_facility")]
    pub syslog_facility: String,

    #[serde(default = "ConfigDefaults::admin_token", alias = "auth_token")]
    pub admin_token: Token,

    #[serde(default = "ConfigDefaults::auth_type")]
    pub auth_type: AuthType,

    #[cfg(feature = "multi-user")]
    pub auth_users: Option<ConfigAuthUsers>,

    #[cfg(feature = "multi-user")]
    pub auth_openidconnect: Option<ConfigAuthOpenIDConnect>,

    #[serde(default = "ConfigDefaults::auth_roles")]
    pub auth_roles: Arc<RoleMap>,

    #[serde(default, deserialize_with = "deserialize_signer_ref")]
    pub default_signer: SignerReference,

    #[serde(default, deserialize_with = "deserialize_signer_ref")]
    pub one_off_signer: SignerReference,

    #[serde(default = "ConfigDefaults::signer_probe_retry_seconds")]
    pub signer_probe_retry_seconds: u64,

    #[serde(default = "ConfigDefaults::signers")]
    pub signers: Vec<SignerConfig>,

    #[serde(
        default = "ConfigDefaults::ca_refresh_seconds",
        alias = "ca_refresh"
    )]
    pub ca_refresh_seconds: u32,

    #[serde(default = "ConfigDefaults::ca_refresh_jitter_seconds")]
    pub ca_refresh_jitter_seconds: u32,

    #[serde(default = "ConfigDefaults::ca_refresh_parents_batch_size")]
    pub ca_refresh_parents_batch_size: usize,

    #[serde(skip)]
    pub suspend_child_after_inactive_seconds: Option<u32>,
    pub suspend_child_after_inactive_hours: Option<u32>,

    #[serde(default = "ConfigDefaults::post_limit_api")]
    pub post_limit_api: u64,

    #[serde(default = "ConfigDefaults::post_limit_rfc8181")]
    pub post_limit_rfc8181: u64,

    #[serde(default = "ConfigDefaults::rfc8181_log_dir")]
    pub rfc8181_log_dir: Option<PathBuf>,

    #[serde(default = "ConfigDefaults::post_limit_rfc6492")]
    pub post_limit_rfc6492: u64,

    #[serde(default = "ConfigDefaults::post_protocol_msg_timeout_seconds")]
    pub post_protocol_msg_timeout_seconds: u64,

    #[serde(default = "ConfigDefaults::rfc6492_log_dir")]
    pub rfc6492_log_dir: Option<PathBuf>,

    // RIS BGP
    #[serde(default = "ConfigDefaults::bgp_api_enabled")]
    pub bgp_api_enabled: bool,

    #[serde(default = "ConfigDefaults::bgp_api_uri")]
    pub bgp_api_uri: String,

    #[serde(
        rename = "bgp_api_cache_seconds",
        default = "ConfigDefaults::bgp_api_cache_duration",
        deserialize_with = "deserialize_seconds_duration",
    )]
    pub bgp_api_cache_duration: Duration,

    // ROA Aggregation per ASN
    #[serde(default = "ConfigDefaults::roa_aggregate_threshold")]
    pub roa_aggregate_threshold: usize,

    #[serde(default = "ConfigDefaults::roa_deaggregate_threshold")]
    pub roa_deaggregate_threshold: usize,

    #[serde(flatten)]
    pub issuance_timing: IssuanceTimingConfig,

    #[serde(flatten)]
    pub rrdp_updates_config: RrdpUpdatesConfig,

    #[serde(flatten)]
    pub metrics: MetricsConfig,

    pub testbed: Option<TestBed>,

    pub benchmark: Option<Benchmark>,

    #[serde(
        default,
        alias="timing_config"
    )]
    pub ta_timing: TaTimingConfig,
}

#[derive(Clone, Debug, Deserialize)]
pub struct IssuanceTimingConfig {
    #[serde(default = "ConfigDefaults::timing_publish_next_hours")]
    pub timing_publish_next_hours: u32,
    #[serde(default = "ConfigDefaults::timing_publish_next_jitter_hours")]
    pub timing_publish_next_jitter_hours: u32,
    #[serde(default = "ConfigDefaults::timing_publish_hours_before_next")]
    pub timing_publish_hours_before_next: u32,
    #[serde(
        default = "ConfigDefaults::timing_child_certificate_valid_weeks"
    )]
    pub timing_child_certificate_valid_weeks: u32,
    #[serde(
        default = "ConfigDefaults::timing_child_certificate_reissue_weeks_before"
    )]
    pub timing_child_certificate_reissue_weeks_before: u32,
    #[serde(default = "ConfigDefaults::timing_roa_valid_weeks")]
    pub timing_roa_valid_weeks: u32,
    #[serde(default = "ConfigDefaults::timing_roa_reissue_weeks_before")]
    pub timing_roa_reissue_weeks_before: u32,
    #[serde(default = "ConfigDefaults::timing_aspa_valid_weeks")]
    pub timing_aspa_valid_weeks: u32,
    #[serde(default = "ConfigDefaults::timing_aspa_reissue_weeks_before")]
    pub timing_aspa_reissue_weeks_before: u32,
    #[serde(default = "ConfigDefaults::timing_bgpsec_valid_weeks")]
    pub timing_bgpsec_valid_weeks: u32,
    #[serde(default = "ConfigDefaults::timing_bgpsec_reissue_weeks_before")]
    pub timing_bgpsec_reissue_weeks_before: u32,
}

impl IssuanceTimingConfig {
    //-- Publishing Manifests and CRLs

    /// Returns the next update time based on configuration:
    ///
    /// now + timing_publish_next_hours +
    /// random(0..timing_publish_next_jitter_hours) defaults: now + 24
    /// hours + 0 to 4 hours
    pub fn publish_next(&self) -> Time {
        let regular_mins = self.timing_publish_next_hours as i64 * 60;
        let random_mins = if self.timing_publish_next_jitter_hours == 0 {
            0
        } else {
            use rand::Rng;
            let mut rng = rand::rng();
            rng.random_range(0..(60 * self.timing_publish_next_jitter_hours))
        } as i64;
        Time::now() + Duration::minutes(regular_mins + random_mins)
    }

    /// Returns the number of hours before expiry that should trigger that
    /// Manifests and CRLs are re-issued.
    pub fn publish_hours_before_next(&self) -> i64 {
        self.timing_publish_hours_before_next.into()
    }

    //-- Child Cert

    /// Validity period for newly issued child certificates
    pub fn new_child_cert_validity(&self) -> Validity {
        SignSupport::sign_validity_weeks(
            self.timing_child_certificate_valid_weeks.into(),
        )
    }

    /// Not after time for newly issued child certificates
    pub fn new_child_cert_not_after(&self) -> Time {
        Time::now()
            + Duration::weeks(
                self.timing_child_certificate_valid_weeks.into(),
            )
    }

    /// Threshold time for issuing new child certificates
    ///
    /// i.e. certificates with a not after time *before* this moment should be
    /// re-issued.
    pub fn new_child_cert_issuance_threshold(&self) -> Time {
        Time::now()
            + Duration::weeks(
                self.timing_child_certificate_reissue_weeks_before.into(),
            )
    }

    //-- ROAs

    /// Validity period for new ROA objects
    pub fn new_roa_validity(&self) -> Validity {
        SignSupport::sign_validity_weeks(self.timing_roa_valid_weeks.into())
    }

    /// Threshold time for issuing new ROA objects
    ///
    /// i.e. ROA objects with a not after time *before* this moment should be
    /// re-issued.
    pub fn new_roa_issuance_threshold(&self) -> Time {
        Time::now()
            + Duration::weeks(self.timing_roa_reissue_weeks_before.into())
    }

    //-- ASPA

    /// Validity period for new ASPA objects
    pub fn new_aspa_validity(&self) -> Validity {
        SignSupport::sign_validity_weeks(self.timing_aspa_valid_weeks.into())
    }

    /// Threshold time for issuing new ASPA objects
    ///
    /// i.e. ASPA objects with a not after time *before* this moment should be
    /// re-issued.
    pub fn new_aspa_issuance_threshold(&self) -> Time {
        Time::now()
            + Duration::weeks(self.timing_aspa_reissue_weeks_before.into())
    }

    //-- BGPSec

    /// Validity period for new BGPSec router certificates
    pub fn new_bgpsec_validity(&self) -> Validity {
        SignSupport::sign_validity_weeks(
            self.timing_bgpsec_valid_weeks.into(),
        )
    }

    /// Threshold time for issuing new BGPSec router certificates
    ///
    /// i.e. certs with a not after time *before* this moment should be
    /// re-issued.
    pub fn new_bgpsec_issuance_threshold(&self) -> Time {
        Time::now()
            + Duration::weeks(self.timing_bgpsec_reissue_weeks_before.into())
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct RrdpUpdatesConfig {
    #[serde(default = "RrdpUpdatesConfig::dflt_rrdp_delta_files_min_nr")]
    pub rrdp_delta_files_min_nr: usize,
    #[serde(
        default = "RrdpUpdatesConfig::dflt_rrdp_delta_files_min_seconds"
    )]
    pub rrdp_delta_files_min_seconds: u32,
    #[serde(default = "RrdpUpdatesConfig::dflt_rrdp_delta_files_max_nr")]
    pub rrdp_delta_files_max_nr: usize,
    #[serde(
        default = "RrdpUpdatesConfig::dflt_rrdp_delta_files_max_seconds"
    )]
    pub rrdp_delta_files_max_seconds: u32,
    #[serde(
        default = "RrdpUpdatesConfig::dflt_rrdp_delta_min_interval_seconds"
    )]
    pub rrdp_delta_interval_min_seconds: u32,
    #[serde(default = "RrdpUpdatesConfig::dflt_rrdp_files_archive")]
    pub rrdp_files_archive: bool,
}

impl RrdpUpdatesConfig {
    // Keep at least X (default 5) delta files in the notification
    // file, even if they would be too old. Their impact on the notification
    // file size is not too bad.
    fn dflt_rrdp_delta_files_min_nr() -> usize {
        5
    }

    // Minimum time to keep deltas. Defaults to 20 minutes, which
    // is double a commonly used update interval, allowing the vast
    // majority of RPs to update using deltas.
    fn dflt_rrdp_delta_files_min_seconds() -> u32 {
        1200 // 20 minutes
    }

    // Maximum time to keep deltas. Defaults to two hours meaning,
    // which is double to slowest normal update interval seen used
    // by a minority of RPs.
    fn dflt_rrdp_delta_files_max_seconds() -> u32 {
        7200 // 2 hours
    }

    // For files older than the min seconds specified (default 20 mins),
    // and younger than max seconds (2 hours), keep at most up to a total
    // nr of files X (default 50).
    fn dflt_rrdp_delta_files_max_nr() -> usize {
        50
    }

    // The minimum interval between RRDP deltas. A value of 0 (default)
    // means that there will be no delays, and every change gets its
    // own delta.
    fn dflt_rrdp_delta_min_interval_seconds() -> u32 {
        0
    }

    // If set to true, we will archive - rather than delete - old
    // snapshot and delta files. The can then be backed up and/deleted
    // at the repository operator's discretion.
    fn dflt_rrdp_files_archive() -> bool {
        false
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct MetricsConfig {
    #[serde(default)] // false
    pub metrics_hide_ca_details: bool,
    #[serde(default)] // false
    pub metrics_hide_child_details: bool,
    #[serde(default)] // false
    pub metrics_hide_publisher_details: bool,
    #[serde(default)] // false
    pub metrics_hide_roa_details: bool,
}

#[derive(Clone, Debug, Deserialize)]
pub struct TestBed {
    ta_aia: uri::Rsync,
    ta_uri: uri::Https,
    rrdp_base_uri: uri::Https,
    rsync_jail: uri::Rsync,
}

impl TestBed {
    pub fn new(
        ta_aia: uri::Rsync,
        ta_uri: uri::Https,
        rrdp_base_uri: uri::Https,
        rsync_jail: uri::Rsync,
    ) -> Self {
        TestBed {
            ta_aia,
            ta_uri,
            rrdp_base_uri,
            rsync_jail,
        }
    }

    pub fn ta_aia(&self) -> &uri::Rsync {
        &self.ta_aia
    }

    pub fn ta_uri(&self) -> &uri::Https {
        &self.ta_uri
    }

    pub fn publication_server_uris(&self) -> PublicationServerUris {
        PublicationServerUris {
            rrdp_base_uri: self.rrdp_base_uri.clone(),
            rsync_jail: self.rsync_jail.clone(),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Benchmark {
    pub cas: usize,
    pub ca_roas: usize,
}

/// # Accessors
impl Config {
    /// General purpose KV store, can be used to track server settings
    /// etc not specific to any Aggregate or WalSupport type
    pub fn general_key_value_store(&self) -> KrillResult<KeyValueStore> {
        KeyValueStore::create(&self.storage_uri, PROPERTIES_NS)
            .map_err(Error::KeyValueError)
    }

    pub fn key_value_store(
        &self,
        name_space: &Namespace,
    ) -> KrillResult<KeyValueStore> {
        KeyValueStore::create(&self.storage_uri, name_space)
            .map_err(Error::KeyValueError)
    }

    /// Returns the data directory if disk was used for storage.
    /// This will always be true for upgrades of pre 0.14.0 versions
    fn data_dir(&self) -> Option<PathBuf> {
        if self.storage_uri.scheme() != "local" {
            None
        } else {
            Some(
                Path::new(&format!(
                    "{}{}",
                    self.storage_uri.host_str().unwrap_or(""),
                    self.storage_uri.path()
                ))
                .to_path_buf(),
            )
        }
    }

    pub fn tls_keys_dir(&self) -> &PathBuf {
        self.tls_keys_dir.as_ref().unwrap() // should not panic, as it is
                                            // always set
    }

    pub fn repo_dir(&self) -> &PathBuf {
        self.repo_dir.as_ref().unwrap() // should not panic, as it is always
                                        // set
    }

    fn ips(&self) -> &Vec<IpAddr> {
        &self.ip
    }

    pub fn socket_addresses(&self) -> Vec<SocketAddr> {
        self.ips()
            .iter()
            .map(|ip| SocketAddr::new(*ip, self.port))
            .collect()
    }

    pub fn https_mode(&self) -> HttpsMode {
        self.https_mode
    }

    pub fn https_cert_file(&self) -> PathBuf {
        let mut path = self.tls_keys_dir().to_path_buf();
        path.push(tls_keys::CERT_FILE);
        path
    }

    pub fn https_key_file(&self) -> PathBuf {
        let mut path = self.tls_keys_dir().to_path_buf();
        path.push(tls_keys::KEY_FILE);
        path
    }

    pub fn service_uri(&self) -> uri::Https {
        match &self.service_uri {
            None => {
                if self.ip == ConfigDefaults::ip() {
                    uri::Https::from_string(format!(
                        "https://localhost:{}/",
                        self.port
                    ))
                    .unwrap()
                } else {
                    uri::Https::from_string(format!(
                        "https://{}:{}/",
                        self.ips()[0],
                        self.port
                    ))
                    .unwrap()
                }
            }
            Some(uri) => uri.clone(),
        }
    }

    pub fn rfc8181_uri(&self, publisher: &PublisherHandle) -> uri::Https {
        uri::Https::from_string(format!(
            "{}rfc8181/{}/",
            self.service_uri(),
            publisher
        ))
        .unwrap()
    }

    pub fn pid_file(&self) -> &PathBuf {
        self.pid_file.as_ref().unwrap() // should not panic, as it is always
                                        // set
    }

    /// Returns whether TA support is explicitly enabled in the config, or
    /// implicitly enabled in case testbed (or benchmark) mode is used.
    pub fn ta_proxy_enabled(&self) -> bool {
        self.ta_support_enabled || self.testbed.is_some()
    }

    /// Returns whether TA signer is enabled.
    pub fn ta_signer_enabled(&self) -> bool {
        self.ta_signer_enabled || self.testbed.is_some()
    }

    pub fn suspend_child_after_inactive_seconds(&self) -> Option<i64> {
        match self.suspend_child_after_inactive_seconds {
            Some(seconds) => Some(seconds.into()),
            None => self
                .suspend_child_after_inactive_hours
                .map(|hours| hours as i64 * 3600),
        }
    }

    pub fn requeue_remote_failed(&self) -> Priority {
        if test_mode_enabled() {
            in_seconds(5)
        } else {
            in_seconds(SCHEDULER_REQUEUE_DELAY_SECONDS)
        }
    }

    /// Get the priority for the next CA refresh based on the configured
    /// ca_refresh_seconds (1 day), and jitter (12 hours)
    pub fn ca_refresh_next(&self) -> Priority {
        Self::ca_refresh_next_from(
            self.ca_refresh_seconds,
            self.ca_refresh_jitter_seconds,
        )
    }

    pub fn ca_refresh_start_up(&self, use_jitter: bool) -> Priority {
        let jitter_seconds = if use_jitter {
            self.ca_refresh_jitter_seconds
        } else {
            0
        };

        Self::ca_refresh_next_from(0, jitter_seconds)
    }

    fn ca_refresh_next_from(
        regular_seconds: u32,
        jitter_seconds: u32,
    ) -> Priority {
        let random_seconds = if jitter_seconds == 0 {
            0
        } else {
            use rand::Rng;
            let mut rng = rand::rng();
            rng.random_range(0..jitter_seconds)
        };

        in_seconds((regular_seconds + random_seconds).into())
    }

    pub fn testbed(&self) -> Option<&TestBed> {
        self.testbed.as_ref()
    }

    /// Returns a reference to the default signer configuration.
    ///
    /// Assumes that the configuration is valid. Will panic otherwise.
    pub fn default_signer(&self) -> &SignerConfig {
        &self.signers[self.default_signer.idx()]
    }

    /// Returns a reference to the one off signer configuration.
    ///
    /// Assumes that the configuration is valid. Will panic otherwise.
    pub fn one_off_signer(&self) -> &SignerConfig {
        &self.signers[self.one_off_signer.idx()]
    }
}

/// # Create
impl Config {
    #[cfg(test)]
    fn test_config(
        storage_uri: &Url,
        data_dir: Option<&Path>,
        enable_testbed: bool,
        enable_ca_refresh: bool,
        enable_suspend: bool,
        #[allow(unused_variables)] second_signer: bool,
    ) -> Self {
        use crate::commons::test;

        let ip = ConfigDefaults::ip();
        let port = ConfigDefaults::port();

        let https_mode = HttpsMode::Generate;

        let log_level = LevelFilter::Debug;
        let log_type = LogType::Stderr;
        let syslog_facility = ConfigDefaults::syslog_facility();
        let auth_type = AuthType::AdminToken;
        let admin_token = Token::from("secret");
        #[cfg(feature = "multi-user")]
        let auth_users = None;
        #[cfg(feature = "multi-user")]
        let auth_openidconnect = None;
        let auth_roles = ConfigDefaults::auth_roles();

        let default_signer = SignerReference::default();
        let one_off_signer = SignerReference::default();
        let signer_probe_retry_seconds =
            ConfigDefaults::signer_probe_retry_seconds();

        // Multiple signers are only needed and can only be configured when
        // the "hsm" feature is enabled.
        #[cfg(not(feature = "hsm"))]
        let second_signer = false;

        let signers = match second_signer {
            false => ConfigDefaults::signers(),
            true => vec![SignerConfig::new(
                "Second Test Signer".to_string(),
                SignerType::OpenSsl(OpenSslSignerConfig::default()),
            )],
        };

        let ca_refresh_seconds = if enable_ca_refresh { 1 } else { 86400 };
        let ca_refresh_jitter_seconds =
            if enable_ca_refresh { 0 } else { 86400 }; // no jitter in testing
        let ca_refresh_parents_batch_size = 10;
        let post_limit_api = ConfigDefaults::post_limit_api();
        let post_limit_rfc8181 = ConfigDefaults::post_limit_rfc8181();
        let post_limit_rfc6492 = ConfigDefaults::post_limit_rfc6492();
        let post_protocol_msg_timeout_seconds =
            ConfigDefaults::post_protocol_msg_timeout_seconds();

        let bgp_api_enabled = false;
        let bgp_api_uri = ConfigDefaults::bgp_api_uri();
        let bgp_api_cache_duration = ConfigDefaults::bgp_api_cache_duration();

        let roa_aggregate_threshold = 3;
        let roa_deaggregate_threshold = 2;

        let timing_publish_next_hours =
            ConfigDefaults::timing_publish_next_hours();
        let timing_publish_next_jitter_hours =
            ConfigDefaults::timing_publish_next_jitter_hours();
        let timing_publish_hours_before_next =
            ConfigDefaults::timing_publish_hours_before_next();
        let timing_child_certificate_valid_weeks =
            ConfigDefaults::timing_child_certificate_valid_weeks();
        let timing_child_certificate_reissue_weeks_before =
            ConfigDefaults::timing_child_certificate_reissue_weeks_before();
        let timing_roa_valid_weeks = ConfigDefaults::timing_roa_valid_weeks();
        let timing_roa_reissue_weeks_before =
            ConfigDefaults::timing_roa_reissue_weeks_before();
        let timing_aspa_valid_weeks =
            ConfigDefaults::timing_aspa_valid_weeks();
        let timing_aspa_reissue_weeks_before =
            ConfigDefaults::timing_aspa_reissue_weeks_before();
        let timing_bgpsec_valid_weeks =
            ConfigDefaults::timing_bgpsec_valid_weeks();
        let timing_bgpsec_reissue_weeks_before =
            ConfigDefaults::timing_bgpsec_reissue_weeks_before();

        let issuance_timing = IssuanceTimingConfig {
            timing_publish_next_hours,
            timing_publish_next_jitter_hours,
            timing_publish_hours_before_next,
            timing_child_certificate_valid_weeks,
            timing_child_certificate_reissue_weeks_before,
            timing_roa_valid_weeks,
            timing_roa_reissue_weeks_before,
            timing_aspa_valid_weeks,
            timing_aspa_reissue_weeks_before,
            timing_bgpsec_valid_weeks,
            timing_bgpsec_reissue_weeks_before,
        };

        let rrdp_updates_config = RrdpUpdatesConfig {
            rrdp_delta_files_min_seconds: 0,
            rrdp_delta_files_min_nr: 5,
            rrdp_delta_files_max_seconds: 1,
            rrdp_delta_files_max_nr: 50,
            rrdp_delta_interval_min_seconds: 0,
            rrdp_files_archive: false,
        };

        let metrics = MetricsConfig {
            metrics_hide_ca_details: false,
            metrics_hide_child_details: false,
            metrics_hide_publisher_details: false,
            metrics_hide_roa_details: false,
        };

        let testbed = if enable_testbed {
            Some(TestBed::new(
                test::rsync("rsync://localhost/ta/ta.cer"),
                test::https(&format!("https://localhost:{port}/ta/ta.cer")),
                test::https(&format!("https://localhost:{port}/rrdp/")),
                test::rsync("rsync://localhost/repo/"),
            ))
        } else {
            None
        };

        let suspend_child_after_inactive_seconds =
            if enable_suspend { Some(3) } else { None };

        Config {
            ip,
            port,
            https_mode,
            storage_uri: storage_uri.clone(),
            use_history_cache: false,
            tls_keys_dir: data_dir.map(|d| d.join(HTTPS_SUB_DIR)),
            repo_dir: data_dir.map(|d| d.join(REPOSITORY_DIR)),
            ta_support_enabled: false, /* but, enabled by testbed where
                                        * applicable */
            ta_signer_enabled: false, // same as above
            pid_file: data_dir.map(|d| d.join("krill.pid")),
            service_uri: None,
            log_level,
            log_type,
            log_file: None,
            syslog_facility,
            admin_token,
            auth_type,
            #[cfg(feature = "multi-user")]
            auth_users,
            #[cfg(feature = "multi-user")]
            auth_openidconnect,
            auth_roles,
            default_signer,
            one_off_signer,
            signers,
            signer_probe_retry_seconds,
            ca_refresh_seconds,
            ca_refresh_jitter_seconds,
            ca_refresh_parents_batch_size,
            suspend_child_after_inactive_seconds,
            suspend_child_after_inactive_hours: None,
            post_limit_api,
            post_limit_rfc8181,
            rfc8181_log_dir: None,
            post_limit_rfc6492,
            rfc6492_log_dir: None,
            post_protocol_msg_timeout_seconds,
            bgp_api_enabled,
            bgp_api_uri,
            bgp_api_cache_duration,
            roa_aggregate_threshold,
            roa_deaggregate_threshold,
            issuance_timing,
            rrdp_updates_config,
            metrics,
            testbed,
            benchmark: None,
            ta_timing: TaTimingConfig::default(),
        }
    }

    #[cfg(test)]
    pub fn test(
        test_storage: &Url,
        test_dir: Option<&Path>,
        enable_testbed: bool,
        enable_ca_refresh: bool,
        enable_suspend: bool,
        second_signer: bool,
    ) -> Self {
        let mut cfg = Self::test_config(
            test_storage,
            test_dir,
            enable_testbed,
            enable_ca_refresh,
            enable_suspend,
            second_signer,
        );
        cfg.process().unwrap();
        cfg
    }

    #[cfg(test)]
    pub fn pubd_test(storage_uri: &Url, data_dir: Option<&Path>) -> Self {
        let mut config = Self::test_config(
            storage_uri,
            data_dir,
            false,
            false,
            false,
            false,
        );
        config.port = 3001;
        config
    }

    /// Creates the config (at startup).
    pub fn create(
        config_file: &Path,
        upgrade_only: bool,
    ) -> Result<Self, ConfigError> {
        let mut config = Self::read_config(config_file)?;

        if upgrade_only {
            config.log_type = LogType::Stderr;
        }

        config.init_logging()?;

        if upgrade_only {
            info!(
                "Prepare upgrade using configuration file: {}",
                config_file.display(),
            );
            info!("Processing data from: {}", config.storage_uri);
        } else {
            info!(
                "{} uses configuration file: {}",
                KRILL_SERVER_APP, config_file.display()
            );
        }

        config.process().map_err(|e| {
            ConfigError::Other(format!(
                "Error parsing config file: {}, error: {}",
                config_file.display(), e
            ))
        })?;

        Ok(config)
    }

    pub fn process(&mut self) -> Result<(), ConfigError> {
        self.fix()?;
        self.verify()?;
        self.resolve();
        Ok(())
    }

    fn fix(&mut self) -> Result<(), ConfigError> {
        if self.ca_refresh_seconds < CA_REFRESH_SECONDS_MIN {
            warn!(
                "The value for 'ca_refresh_seconds' was below the minimum value, changing it to {CA_REFRESH_SECONDS_MIN} seconds"
            );
            self.ca_refresh_seconds = CA_REFRESH_SECONDS_MIN;
        }

        if self.ca_refresh_seconds > CA_REFRESH_SECONDS_MAX {
            warn!(
                "The value for 'ca_refresh_seconds' was above the maximum value, changing it to {CA_REFRESH_SECONDS_MAX} seconds"
            );
            self.ca_refresh_seconds = CA_REFRESH_SECONDS_MAX;
        }

        if self.tls_keys_dir.is_none() {
            if let Some(mut data_dir) = self.data_dir() {
                data_dir.push(HTTPS_SUB_DIR);
                self.tls_keys_dir = Some(data_dir);
            } else {
                return Err(ConfigError::other("'tls_keys_dir' is not configured, but 'storage_uri' is not a local directory, please configure an 'tls_keys_dir'"));
            }
        }

        if self.repo_dir.is_none() {
            if let Some(mut data_dir) = self.data_dir() {
                data_dir.push(REPOSITORY_DIR);
                self.repo_dir = Some(data_dir);
            } else {
                return Err(ConfigError::other("'repo_dir' is not configured, but 'storage_uri' is not a local directory, please configure an 'repo_dir'"));
            }
        }

        if self.pid_file.is_none() {
            if let Some(mut data_dir) = self.data_dir() {
                data_dir.push("krill.pid");
                self.pid_file = Some(data_dir);
            } else {
                return Err(ConfigError::other("'pid_file' is not configured, but 'storage_uri' is not a local directory, please configure an 'pid_file'"));
            }
        }

        let half_refresh = self.ca_refresh_seconds / 2;

        if self.ca_refresh_jitter_seconds > half_refresh {
            warn!("The value for 'ca_refresh_jitter_seconds' exceeded 50% of 'ca_refresh_seconds'. Changing it to {half_refresh} seconds");
            self.ca_refresh_jitter_seconds = half_refresh;
        }

        Ok(())
    }

    fn resolve(&mut self) {
        if self.signers.len() == 1 && !self.default_signer.is_named() {
            self.default_signer = SignerReference::new(&self.signers[0].name);
        }

        let default_signer_idx =
            self.find_signer_reference(&self.default_signer).unwrap();
        self.default_signer = SignerReference::Index(default_signer_idx);

        let openssl_signer_idx = self.find_openssl_signer();
        let one_off_signer_idx =
            self.find_signer_reference(&self.one_off_signer);

        // Use the specified one-off signer, if set, else:
        //   - Use an existing OpenSSL signer config,
        //   - Or create a new OpenSSL signer config.
        let one_off_signer_idx =
            match (one_off_signer_idx, openssl_signer_idx) {
                (Some(one_off_signer_idx), _) => one_off_signer_idx,
                (None, Some(openssl_signer_idx)) => openssl_signer_idx,
                (None, None) => {
                    self.add_openssl_signer(OPENSSL_ONE_OFF_SIGNER_NAME)
                }
            };

        self.one_off_signer = SignerReference::Index(one_off_signer_idx);
    }

    fn add_openssl_signer(&mut self, name: &str) -> usize {
        let signer_config = SignerConfig::new(
            name.to_string(),
            SignerType::OpenSsl(OpenSslSignerConfig::default()),
        );
        self.signers.push(signer_config);
        self.signers.len() - 1
    }

    fn find_signer_reference(
        &self,
        signer_ref: &SignerReference,
    ) -> Option<usize> {
        match signer_ref {
            SignerReference::Name(None) => None,
            SignerReference::Name(Some(name)) => {
                self.signers.iter().position(|s| &s.name == name)
            }
            SignerReference::Index(idx) => Some(*idx),
        }
    }

    fn find_openssl_signer(&self) -> Option<usize> {
        self.signers
            .iter()
            .position(|s| matches!(s.signer_type, SignerType::OpenSsl(_)))
    }

    fn verify(&self) -> Result<(), ConfigError> {
        if env::var(KRILL_ENV_ADMIN_TOKEN_DEPRECATED).is_ok() {
            warn!("The environment variable for setting the admin token has been updated from '{KRILL_ENV_ADMIN_TOKEN_DEPRECATED}' to '{KRILL_ENV_ADMIN_TOKEN}', please update as the old value may not be supported in future releases")
        }

        if self.port < 1024 {
            return Err(ConfigError::other("Port number must be >1024"));
        }

        if let Some(service_uri) = &self.service_uri {
            if !service_uri.as_str().ends_with('/') {
                return Err(ConfigError::other(
                    "service URI must end with '/'",
                ));
            } else if service_uri.as_str().matches('/').count() != 3 {
                return Err(ConfigError::other(
                    "Service URI MUST specify a host name only, e.g. https://rpki.example.com:3000/",
                ));
            }
        }

        if self.issuance_timing.timing_publish_next_hours < 2 {
            return Err(ConfigError::other(
                "timing_publish_next_hours must be at least 2",
            ));
        }

        if self.issuance_timing.timing_publish_next_jitter_hours
            > (self.issuance_timing.timing_publish_next_hours / 2)
        {
            return Err(ConfigError::other(
                "timing_publish_next_jitter_hours must be at most timing_publish_next_hours divided by 2",
            ));
        }

        if self.issuance_timing.timing_publish_hours_before_next < 1 {
            return Err(ConfigError::other(
                "timing_publish_hours_before_next must be at least 1",
            ));
        }

        if self.issuance_timing.timing_publish_hours_before_next
            >= self.issuance_timing.timing_publish_next_hours
        {
            return Err(ConfigError::other(
                "timing_publish_hours_before_next must be smaller than timing_publish_hours",
            ));
        }

        if self.issuance_timing.timing_child_certificate_valid_weeks < 2 {
            return Err(ConfigError::other(
                "timing_child_certificate_valid_weeks must be at least 2",
            ));
        }

        if self
            .issuance_timing
            .timing_child_certificate_reissue_weeks_before
            < 1
        {
            return Err(ConfigError::other(
                "timing_child_certificate_reissue_weeks_before must be at least 1",
            ));
        }

        if self
            .issuance_timing
            .timing_child_certificate_reissue_weeks_before
            >= self.issuance_timing.timing_child_certificate_valid_weeks
        {
            return Err(ConfigError::other("timing_child_certificate_reissue_weeks_before must be smaller than timing_child_certificate_valid_weeks"));
        }

        if self.issuance_timing.timing_roa_valid_weeks < 2 {
            return Err(ConfigError::other(
                "timing_roa_valid_weeks must be at least 2",
            ));
        }

        if self.issuance_timing.timing_roa_reissue_weeks_before < 1 {
            return Err(ConfigError::other(
                "timing_roa_reissue_weeks_before must be at least 1",
            ));
        }

        if self.issuance_timing.timing_roa_reissue_weeks_before
            >= self.issuance_timing.timing_roa_valid_weeks
        {
            return Err(ConfigError::other(
                "timing_roa_reissue_weeks_before must be smaller than timing_roa_valid_week",
            ));
        }

        if let Some(threshold) = self.suspend_child_after_inactive_hours {
            if threshold < CA_SUSPEND_MIN_HOURS {
                return Err(ConfigError::Other(format!(
                    "suspend_child_after_inactive_hours must be {CA_SUSPEND_MIN_HOURS} or higher (or not set at all)"
                )));
            }
        }

        if let Some(benchmark) = &self.benchmark {
            if self.testbed.is_none() {
                return Err(ConfigError::other(
                    "[benchmark] section requires [testbed] config",
                ));
            }
            if benchmark.cas > 65535 {
                return Err(ConfigError::other(
                    "[benchmark] allows only up to 65536 CAs",
                ));
            }
            if benchmark.ca_roas > 100 {
                return Err(ConfigError::other(
                    "[benchmark] allows only up to 100 ROAs per CA",
                ));
            }
        }

        if self.signers.is_empty() {
            // Since Config.signers defaults via Serde to
            // ConfigDefaults::signers() which creates a vector with a
            // single signer, this can only happen if we were invoked on a
            // config object created or modified by test code.
            return Err(ConfigError::Other(
                "No signers configured".to_string(),
            ));
        }

        #[cfg(not(feature = "hsm"))]
        {
            fn mk_err_msg(setting_name: &str) -> String {
                format!("This build of Krill lacks support for the '{}' config file setting. Please use a version of Krill that has the 'hsm' feature enabled.", setting_name)
            }

            if self.default_signer.is_named() {
                return Err(ConfigError::other(&mk_err_msg(
                    "default_signer",
                )));
            }
            if self.one_off_signer.is_named() {
                return Err(ConfigError::other(&mk_err_msg(
                    "one_off_signer",
                )));
            }
            if self.signers != ConfigDefaults::signers() {
                return Err(ConfigError::other(&mk_err_msg("[[signers]]")));
            }
        }

        for n in &self.signers {
            if self.signers.iter().filter(|m| m.name == n.name).count() > 1 {
                return Err(ConfigError::other(&format!(
                    "Signer name '{}' is not unique",
                    n.name
                )));
            }
        }

        if self.signers.len() > 1 && !self.default_signer.is_set() {
            return Err(ConfigError::other(
                "'default_signer' must be set when more than one [[signers]] configuration is defined",
            ));
        }

        if self.default_signer.is_named()
            && self.find_signer_reference(&self.default_signer).is_none()
        {
            return Err(ConfigError::other(&format!(
                "'{}' cannot be used as the 'default_signer' as no signer with that name is defined",
                self.default_signer.name()
            )));
        }

        if self.one_off_signer.is_named()
            && self.find_signer_reference(&self.one_off_signer).is_none()
        {
            return Err(ConfigError::other(&format!(
                "'{}' cannot be used as the 'one_off_signer' as no signer with that name is defined",
                self.one_off_signer.name()
            )));
        }

        Ok(())
    }

    pub fn read_config(file: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let file = file.as_ref();
        let mut v = String::new();
        let mut f = File::open(file).map_err(|e| {
            KrillIoError::new(
                format!(
                    "Could not read config file '{}'. Note: you may want to override the default location using --config <path>",
                    file.display()
                ),
                e,
            )
        })?;
        f.read_to_string(&mut v).map_err(|e| {
            KrillIoError::new(
                format!("Could not read config file '{}'", file.display()),
                e,
            )
        })?;

        toml::from_str(&v).map_err(|e| {
            ConfigError::Other(format!(
                "Error parsing config file: {}, error: {}",
                file.display(), e
            ))
        })
    }

    pub fn init_logging(&self) -> Result<(), ConfigError> {
        match self.log_type {
            LogType::File => self.file_logger(),
            LogType::Stderr => self.stderr_logger(),
            LogType::Syslog => {
                let facility = Facility::from_str(&self.syslog_facility)
                    .map_err(|_| {
                        ConfigError::other("Invalid syslog_facility")
                    })?;
                self.syslog_logger(facility)
            }
        }
    }

    /// Creates a stderr logger.
    fn stderr_logger(&self) -> Result<(), ConfigError> {
        self.fern_logger().chain(io::stderr()).apply().map_err(|e| {
            ConfigError::Other(format!(
                "Failed to init stderr logging: {e}"
            ))
        })
    }

    /// Creates a file logger using the file provided by `path`.
    fn file_logger(&self) -> Result<(), ConfigError> {
        let path = self.log_file.as_ref().ok_or(ConfigError::Other(
            "log_file not configured with log_type = \"file\"".to_owned(),
        ))?;

        let file = match fern::log_file(path) {
            Ok(file) => file,
            Err(err) => {
                let error_string = format!(
                    "Failed to open log file '{}': {}",
                    path.display(),
                    err
                );
                error!("{}", error_string.as_str());
                return Err(ConfigError::Other(error_string));
            }
        };
        self.fern_logger().chain(file).apply().map_err(|e| {
            ConfigError::Other(format!("Failed to init file logging: {e}"))
        })
    }

    /// Creates a syslog logger and configures correctly.
    #[cfg(unix)]
    fn syslog_logger(
        &self,
        facility: syslog::Facility,
    ) -> Result<(), ConfigError> {
        let process = env::current_exe()
            .ok()
            .and_then(|path| {
                path.file_name()
                    .and_then(std::ffi::OsStr::to_str)
                    .map(ToString::to_string)
            })
            .unwrap_or_else(|| String::from("krill"));
        let formatter = syslog::Formatter3164 {
            facility,
            hostname: None,
            process,
            pid: std::process::id(),
        };
        let logger = syslog::unix(formatter.clone())
            .or_else(|_| syslog::tcp(formatter.clone(), ("127.0.0.1", 601)))
            .or_else(|_| {
                syslog::udp(formatter, ("127.0.0.1", 0), ("127.0.0.1", 514))
            });
        match logger {
            Ok(logger) => {
                self.fern_logger().chain(logger).apply().map_err(|e| {
                    ConfigError::Other(format!(
                        "Failed to init syslog: {e}"
                    ))
                })
            }
            Err(err) => {
                let msg = format!("Cannot connect to syslog: {err}");
                Err(ConfigError::Other(msg))
            }
        }
    }

    /// Creates and returns a fern logger with log level tweaks
    fn fern_logger(&self) -> fern::Dispatch {
        // suppress overly noisy logging
        let framework_level = self.log_level.min(LevelFilter::Warn);
        let krill_framework_level = self.log_level.min(LevelFilter::Debug);

        // disable Oso logging unless the Oso specific POLAR_LOG environment
        // variable is set, it's too noisy otherwise
        let oso_framework_level = if env::var("POLAR_LOG").is_ok() {
            self.log_level.min(LevelFilter::Trace)
        } else {
            self.log_level.min(LevelFilter::Info)
        };

        let show_target = self.log_level == LevelFilter::Trace
            || self.log_level == LevelFilter::Debug;
        fern::Dispatch::new()
            .format(move |out, message, record| {
                if show_target {
                    out.finish(format_args!(
                        "{} [{}] [{}] {}",
                        chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
                        record.level(),
                        record.target(),
                        message
                    ))
                } else {
                    out.finish(format_args!(
                        "{} [{}] {}",
                        chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
                        record.level(),
                        message
                    ))
                }
            })
            .level(self.log_level)
            .level_for("rustls", framework_level)
            .level_for("hyper", framework_level)
            .level_for("mio", framework_level)
            .level_for("reqwest", framework_level)
            .level_for("tokio_reactor", framework_level)
            .level_for("tokio_util::codec::framed_read", framework_level)
            .level_for("want", framework_level)
            .level_for("tracing::span", framework_level)
            .level_for("h2", framework_level)
            .level_for("oso", oso_framework_level)
            .level_for("krill::commons::eventsourcing", krill_framework_level)
            .level_for("krill::commons::util::file", krill_framework_level)
    }
}

#[derive(Debug)]
pub enum ConfigError {
    IoError(KrillIoError),
    TomlError(toml::de::Error),
    RpkiUriError(uri::Error),
    Other(String),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ConfigError::IoError(e) => e.fmt(f),
            ConfigError::TomlError(e) => e.fmt(f),
            ConfigError::RpkiUriError(e) => e.fmt(f),
            ConfigError::Other(s) => s.fmt(f),
        }
    }
}

impl ConfigError {
    pub fn other(s: &str) -> ConfigError {
        ConfigError::Other(s.to_string())
    }
}

impl From<KrillIoError> for ConfigError {
    fn from(e: KrillIoError) -> Self {
        ConfigError::IoError(e)
    }
}

impl From<toml::de::Error> for ConfigError {
    fn from(e: toml::de::Error) -> Self {
        ConfigError::TomlError(e)
    }
}

impl From<uri::Error> for ConfigError {
    fn from(e: uri::Error) -> Self {
        ConfigError::RpkiUriError(e)
    }
}

//------------ LogType -------------------------------------------------------

/// The target to log to.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LogType {
    Stderr,
    File,
    Syslog,
}

impl FromStr for LogType {
    type Err = String;

    fn from_str(log_type: &str) -> Result<LogType, Self::Err> {
        match log_type {
            "stderr" => Ok(LogType::Stderr),
            "file" => Ok(LogType::File),
            "syslog" => Ok(LogType::Syslog),
            _ => Err(format!(
                "expected \"stderr\", \"file\" or \"syslog\", found : \"{log_type}\""
            )),
        }
    }
}

impl<'de> Deserialize<'de> for LogType {
    fn deserialize<D>(d: D) -> Result<LogType, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(d)?;
        LogType::from_str(string.as_str()).map_err(de::Error::custom)
    }
}

//------------ HttpsMode -----------------------------------------------------

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HttpsMode {
    Existing,
    Generate,
    Disable,
}

impl HttpsMode {
    pub fn is_generate_https_cert(&self) -> bool {
        *self == HttpsMode::Generate
    }

    pub fn is_disable_https(&self) -> bool {
        *self == HttpsMode::Disable
    }
}

impl<'de> Deserialize<'de> for HttpsMode {
    fn deserialize<D>(d: D) -> Result<HttpsMode, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(d)?;
        match string.as_str() {
            "existing" => Ok(HttpsMode::Existing),
            "generate" => Ok(HttpsMode::Generate),
            "disable" => Ok(HttpsMode::Disable),
            _ => Err(de::Error::custom(format!(
                "expected \"existing\", \"generate\", or \"disable\" found: \"{string}\""
            ))),
        }
    }
}

//------------ AuthType -----------------------------------------------------

/// The target to log to.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuthType {
    AdminToken,
    #[cfg(feature = "multi-user")]
    ConfigFile,
    #[cfg(feature = "multi-user")]
    OpenIDConnect,
}

impl<'de> Deserialize<'de> for AuthType {
    fn deserialize<D>(d: D) -> Result<AuthType, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(d)?;
        match string.as_str() {
            "admin-token" => Ok(AuthType::AdminToken),
            #[cfg(feature = "multi-user")]
            "config-file" => Ok(AuthType::ConfigFile),
            #[cfg(feature = "multi-user")]
            "openid-connect" => Ok(AuthType::OpenIDConnect),
            _ => {
                #[cfg(not(feature = "multi-user"))]
                let msg = format!(
                    "expected \"admin-token\", found: \"{}\"",
                    string
                );
                #[cfg(feature = "multi-user")]
                let msg = format!(
                    "expected \"config-file\", \"admin-token\", or \"openid-connect\", found: \"{string}\""
                );
                Err(de::Error::custom(msg))
            }
        }
    }
}

//------------ Signers -----------------------------------------------------

// Supports TOML such as:
//
//   default_signer = "<signer name>"   # optional
//   one_off_signer = "<signer name>"   # optional
//
//   [[signers]]
//   name = "My PKCS#11 signer"
//   type = "PKCS#11"
//   lib_path = "/path/to/pkcs11.so"
//   ...
//
//   [[signers]]
//   name = "My OpenSSL Signer"
//   type = "OpenSSL"
//
//   [[signers]]
//   name = "My KMIP Signer"
//   type = "KMIP"
//   host = "example.com"
//   ...
//
//   # Multiple signers of the same type are supported
//   [[signers]]
//   name = "My Other KMIP Signer"
//   type = "KMIP"
//   ...

#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct SignerConfig {
    /// A friendly name for the signer. Used to identify the signer with the
    /// `default_signer` and `one_off_signer` settings.
    pub name: String,

    /// Signer specific configuration settings.
    #[serde(flatten)]
    pub signer_type: SignerType,
}

#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum SignerType {
    #[serde(alias = "OpenSSL")]
    OpenSsl(OpenSslSignerConfig),

    #[cfg(feature = "hsm")]
    #[serde(alias = "PKCS#11")]
    Pkcs11(Pkcs11SignerConfig),

    #[cfg(feature = "hsm")]
    #[serde(alias = "KMIP")]
    Kmip(KmipSignerConfig),
}

impl std::fmt::Display for SignerType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SignerType::OpenSsl(_) => f.write_str("OpenSSL"),

            #[cfg(feature = "hsm")]
            SignerType::Pkcs11(_) => f.write_str("PKCS#11"),

            #[cfg(feature = "hsm")]
            SignerType::Kmip(_) => f.write_str("KMIP"),
        }
    }
}

impl SignerConfig {
    pub fn new(name: String, signer_type: SignerType) -> SignerConfig {
        Self { name, signer_type }
    }
}


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

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

    fn assert_err_msg(
        res: Result<Config, ConfigError>,
        expected_err_msg: &str,
    ) {
        if let Err(ConfigError::Other(msg)) = res {
            assert_eq!(msg, expected_err_msg);
        } else {
            panic!(
                "Expected error '{expected_err_msg}' but got: {res:?}"
            );
        }
    }

    #[test]
    fn should_parse_default_config_file() {
        // Config for auth token is required! If there is nothing in the conf
        // file, then an environment variable must be set.
        //
        // Safety: Not really.
        unsafe { env::set_var(KRILL_ENV_ADMIN_TOKEN, "secret"); }

        let c = Config::read_config("./defaults/krill.conf").unwrap();
        let expected_socket_addresses: Vec<SocketAddr> =
            vec![([127, 0, 0, 1], 3000).into()];
        assert_eq!(c.socket_addresses(), expected_socket_addresses);
        assert!(c.testbed().is_none());
    }

    #[test]
    fn should_parse_testbed_config_file() {
        // Config for auth token is required! If there is nothing in the conf
        // file, then an environment variable must be set.
        //
        // Safety: Not really.
        unsafe { env::set_var(KRILL_ENV_ADMIN_TOKEN, "secret"); }

        let c = Config::read_config("./defaults/krill-testbed.conf").unwrap();

        let testbed = c.testbed().unwrap();
        assert_eq!(
            testbed.ta_aia(),
            &test::rsync("rsync://testbed.example.com/ta/ta.cer")
        );
        assert_eq!(
            testbed.ta_uri(),
            &test::https("https://testbed.example.com/ta/ta.cer")
        );

        let uris = testbed.publication_server_uris();
        assert_eq!(
            uris.rrdp_base_uri,
            test::https("https://testbed.example.com/rrdp/")
        );
        assert_eq!(
            uris.rsync_jail,
            test::rsync("rsync://testbed.example.com/repo/")
        );
    }

    #[test]
    fn should_set_correct_log_levels() {
        use log::Level as LL;

        fn void_logger_from_krill_config(config: &str) -> Box<dyn log::Log> {
            let c: Config = toml::from_str(config).unwrap();
            let void_output = fern::Output::writer(Box::new(io::sink()), "");
            let (_, void_logger) =
                c.fern_logger().chain(void_output).into_log();
            void_logger
        }

        fn for_target_at_level(target: &str, level: LL) -> log::Metadata<'_> {
            log::Metadata::builder().target(target).level(level).build()
        }

        fn should_logging_be_enabled_at_this_krill_config_log_level(
            log_level: &LL,
            config_level: &str,
        ) -> bool {
            let log_level_from_krill_config_level =
                LL::from_str(config_level).unwrap();
            log_level <= &log_level_from_krill_config_level
        }

        // Krill requires an auth token to be defined, give it one in the
        // environment
        //
        // Safety: Not really.
        unsafe {env::set_var(KRILL_ENV_ADMIN_TOKEN, "secret"); }

        // Define sets of log targets aka components of Krill that we want to
        // test log settings for, based on the rules & exceptions that
        // the actual code under test is supposed to configure the logger with
        let krill_components = vec!["krill"];
        let krill_framework_components = vec![
            "krill::commons::eventsourcing",
            "krill::commons::util::file",
        ];
        let other_key_components = vec!["hyper", "reqwest", "oso"];

        let krill_key_components =
            vec![krill_components, krill_framework_components.clone()]
                .into_iter()
                .flatten()
                .collect::<Vec<_>>();
        let all_key_components =
            vec![krill_key_components.clone(), other_key_components]
                .into_iter()
                .flatten()
                .collect::<Vec<_>>();

        //
        // Test that important log levels are enabled for all key components
        //

        // for each important Krill config log level
        for config_level in &["error", "warn"] {
            // build a logger for that config
            let log = void_logger_from_krill_config(&format!(
                r#"log_level = "{config_level}""#
            ));

            // for all log levels
            for log_msg_level in
                &[LL::Error, LL::Warn, LL::Info, LL::Debug, LL::Trace]
            {
                // determine if logging should be enabled or not
                let should_be_enabled =
                    should_logging_be_enabled_at_this_krill_config_log_level(
                        log_msg_level,
                        config_level,
                    );

                // for each Krill component we want to pretend to log as
                for component in &all_key_components {
                    // verify that logging is enabled or not as expected
                    assert_eq!(
                        should_be_enabled,
                        log.enabled(&for_target_at_level(component, *log_msg_level)),
                        // output an easy to understand test failure description
                        "Logging at level {} with log_level={} should be {} for component {}",
                        log_msg_level,
                        config_level,
                        if should_be_enabled { "enabled" } else { "disabled" },
                        component
                    );
                }
            }
        }

        //
        // Test that info level and below are only enabled for Krill at the
        // right log levels
        //

        // for each Krill config log level we want to test
        for config_level in &["info", "debug", "trace"] {
            // build a logger for that config
            let log = void_logger_from_krill_config(&format!(
                r#"log_level = "{config_level}""#
            ));

            // for each level of interest that messages could be logged at
            for log_msg_level in &[LL::Info, LL::Debug, LL::Trace] {
                // determine if logging should be enabled or not
                let should_be_enabled =
                    should_logging_be_enabled_at_this_krill_config_log_level(
                        log_msg_level,
                        config_level,
                    );

                // for each Krill component we want to pretend to log as
                for component in &krill_key_components {
                    // framework components shouldn't log at Trace level
                    let should_be_enabled = should_be_enabled
                        && (*log_msg_level < LL::Trace
                            || !krill_framework_components
                                .contains(component));

                    // verify that logging is enabled or not as expected
                    assert_eq!(
                        should_be_enabled,
                        log.enabled(&for_target_at_level(component, *log_msg_level)),
                        // output an easy to understand test failure description
                        "Logging at level {} with log_level={} should be {} for component {}",
                        log_msg_level,
                        config_level,
                        if should_be_enabled { "enabled" } else { "disabled" },
                        component
                    );
                }
            }
        }
    }

    fn parse_and_process_config_str(
        config_str: &str,
    ) -> Result<Config, ConfigError> {
        let mut c: Config = toml::from_str(config_str).unwrap();
        c.process()?;
        Ok(c)
    }

    #[test]
    fn config_should_accept_and_warn_about_auth_token() {
        let old_config = r#"auth_token = "secret""#;
        let c = parse_and_process_config_str(old_config).unwrap();
        assert_eq!(c.admin_token.as_ref(), "secret");
    }

    #[test]
    fn parse_single_ip() {
        let config_str = r#"
            auth_token = "secret"
            ip         = "127.0.0.1"
        "#;

        parse_and_process_config_str(config_str).unwrap();
    }

    #[test]
    fn parse_multiple_ips() {
        let config_str = r#"
            auth_token = "secret"
            ip         =  [ "127.0.0.1", "::1" ]
        "#;

        parse_and_process_config_str(config_str).unwrap();
    }

    #[cfg(not(feature = "hsm"))]
    #[test]
    fn should_fail_when_config_defines_signers_but_hsm_support_is_not_enabled(
    ) {
        fn assert_unexpected_setting_err(
            res: Result<Config, ConfigError>,
            setting_name: &str,
        ) {
            let expected_err_msg = format!("This build of Krill lacks support for the '{}' config file setting. Please use a version of Krill that has the 'hsm' feature enabled.", setting_name);
            assert_err_msg(res, &expected_err_msg);
        }

        let config_str = r#"
            auth_token = "secret"

            [[signers]]
            type = "OpenSSL"
            name = "Signer 1"
        "#;

        let res = parse_and_process_config_str(config_str);
        assert_unexpected_setting_err(res, "[[signers]]");

        // ---

        let config_str = r#"
            auth_token = "secret"
            default_signer = "Signer 1"

            [[signers]]
            type = "OpenSSL"
            name = "Signer 1"
        "#;

        let res = parse_and_process_config_str(config_str);
        assert_unexpected_setting_err(res, "default_signer");

        // ---

        let config_str = r#"
            auth_token = "secret"
            one_off_signer = "Signer 1"

            [[signers]]
            type = "OpenSSL"
            name = "Signer 1"
        "#;

        let res = parse_and_process_config_str(config_str);
        assert_unexpected_setting_err(res, "one_off_signer");
    }

    #[cfg(feature = "hsm")]
    #[test]
    fn should_fail_with_multiple_signers_and_no_default_signer() {
        let config_str = r#"
            auth_token = "secret"

            [[signers]]
            type = "OpenSSL"
            name = "Signer 1"

            [[signers]]
            type = "OpenSSL"
            name = "Signer 2"
        "#;

        let res = parse_and_process_config_str(config_str);
        assert_err_msg(
            res,
            "'default_signer' must be set when more than one [[signers]] configuration is defined",
        );
    }

    #[cfg(feature = "hsm")]
    #[test]
    fn should_fail_if_referenced_signer_is_not_defined() {
        let config_str = r#"
            auth_token = "secret"
            default_signer = "Unknown Signer"
        "#;

        let res = parse_and_process_config_str(config_str);
        assert_err_msg(
            res,
            "'Unknown Signer' cannot be used as the 'default_signer' as no signer with that name is defined",
        );

        // ---

        let config_str = r#"
            auth_token = "secret"
            one_off_signer = "Unknown Signer"
        "#;

        let res = parse_and_process_config_str(config_str);
        assert_err_msg(
            res,
            "'Unknown Signer' cannot be used as the 'one_off_signer' as no signer with that name is defined",
        );
    }

    #[test]
    #[ignore = "see issue #821"]
    fn should_use_the_expected_default_signer() {
        let config_str = r#"
            auth_token = "secret"
        "#;

        let c = parse_and_process_config_str(config_str).unwrap();

        #[cfg(not(any(
            feature = "hsm-tests-kmip",
            feature = "hsm-tests-pkcs11"
        )))]
        {
            assert_eq!(c.signers.len(), 1);
            assert_eq!(c.signers[0].name, "Default OpenSSL signer");
            assert!(matches!(
                c.signers[0].signer_type,
                SignerType::OpenSsl(_)
            ));
        }

        #[cfg(feature = "hsm-tests-kmip")]
        {
            assert_eq!(c.signers.len(), 2);
            assert_eq!(c.signers[0].name, "(test mode) Default KMIP signer");
            assert!(matches!(c.signers[0].signer_type, SignerType::Kmip(_)));
            assert_eq!(c.signers[1].name, "OpenSSL one-off signer");
            assert!(matches!(
                c.signers[1].signer_type,
                SignerType::OpenSsl(_)
            ));
        }

        #[cfg(feature = "hsm-tests-pkcs11")]
        {
            assert_eq!(c.signers.len(), 2);
            assert_eq!(
                c.signers[0].name,
                "(test mode) Default PKCS#11 signer"
            );
            assert!(matches!(
                c.signers[0].signer_type,
                SignerType::Pkcs11(_)
            ));
            assert_eq!(c.signers[1].name, "OpenSSL one-off signer");
            assert!(matches!(
                c.signers[1].signer_type,
                SignerType::OpenSsl(_)
            ));
        }
    }

    #[cfg(feature = "hsm")]
    #[test]
    fn should_fail_if_signer_name_is_not_unique() {
        let config_str = r#"
            auth_token = "secret"
            
            [[signers]]
            type = "OpenSSL"
            name = "Blah"

            [[signers]]
            type = "OpenSSL"
            name = "Blah"
        "#;

        let res = parse_and_process_config_str(config_str);
        assert_err_msg(res, "Signer name 'Blah' is not unique");
    }

    #[test]
    fn data_dir_for_storage() {
        fn test_uri(uri: &str, expected_path: &str) {
            let storage_uri = Url::parse(uri).unwrap();
            let config = Config::test_config(
                &storage_uri,
                None,
                false,
                false,
                false,
                false,
            );

            let expected_path = PathBuf::from(expected_path);
            assert_eq!(config.data_dir().unwrap(), expected_path);
        }

        test_uri("local:///tmp/test", "/tmp/test");
        test_uri("local://./data", "./data");
        test_uri("local://data", "data");
        test_uri("local://data/test", "data/test");
        test_uri("local:///tmp/test", "/tmp/test");
    }
}