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
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
// SPDX-FileCopyrightText: 2024 David Runge <dvzrv@archlinux.org>
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! A high-level library to interact with the API of a [Nitrokey NetHSM](https://docs.nitrokey.com/nethsm/)
//!
//! Provides high-level integration with a Nitrokey NetHSM and official container.
//! As this crate is a wrapper around [`nethsm_sdk_rs`] it covers all available actions from
//! provisioning, over key and user management to backup and restore.
//!
//! The NetHSM provides dedicated [user management](https://docs.nitrokey.com/nethsm/administration#user-management)
//! based on several roles (see [`UserRole`]) which can be used to separate concerns.
//!
//! The cryptographic key material on the device can be assigned to one or several [tags](https://docs.nitrokey.com/nethsm/operation#tags-for-keys).
//! Users in the "operator" role can be assigned to the same [tags](https://docs.nitrokey.com/nethsm/administration#tags-for-users)
//! to gain access to the keys.
//!
//! Apart from the crate specific documentation it is very recommended to read the canonical
//! upstream documentation as well: <https://docs.nitrokey.com/nethsm/>
//!
//! This crate re-exports the following [`nethsm_sdk_rs`] types so that the crate does not have to
//! be relied on directly:
//! * [`nethsm_sdk_rs::models::DecryptMode`]
//! * [`nethsm_sdk_rs::models::DistinguishedName`]
//! * [`nethsm_sdk_rs::models::EncryptMode`]
//! * [`nethsm_sdk_rs::models::KeyMechanism`]
//! * [`nethsm_sdk_rs::models::KeyType`]
//! * [`nethsm_sdk_rs::models::LogLevel`]
//! * [`nethsm_sdk_rs::models::NetworkConfig`]
//! * [`nethsm_sdk_rs::models::SystemState`]
//! * [`nethsm_sdk_rs::models::TlsKeyType`]
//! * [`nethsm_sdk_rs::models::UserRole`]
//!
//! Using the [`NetHsm`] struct it is possible to establish a TLS connection for multiple users.
//! TLS validation can be configured based on a variant of the [`ConnectionSecurity`] enum:
//! - [`ConnectionSecurity::Unsafe`]: The host certificate is not validated.
//! - [`ConnectionSecurity::Fingerprints`]: The host certificate is validated based on configurable
//!   fingerprints.
//! - [`ConnectionSecurity::Native`]: The host certificate is validated using the native Operating
//!   System trust store.
//!
//! # Examples
//!
//! ```
//! use nethsm::{ConnectionSecurity, Error, NetHsm};
//!
//! # fn main() -> Result<(), Error> {
//! // Create a new connection to a NetHSM at "https://example.org" using admin credentials
//! let nethsm = NetHsm::new(
//!     "https://example.org/api/v1".to_string(),
//!     ConnectionSecurity::Unsafe,
//!     Some(("admin".to_string(), Some("passphrase".to_string()))),
//!     None,
//!     None,
//! )?;
//!
//! // Connections can be initialized without any credentials and more than one can be provided later on
//! let nethsm = NetHsm::new(
//!     "https://example.org/api/v1".to_string(),
//!     ConnectionSecurity::Unsafe,
//!     None,
//!     None,
//!     None,
//! )?;
//!
//! nethsm.add_credentials(("admin".to_string(), Some("passphrase".to_string())));
//! nethsm.add_credentials(("user1".to_string(), Some("other_passphrase".to_string())));
//!
//! // A set of credentials must be used before establishing a connection with the configured NetHSM
//! nethsm.use_credentials("user1")?;
//! # Ok(())
//! # }
//! ```
use std::cell::RefCell;
use std::net::Ipv4Addr;
use std::sync::Arc;
use std::thread::available_parallelism;
use std::time::Duration;

use base64ct::{Base64, Encoding};
use chrono::{DateTime, Utc};
use log::{debug, error, info};
use md5::Md5;
use nethsm_sdk_rs::apis::configuration::{BasicAuth, Configuration};
use nethsm_sdk_rs::apis::default_api::{
    config_backup_passphrase_put,
    config_logging_get,
    config_logging_put,
    config_network_get,
    config_network_put,
    config_time_get,
    config_time_put,
    config_tls_cert_pem_get,
    config_tls_cert_pem_put,
    config_tls_csr_pem_post,
    config_tls_generate_post,
    config_unattended_boot_get,
    config_unattended_boot_put,
    config_unlock_passphrase_put,
    health_state_get,
    info_get,
    keys_generate_post,
    keys_get,
    keys_key_id_cert_delete,
    keys_key_id_cert_get,
    keys_key_id_cert_put,
    keys_key_id_csr_pem_post,
    keys_key_id_decrypt_post,
    keys_key_id_delete,
    keys_key_id_encrypt_post,
    keys_key_id_get,
    keys_key_id_public_pem_get,
    keys_key_id_put,
    keys_key_id_restrictions_tags_tag_delete,
    keys_key_id_restrictions_tags_tag_put,
    keys_key_id_sign_post,
    keys_post,
    lock_post,
    metrics_get,
    provision_post,
    random_post,
    system_backup_post,
    system_cancel_update_post,
    system_commit_update_post,
    system_factory_reset_post,
    system_reboot_post,
    system_restore_post,
    system_shutdown_post,
    system_update_post,
    unlock_post,
    users_get,
    users_post,
    users_user_id_delete,
    users_user_id_get,
    users_user_id_passphrase_post,
    users_user_id_put,
    users_user_id_tags_get,
    users_user_id_tags_tag_delete,
    users_user_id_tags_tag_put,
    KeysPostBody,
};
use nethsm_sdk_rs::models::{
    BackupPassphraseConfig,
    DecryptRequestData,
    EncryptRequestData,
    InfoData,
    KeyGenerateRequestData,
    KeyRestrictions,
    LoggingConfig,
    PrivateKey,
    ProvisionRequestData,
    PublicKey,
    RandomRequestData,
    SignRequestData,
    SystemUpdateData,
    TimeConfig,
    TlsKeyGenerateRequestData,
    UnlockPassphraseConfig,
    UnlockRequestData,
    UserData,
    UserPassphrasePostData,
    UserPostData,
};
// Re-export some useful types so that users do not have to use nethsm-sdk-rs directly
pub use nethsm_sdk_rs::models::{
    DecryptMode,
    DistinguishedName,
    EncryptMode,
    KeyMechanism,
    KeyType,
    LogLevel,
    NetworkConfig,
    SystemState,
    TlsKeyType,
    UserRole,
};
use nethsm_sdk_rs::ureq::AgentBuilder;
use rustls::crypto::{aws_lc_rs as tls_provider, CryptoProvider};
use rustls::ClientConfig;
use serde_json::Value;
use sha1::Sha1;
use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};

mod nethsm_sdk;
use nethsm_sdk::{match_key_type_and_mechanisms, NetHsmApiError};
pub use nethsm_sdk::{BootMode, KeyImportData, SignatureType};
mod tls;
pub use tls::{ConnectionSecurity, HostCertificateFingerprints};
use tls::{DangerIgnoreVerifier, FingerprintVerifier};

const USER_AGENT: &str = "signstar-nethsm/0.1.0";

#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Wraps a [`rustls::Error`] for issues with rustls based TLS setups
    #[error("TLS error: {0}")]
    Rustls(#[from] rustls::Error),

    /// A Base64 encoded string can not be decode
    #[error("Decoding Base64 string failed: {0}")]
    Base64Decode(base64ct::Error),

    /// A generic error with a custom message
    #[error("NetHSM error: {0}")]
    Default(String),

    /// The loading of TLS root certificates from the platform's native certificate store failed
    #[error("Loading system TLS certs failed")]
    CertLoading,

    /// A call to the NetHSM API failed
    #[error("NetHSM API error: {0}")]
    Api(String),

    /// Provided key data is invalid
    #[error("Key data invalid: {0}")]
    KeyData(String),

    /// Importing a key failed because of insufficient or malformed data
    #[error("Key import failed: {0}")]
    KeyImport(String),
}

/// A network connection to a NetHSM
///
/// Defines a network configuration for the connection and a list of user credentials that can be
/// used over this connection.
pub struct NetHsm {
    /// The API configuration for a NetHSM
    config: RefCell<Configuration>,
    /// Credentials for interacting with the NetHSM using [`NetHsm::config`]
    users: RefCell<Vec<BasicAuth>>,
}

impl NetHsm {
    /// Creates a new NetHSM connection
    ///
    /// Creates a new NetHSM connection based on the `url` of the API and a chosen
    /// `connection_security` for TLS (see [`ConnectionSecurity`]).
    ///
    /// Optionally initial `credentials` (used when communicating with the NetHSM),
    /// `max_idle_connections` to set the size of the connection pool (defaults to `100`) and
    /// `timeout_seconds` to set the timeout for a successful socket connection (defaults to `10`)
    /// can be provided.
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if the rustls based [`ClientConfig`] can not be created.
    pub fn new(
        url: String,
        connection_security: ConnectionSecurity,
        credentials: Option<BasicAuth>,
        max_idle_connections: Option<usize>,
        timeout_seconds: Option<u64>,
    ) -> Result<Self, Error> {
        let tls_conf = {
            let tls_conf = ClientConfig::builder_with_provider(Arc::new(CryptoProvider {
                cipher_suites: tls_provider::ALL_CIPHER_SUITES.into(),
                ..tls_provider::default_provider()
            }))
            .with_protocol_versions(rustls::DEFAULT_VERSIONS)?;

            match connection_security {
                ConnectionSecurity::Unsafe => {
                    let dangerous = tls_conf.dangerous();
                    dangerous
                        .with_custom_certificate_verifier(Arc::new(DangerIgnoreVerifier(
                            tls_provider::default_provider(),
                        )))
                        .with_no_client_auth()
                }
                ConnectionSecurity::Native => {
                    let mut roots = rustls::RootCertStore::empty();
                    let native_certs = rustls_native_certs::load_native_certs().map_err(|err| {
                        error!("Failed to load certificates: {err}");
                        Error::CertLoading
                    })?;

                    let (added, failed) = roots.add_parsable_certificates(native_certs);
                    debug!("Added {added} certificates and failed to parse {failed} certificates");

                    if added == 0 {
                        error!("Added no native certificates");
                        return Err(Error::CertLoading);
                    }

                    tls_conf.with_root_certificates(roots).with_no_client_auth()
                }
                ConnectionSecurity::Fingerprints(fingerprints) => {
                    let dangerous = tls_conf.dangerous();
                    dangerous
                        .with_custom_certificate_verifier(Arc::new(FingerprintVerifier {
                            fingerprints,
                            provider: tls_provider::default_provider(),
                        }))
                        .with_no_client_auth()
                }
            }
        };

        let agent = {
            let max_idle_connections = max_idle_connections
                .or_else(|| available_parallelism().ok().map(Into::into))
                .unwrap_or(100);
            let timeout_seconds = timeout_seconds.unwrap_or(10);
            info!(
                "NetHSM connection configured with \"max_idle_connection\" {} and \"timeout_seconds\" {}.",
                max_idle_connections, timeout_seconds
            );

            AgentBuilder::new()
                .tls_config(Arc::new(tls_conf))
                .max_idle_connections(max_idle_connections)
                .max_idle_connections_per_host(max_idle_connections)
                .timeout_connect(Duration::from_secs(timeout_seconds))
                .build()
        };

        let api_config = RefCell::new(Configuration {
            client: agent,
            base_path: url,
            basic_auth: credentials.clone(),
            user_agent: Some(USER_AGENT.to_string()),
            ..Default::default()
        });

        let users = {
            let mut users = vec![];
            if let Some(credentials) = credentials {
                users.push(credentials)
            }
            RefCell::new(users)
        };

        Ok(Self {
            config: api_config,
            users,
        })
    }

    /// Sets the URL for the NetHSM connection
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // Create a new connection for a NetHSM at "https://example.org"
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // change the url to something else
    /// nethsm.set_url("https://other.org/api/v1".to_string());
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_url(&self, url: String) {
        self.config.borrow_mut().base_path = url;
    }

    /// Adds credentials to the list of available credentials
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add credentials
    /// nethsm.add_credentials(("admin".to_string(), Some("passphrase".to_string())));
    /// nethsm.add_credentials(("user1".to_string(), Some("other_passphrase".to_string())));
    /// nethsm.add_credentials(("user2".to_string(), None));
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_credentials(&self, credentials: BasicAuth) {
        // remove any previously existing credentials (User IDs are unique)
        self.remove_credentials(&credentials.0);
        self.users.borrow_mut().push(credentials)
    }

    /// Removes credentials from the list of available and currently used ones
    ///
    /// Removes credentials from the list of available credentials and if identical unsets the
    /// credentials for current authentication as well.
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // remove credentials
    /// nethsm.remove_credentials("admin");
    /// # Ok(())
    /// # }
    /// ```
    pub fn remove_credentials(&self, user_id: &str) {
        self.users.borrow_mut().retain(|cred| cred.0 != user_id);
        if self
            .config
            .borrow()
            .basic_auth
            .as_ref()
            .is_some_and(|x| x.0 == user_id)
        {
            self.config.borrow_mut().basic_auth = None;
        }
    }

    /// Sets credentials to use for the next connection
    ///
    /// # Errors
    ///
    /// An [`Error`] is returned if no credentials with the User ID `user_id` can be found.
    ///
    /// # Examples
    ///
    /// ```
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add credentials
    /// nethsm.add_credentials(("admin".to_string(), Some("passphrase".to_string())));
    /// nethsm.add_credentials(("user1".to_string(), Some("other_passphrase".to_string())));
    ///
    /// // use admin credentials
    /// nethsm.use_credentials("admin")?;
    ///
    /// // use operator credentials
    /// nethsm.use_credentials("user1")?;
    ///
    /// // this fails, because the user has not been added yet
    /// assert!(nethsm.use_credentials("user2").is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn use_credentials(&self, user_id: &str) -> Result<(), Error> {
        if let Some(basic_auth) = self
            .users
            .borrow()
            .iter()
            .find(|&basic_auth| basic_auth.0 == user_id)
        {
            let passphrase = basic_auth.1.as_ref().cloned();
            self.config.borrow_mut().basic_auth = Some((basic_auth.0.clone(), passphrase));
            Ok(())
        } else {
            Err(Error::Default(format!(
                "The credentials for User ID \"{}\" needs to be added before it can be used!",
                user_id
            )))
        }
    }

    /// Provisions a NetHSM
    ///
    /// [Provisioning](https://docs.nitrokey.com/nethsm/getting-started#provisioning) is the initial setup step for a device.
    /// It sets the `unlock_passphrase` which is used for unlocking a device that is using attended
    /// boot (see [`BootMode::Attended`]), the initial `admin_passphrase` for the default
    /// administrator account ("admin") and the `system_time`.
    /// The unlock passphrase can later on be changed using [`NetHsm::set_unlock_passphrase`] and
    /// the admin passphrase using [`NetHsm::set_user_passphrase`].
    ///
    /// For this call no credentials are required and if any are configured, they are ignored.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if provisioning fails:
    /// * the device is not in state [`SystemState::Unprovisioned`]
    /// * the provided data is malformed
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chrono::Utc;
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // no initial credentials are required
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // provision the device
    /// nethsm.provision(
    ///     "unlock-the-device".to_string(),
    ///     "admin-passphrase".to_string(),
    ///     Utc::now(),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn provision(
        &self,
        unlock_passphrase: String,
        admin_passphrase: String,
        system_time: DateTime<Utc>,
    ) -> Result<(), Error> {
        let provision_request_data = ProvisionRequestData::new(
            unlock_passphrase,
            admin_passphrase,
            system_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        );
        provision_post(&self.config.borrow(), provision_request_data).map_err(|error| {
            Error::Api(format!(
                "Provisioning failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Returns the system state of the NetHSM instance
    ///
    /// Returns a variant of [`SystemState`], which describes the [state](https://docs.nitrokey.com/nethsm/administration#state) a device is currently in.
    ///
    /// For this call no credentials are required and if any are configured, they are ignored.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the state information can not be retrieved.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // no initial credentials are required
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // retrieve the state
    /// println!("{:?}", nethsm.state()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn state(&self) -> Result<SystemState, Error> {
        let health_state = health_state_get(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Retrieving state failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(health_state.entity.state)
    }

    /// Returns device information for the NetHSM instance
    ///
    /// Returns an [`InfoData`], which provides the [device information](https://docs.nitrokey.com/nethsm/administration#device-information).
    ///
    /// For this call no credentials are required and if any are configured, they are ignored.
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the device information can not be retrieved.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // no initial credentials are required
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // retrieve the device info
    /// println!("{:?}", nethsm.info()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn info(&self) -> Result<InfoData, Error> {
        let info = info_get(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Retrieving device information failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(info.entity)
    }

    /// Returns metrics for the NetHSM instance
    ///
    /// Returns a [`serde_json::Value`] which provides [metrics](https://docs.nitrokey.com/nethsm/administration#metrics) for the device.
    ///
    /// This call requires using credentials of a user in the "metrics" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the device metrics can not be retrieved:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "metrics" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "metrics" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some((
    ///         "metrics".to_string(),
    ///         Some("metrics-passphrase".to_string()),
    ///     )),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // retrieve the metrics
    /// println!("{:?}", nethsm.metrics()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn metrics(&self) -> Result<Value, Error> {
        let metrics = metrics_get(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Retrieving metrics failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(metrics.entity)
    }

    /// Sets the unlock passphrase for the NetHSM instance
    ///
    /// Sets `current_passphrase` to `new_passphrase`, which changes the [unlock passphrase](https://docs.nitrokey.com/nethsm/administration#unlock-passphrase) for the device.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the unlock passphrase can not be changed:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided `current_passphrase` is not correct
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // set the unlock passphrase
    /// nethsm.set_unlock_passphrase(
    ///     "current-unlock-passphrase".to_string(),
    ///     "new-unlock-passphrase".to_string(),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_unlock_passphrase(
        &self,
        current_passphrase: String,
        new_passphrase: String,
    ) -> Result<(), Error> {
        config_unlock_passphrase_put(
            &self.config.borrow(),
            UnlockPassphraseConfig::new(new_passphrase, current_passphrase),
        )
        .map_err(|error| {
            Error::Api(format!(
                "Changing unlock passphrase failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Returns the boot mode
    ///
    /// Returns a variant of [`BootMode`] which represents the device's [boot mode](https://docs.nitrokey.com/nethsm/administration#boot-mode).
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the boot mode can not be retrieved:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // retrieve the boot mode
    /// println!("{:?}", nethsm.get_boot_mode()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_boot_mode(&self) -> Result<BootMode, Error> {
        Ok(BootMode::from(
            config_unattended_boot_get(&self.config.borrow())
                .map_err(|error| {
                    Error::Api(format!(
                        "Retrieving boot mode failed: {}",
                        NetHsmApiError::from(error)
                    ))
                })?
                .entity,
        ))
    }

    /// Sets the boot mode
    ///
    /// Sets the device's [boot mode](https://docs.nitrokey.com/nethsm/administration#boot-mode) based on a [`BootMode`] variant.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the boot mode can not be set:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{BootMode, ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // set the boot mode to unattended
    /// nethsm.set_boot_mode(BootMode::Unattended)?;
    ///
    /// // set the boot mode to attended
    /// nethsm.set_boot_mode(BootMode::Attended)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_boot_mode(&self, boot_mode: BootMode) -> Result<(), Error> {
        config_unattended_boot_put(&self.config.borrow(), boot_mode.into()).map_err(|error| {
            Error::Api(format!(
                "Setting boot mode failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Returns the TLS certificate of the API
    ///
    /// Returns the device's [TLS certificate](https://docs.nitrokey.com/nethsm/administration#tls-certificate) which is used for communication with the API.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the device's TLS certificate can not be retrieved:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get the TLS certificate
    /// println!("{}", nethsm.get_tls_cert()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_tls_cert(&self) -> Result<String, Error> {
        Ok(config_tls_cert_pem_get(&self.config.borrow())
            .map_err(|error| {
                Error::Api(format!(
                    "Retrieving API TLS certificate failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Returns a Certificate Signing Request (CSR) for the API's TLS certificate
    ///
    /// Based on data from an instance of [`nethsm_sdk_rs::models::DistinguishedName`] returns a
    /// [Certificate Signing Request (CSR)](https://en.wikipedia.org/wiki/Certificate_signing_request)
    /// in [PKCS#10](https://en.wikipedia.org/wiki/Certificate_signing_request#Structure_of_a_PKCS_#10_CSR) format
    /// for the device's [TLS certificate](https://docs.nitrokey.com/nethsm/administration#tls-certificate)
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the CSR can not be retrieved:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, DistinguishedName, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get the CSR for TLS certificate
    /// println!(
    ///     "{}",
    ///     nethsm.get_tls_csr(DistinguishedName {
    ///         country_name: Some("DE".to_string()),
    ///         state_or_province_name: Some("Berlin".to_string()),
    ///         locality_name: Some("Berlin".to_string()),
    ///         organization_name: Some("Foobar Inc".to_string()),
    ///         organizational_unit_name: Some("Department of Foo".to_string()),
    ///         common_name: "Foobar Inc".to_string(),
    ///         email_address: Some("foobar@mcfooface.com".to_string()),
    ///     })?
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_tls_csr(&self, distinguished_name: DistinguishedName) -> Result<String, Error> {
        Ok(
            config_tls_csr_pem_post(&self.config.borrow(), distinguished_name)
                .map_err(|error| {
                    Error::Api(format!(
                        "Retrieving CSR for TLS certificate failed: {}",
                        NetHsmApiError::from(error),
                    ))
                })?
                .entity,
        )
    }

    /// Generates a new TLS certificate for the API
    ///
    /// Based on `tls_key_type` and `length` generates a new
    /// [TLS certificate](https://docs.nitrokey.com/nethsm/administration#tls-certificate)
    /// (used for communication with the API).
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if the new TLS certificate can not be generated:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the `tls_key_type` and `length` combination is not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, TlsKeyType};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // generate a new TLS certificate
    /// nethsm.generate_tls_cert(TlsKeyType::Rsa, Some(4096))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn generate_tls_cert(
        &self,
        tls_key_type: TlsKeyType,
        length: Option<i32>,
    ) -> Result<(), Error> {
        config_tls_generate_post(
            &self.config.borrow(),
            TlsKeyGenerateRequestData {
                r#type: tls_key_type,
                length,
            },
        )
        .map_err(|error| {
            Error::Api(format!(
                "Generating API TLS certificate failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Sets a new TLS certificate for the API
    ///
    /// Accepts a Base64 encoded [DER](https://en.wikipedia.org/wiki/X.690#DER_encoding) certificate via `certificate`
    /// which is added as new [TLS certificate](https://docs.nitrokey.com/nethsm/administration#tls-certificate) for
    /// communication with the API.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if setting a new TLS certificate fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided `certificate` is not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let cert = r#"-----BEGIN CERTIFICATE-----
    /// MIIBHjCBxKADAgECAghDngCv6xWIXDAKBggqhkjOPQQDAjAUMRIwEAYDVQQDDAlr
    /// ZXlmZW5kZXIwIBcNNzAwMTAxMDAwMDAwWhgPOTk5OTEyMzEyMzU5NTlaMBQxEjAQ
    /// BgNVBAMMCWtleWZlbmRlcjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJsHIrsZ
    /// 6fJzrk12GK7nW6bGyTIIZiQUq0uaKbn21dgPiDCO5+iYVXAqnWu4IMVZQnkFJmte
    /// PRUUuM3119f8ffkwCgYIKoZIzj0EAwIDSQAwRgIhALH4fDYJ21tRecXp9IipBlil
    /// p+hJCj77zBvFmGYy/UnPAiEA8csj7U6BfzvK4EiQyUZa7/as+nXwj3XHU/i8LyLm
    /// Chw=
    /// -----END CERTIFICATE-----"#;
    ///
    /// // set a new TLS certificate
    /// nethsm.set_tls_cert(cert)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_tls_cert(&self, certificate: &str) -> Result<(), Error> {
        config_tls_cert_pem_put(&self.config.borrow(), certificate).map_err(|error| {
            Error::Api(format!(
                "Setting API TLS certificate failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Gets the network configuration
    ///
    /// Retrieves the [network configuration](https://docs.nitrokey.com/nethsm/administration#network) of the device in
    /// the form of a [`nethsm_sdk_rs::models::NetworkConfig`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if retrieving network configuration fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get the network configuration
    /// println!("{:?}", nethsm.get_network()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_network(&self) -> Result<NetworkConfig, Error> {
        Ok(config_network_get(&self.config.borrow())
            .map_err(|error| {
                Error::Api(format!(
                    "Getting network config failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Sets the network configuration
    ///
    /// Sets the [network configuration](https://docs.nitrokey.com/nethsm/administration#network) of the device based on
    /// a [`nethsm_sdk_rs::models::NetworkConfig`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if setting the network configuration fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided `network_config` is not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, NetworkConfig};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let network_config = NetworkConfig::new(
    ///     "192.168.1.1".to_string(),
    ///     "255.255.255.0".to_string(),
    ///     "0.0.0.0".to_string(),
    /// );
    ///
    /// // set the network configuration
    /// nethsm.set_network(network_config)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_network(&self, network_config: NetworkConfig) -> Result<(), Error> {
        config_network_put(&self.config.borrow(), network_config).map_err(|error| {
            Error::Api(format!(
                "Setting network config failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Gets the device's time
    ///
    /// Retrieves the current [time](https://docs.nitrokey.com/nethsm/administration#time) of the device.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if retrieving time fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get the time
    /// println!("{:?}", nethsm.get_time()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_time(&self) -> Result<String, Error> {
        Ok(config_time_get(&self.config.borrow())
            .map_err(|error| {
                Error::Api(format!(
                    "Getting device time failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .time)
    }

    /// Sets the device's time
    ///
    /// Sets the [time](https://docs.nitrokey.com/nethsm/administration#time) for the device.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if setting time fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided `time` is not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use chrono::Utc;
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let time = Utc::now();
    /// // set the time
    /// nethsm.set_time(time)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_time(&self, time: DateTime<Utc>) -> Result<(), Error> {
        config_time_put(
            &self.config.borrow(),
            TimeConfig::new(time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
        )
        .map_err(|error| {
            Error::Api(format!(
                "Setting device time failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Gets the logging configuration
    ///
    /// Retrieves the current [logging configuration](https://docs.nitrokey.com/nethsm/administration#logging) of the device.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if getting logging configuration fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get logging configuration
    /// println!("{:?}", nethsm.get_logging()?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_logging(&self) -> Result<LoggingConfig, Error> {
        Ok(config_logging_get(&self.config.borrow())
            .map_err(|error| {
                Error::Api(format!(
                    "Getting logging config failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Sets the logging configuration
    ///
    /// Sets the device's [logging configuration](https://docs.nitrokey.com/nethsm/administration#logging).
    /// A host to send logs to is defined with `ip_address` and `port`. The log level is configured
    /// using `log_level`.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if setting the logging configuration fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided `ip_address`, `port` or `log_level` are not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::net::Ipv4Addr;
    ///
    /// use nethsm::{ConnectionSecurity, Error, LogLevel, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // set logging configuration
    /// println!(
    ///     "{:?}",
    ///     nethsm.set_logging(Ipv4Addr::new(192, 168, 1, 2), 513, LogLevel::Debug)?
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_logging(
        &self,
        ip_address: Ipv4Addr,
        port: i32,
        log_level: LogLevel,
    ) -> Result<(), Error> {
        let ip_address = ip_address.to_string();
        config_logging_put(
            &self.config.borrow(),
            LoggingConfig::new(ip_address, port, log_level),
        )
        .map_err(|error| {
            Error::Api(format!(
                "Setting logging config failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Sets the backup passphrase
    ///
    /// Sets `current_passphrase` to `new_passphrase`, which changes the [backup](https://docs.nitrokey.com/nethsm/administration#backup) passphrase for the device.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if setting the backup passphrase fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided `current_passphrase` is not correct
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // set the backup passphrase
    /// nethsm.set_backup_passphrase(
    ///     "current-backup-passphrase".to_string(),
    ///     "new-backup-passphrase".to_string(),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_backup_passphrase(
        &self,
        current_passphrase: String,
        new_passphrase: String,
    ) -> Result<(), Error> {
        config_backup_passphrase_put(
            &self.config.borrow(),
            BackupPassphraseConfig::new(new_passphrase, current_passphrase),
        )
        .map_err(|error| {
            Error::Api(format!(
                "Setting backup passphrase failed: {}",
                NetHsmApiError::from(error),
            ))
        })?;
        Ok(())
    }

    /// Creates a backup
    ///
    /// Triggers the creation and download of a [backup](https://docs.nitrokey.com/nethsm/administration#backup) of the device.
    /// Before creating a backup, [`NetHsm::set_backup_passphrase`] has to be called once to set a
    /// passphrase for the backup.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if creating a backup fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::PathBuf;
    ///
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // create a backup and write it to file
    /// let backup_file = PathBuf::from("nethsm.bkp");
    /// std::fs::write(backup_file, nethsm.backup()?).unwrap();
    /// # Ok(())
    /// # }
    /// ```
    pub fn backup(&self) -> Result<Vec<u8>, Error> {
        Ok(system_backup_post(&self.config.borrow())
            .map_err(|error| {
                Error::Api(format!(
                    "Getting backup failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Triggers a factory reset
    ///
    /// Triggers a [factory reset](https://docs.nitrokey.com/nethsm/administration#reset-to-factory-defaults) for the device.
    /// This action deletes all user and system data! Make sure to create a backup using
    /// [`NetHsm::backup`] first!
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if resetting the device fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // trigger a factory reset
    /// nethsm.factory_reset()?;
    /// assert_eq!(nethsm.state()?, SystemState::Unprovisioned);
    /// # Ok(())
    /// # }
    /// ```
    pub fn factory_reset(&self) -> Result<(), Error> {
        system_factory_reset_post(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Factory reset failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Restores device from backup
    ///
    /// WARNING: This function has known issues and may in fact not work! <https://github.com/Nitrokey/nethsm/issues/5>
    ///
    /// [Restores](https://docs.nitrokey.com/nethsm/administration#restore) a device from a
    /// [backup](https://docs.nitrokey.com/nethsm/administration#backup), by providing a
    /// `backup_passphrase` (set using [`NetHsm::set_backup_passphrase`]) a new `system_time` for
    /// the device and a backup (created using [`NetHsm::backup`]).
    /// The device may be in state [`SystemState::Operational`] or [`SystemState::Unprovisioned`].
    /// Any existing user data is safely removed and replaced by that of the backup. If the
    /// device is in state [`SystemState::Unprovisioned`] the system configuration from the
    /// backup is also used and the device is rebooted.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if restoring the device from backup fails:
    /// * the device is not in state [`SystemState::Operational`] or [`SystemState::Unprovisioned`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::path::PathBuf;
    ///
    /// use chrono::Utc;
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// #
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // restore from backup
    /// let backup_file = PathBuf::from("nethsm.bkp");
    /// let backup = std::fs::read(backup_file).unwrap();
    /// nethsm.restore("backup-passphrase".to_string(), Utc::now(), backup)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn restore(
        &self,
        backup_passphrase: String,
        system_time: DateTime<Utc>,
        backup: Vec<u8>,
    ) -> Result<(), Error> {
        system_restore_post(
            &self.config.borrow(),
            Some(nethsm_sdk_rs::models::RestoreRequestArguments {
                backup_passphrase: Some(backup_passphrase),
                system_time: Some(system_time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
            }),
            Some(backup),
        )
        .map_err(|error| {
            Error::Api(format!(
                "Restoring backup failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Locks the device
    ///
    /// Locks the device and sets its [state](https://docs.nitrokey.com/nethsm/administration#state) to [`SystemState::Locked`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if locking the device fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // lock the device
    /// nethsm.lock()?;
    /// assert_eq!(nethsm.state()?, SystemState::Locked);
    /// # Ok(())
    /// # }
    /// ```
    pub fn lock(&self) -> Result<(), Error> {
        lock_post(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Locking device failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Unlocks the device
    ///
    /// If the device is in state [`SystemState::Locked`] unlocks the device using
    /// `unlock_passphrase` and sets its [state](https://docs.nitrokey.com/nethsm/administration#state) to [`SystemState::Operational`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if unlocking the device fails:
    /// * the device is not in state [`SystemState::Locked`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Locked);
    /// // unlock the device
    /// nethsm.unlock("unlock-passphrase".to_string())?;
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// # Ok(())
    /// # }
    /// ```
    pub fn unlock(&self, unlock_passphrase: String) -> Result<(), Error> {
        unlock_post(
            &self.config.borrow(),
            UnlockRequestData::new(unlock_passphrase),
        )
        .map_err(|error| {
            Error::Api(format!(
                "Unlocking device failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Reboots the device
    ///
    /// [Reboots](https://docs.nitrokey.com/nethsm/administration#reboot-and-shutdown) the device,
    /// if it is in state [`SystemState::Operational`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if rebooting the device fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // reboot the device
    /// nethsm.reboot()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn reboot(&self) -> Result<(), Error> {
        system_reboot_post(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Rebooting device failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Shuts down the device
    ///
    /// [Shuts down](https://docs.nitrokey.com/nethsm/administration#reboot-and-shutdown) the device,
    /// if it is in state [`SystemState::Operational`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if shutting down the device fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // shut down the device
    /// nethsm.shutdown()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn shutdown(&self) -> Result<(), Error> {
        system_shutdown_post(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Shutting down device failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Uploads a software update
    ///
    /// WARNING: This function has shown flaky behavior during tests with the official container!
    /// Upload may have to be repeated!
    ///
    /// Uploads a [software update](https://docs.nitrokey.com/nethsm/administration#software-update) to the device,
    /// if it is in state [`SystemState::Operational`] and returns information about the software
    /// update ([`nethsm_sdk_rs::models::SystemUpdateData`]).
    /// Software updates can successively be installed ([`NetHsm::commit_update`]) or canceled
    /// ([`NetHsm::cancel_update`]).
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if uploading the software update fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let update_file = std::path::PathBuf::from("update.bin");
    /// let update = std::fs::read(update_file).unwrap();
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // upload software update to device
    /// println!("{:?}", nethsm.upload_update(update)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn upload_update(&self, update: Vec<u8>) -> Result<SystemUpdateData, Error> {
        Ok(system_update_post(&self.config.borrow(), update)
            .map_err(|error| {
                println!("error during upload");
                Error::Api(format!(
                    "Uploading update failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Commits an uploaded software update
    ///
    /// Commits a [software update](https://docs.nitrokey.com/nethsm/administration#software-update)
    /// previously uploaded to the device (e.g. using [`NetHsm::upload_update`]), if the device is
    /// in state [`SystemState::Operational`].
    /// Successfully committing a software update leads to the reboot of the device.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if committing the software update fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * there is no software update to commit
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let update_file = std::path::PathBuf::from("update.bin");
    /// let update = std::fs::read(update_file).unwrap();
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // upload software update to device
    /// println!("{:?}", nethsm.upload_update(update)?);
    /// // commit software update
    /// nethsm.commit_update()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn commit_update(&self) -> Result<(), Error> {
        system_commit_update_post(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Committing update failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Cancels an uploaded software update
    ///
    /// Cancels a [software update](https://docs.nitrokey.com/nethsm/administration#software-update)
    /// previously uploaded to the device (e.g. using [`NetHsm::upload_update`]), if the device is
    /// in state [`SystemState::Operational`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if canceling the software update fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * there is no software update to cancel
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let update_file = std::path::PathBuf::from("update.bin");
    /// let update = std::fs::read(update_file).unwrap();
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // upload software update to device
    /// println!("{:?}", nethsm.upload_update(update)?);
    /// // cancel software update
    /// nethsm.cancel_update()?;
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// # Ok(())
    /// # }
    /// ```
    pub fn cancel_update(&self) -> Result<(), Error> {
        system_cancel_update_post(&self.config.borrow()).map_err(|error| {
            Error::Api(format!(
                "Cancelling update failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Adds a new user on the device
    ///
    /// [Adds a user](https://docs.nitrokey.com/nethsm/administration#add-user)
    /// on the device, if the device is in state [`SystemState::Operational`] and returns the User
    /// ID of the created user.
    /// A new user is created by providing a `real_name` from which a User ID is derived (optionally
    /// a User ID can be provided with `user_id`), a `role` which describes the user's access rights
    /// on the device (see [`UserRole`]) and a `passphrase`.
    ///
    /// Internally, this function also calls [`NetHsm::add_credentials`] to add the new user to the
    /// list of available credentials.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding the user fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided `real_name`, `passphrase` or `user_id` are not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, UserRole};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add a user in the operator role
    /// assert_eq!(
    ///     "user1",
    ///     nethsm.add_user(
    ///         "Operator One".to_string(),
    ///         UserRole::Operator,
    ///         "operator1-passphrase".to_string(),
    ///         Some("user1".to_string()),
    ///     )?
    /// );
    ///
    /// // this fails because the user exists already
    /// assert!(nethsm
    ///     .add_user(
    ///         "Operator One".to_string(),
    ///         UserRole::Operator,
    ///         "operator1-passphrase".to_string(),
    ///         Some("user1".to_string()),
    ///     )
    ///     .is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_user(
        &self,
        real_name: String,
        role: UserRole,
        passphrase: String,
        user_id: Option<String>,
    ) -> Result<String, Error> {
        let user_id = if let Some(user_id) = user_id {
            users_user_id_put(
                &self.config.borrow(),
                &user_id,
                UserPostData::new(real_name, role, passphrase.clone()),
            )
            .map_err(|error| {
                Error::Api(format!(
                    "Adding user failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?;
            user_id
        } else {
            users_post(
                &self.config.borrow(),
                UserPostData::new(real_name, role, passphrase.clone()),
            )
            .map_err(|error| {
                Error::Api(format!(
                    "Adding user failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .id
        };

        // add to list of users
        self.users
            .borrow_mut()
            .push((user_id.clone(), Some(passphrase)));

        Ok(user_id)
    }

    /// Deletes a user from the device
    ///
    /// [Deletes a user](https://docs.nitrokey.com/nethsm/administration#delete-user)
    /// from the device based on `user_id`.
    ///
    /// Internally, this function also calls [`NetHsm::remove_credentials`] to remove the user from
    /// the list of available credentials.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if deleting a user fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the user identified by `user_id` does not exist
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, UserRole};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add a user in the operator role
    /// assert_eq!(
    ///     "user1",
    ///     nethsm.add_user(
    ///         "Operator One".to_string(),
    ///         UserRole::Operator,
    ///         "operator1-passphrase".to_string(),
    ///         Some("user1".to_string()),
    ///     )?
    /// );
    ///
    /// // delete the user again
    /// nethsm.delete_user("user1")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_user(&self, user_id: &str) -> Result<(), Error> {
        users_user_id_delete(&self.config.borrow(), user_id).map_err(|error| {
            Error::Api(format!(
                "Deleting user failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;

        // remove from list of credentials
        self.remove_credentials(user_id);

        Ok(())
    }

    /// Gets a list of all User IDs on the device
    ///
    /// Gets a [list of all User IDs](https://docs.nitrokey.com/nethsm/administration#list-users)
    /// on the device.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if retrieving the list of all User IDs fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get all User IDs... at a minimum the "admin" user should be there!
    /// assert!(nethsm.get_users()?.contains(&"admin".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_users(&self) -> Result<Vec<String>, Error> {
        Ok(users_get(&self.config.borrow())
            .map_err(|error| {
                Error::Api(format!(
                    "Getting users failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .iter()
            .map(|x| x.user.clone())
            .collect())
    }

    /// Gets information of a user on the device
    ///
    /// Gets [information of a user](https://docs.nitrokey.com/nethsm/administration#list-users)
    /// on the device and returns it as a [`UserData`].
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if retrieving information of the user fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the user identified by `user_id` does not exist
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get user information
    /// println!("{:?}", nethsm.get_user("admin")?);
    ///
    /// // this fails as the user does not exist
    /// assert!(nethsm.get_user("user1").is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_user(&self, user_id: &str) -> Result<UserData, Error> {
        Ok(users_user_id_get(&self.config.borrow(), user_id)
            .map_err(|error| {
                Error::Api(format!(
                    "Getting user failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Sets the passphrase for a user on the device
    ///
    /// Sets the [passphrase for a user](https://docs.nitrokey.com/nethsm/administration#user-passphrase)
    /// on the device.
    ///
    /// Internally, this function also calls [`NetHsm::add_credentials`] to add the updated user
    /// credentials to the list of available credentials.
    /// If the calling user in the "admin" role changes their own passphrase, additionally
    /// [`NetHsm::use_credentials`] is called to use the updated passphrase.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if setting the passphrase for the user fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the user identified by `user_id` does not exist
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // set the admin user's passphrase
    /// nethsm.set_user_passphrase("admin", "new-admin-passphrase".to_string())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_user_passphrase(&self, user_id: &str, passphrase: String) -> Result<(), Error> {
        users_user_id_passphrase_post(
            &self.config.borrow(),
            user_id,
            UserPassphrasePostData::new(passphrase.clone()),
        )
        .map_err(|error| {
            Error::Api(format!(
                "Setting user passphrase failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;

        // add to list of available credentials
        self.add_credentials((user_id.to_string(), Some(passphrase)));
        // if the caller changed their own passphrase, use it
        if self
            .config
            .borrow()
            .basic_auth
            .as_ref()
            .is_some_and(|credentials| credentials.0 == user_id)
        {
            self.use_credentials(user_id)?;
        }

        Ok(())
    }

    /// Adds a tag to a user in the operator role
    ///
    /// [Adds a tag](https://docs.nitrokey.com/nethsm/administration#tags-for-users)
    /// to a user in the "operator" role. A tag provides a user in the "operator" role with access
    /// to keys on the device associated with that same tag. The tag must have been set for a
    /// key on the device beforehand (e.g. using [`NetHsm::add_key_tag`]).
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding the tag for the user fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the user identified by `user_id` does not exist
    /// * the user identified by `user_id` is not in the "operator" role
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, UserRole};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add a user in the operator role
    /// assert_eq!(
    ///     "user1",
    ///     nethsm.add_user(
    ///         "Operator One".to_string(),
    ///         UserRole::Operator,
    ///         "operator1-passphrase".to_string(),
    ///         Some("user1".to_string()),
    ///     )?
    /// );
    ///
    /// // add a tag for the user
    /// nethsm.add_user_tag("user1", "tag1")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_user_tag(&self, user_id: &str, tag: &str) -> Result<(), Error> {
        users_user_id_tags_tag_put(&self.config.borrow(), user_id, tag).map_err(|error| {
            Error::Api(format!(
                "Adding tag for user failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Deletes a tag from a user in the operator role
    ///
    /// [Deletes a tag](https://docs.nitrokey.com/nethsm/administration#tags-for-users)
    /// from a user in the "operator" role. Removing a tag from a user in the "operator" role
    /// removes its access to any key on the device that has the same tag.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if deleting the tag from the user fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the user identified by `user_id` does not exist
    /// * the user identified by `user_id` is not in the "operator" role
    /// * the user identified by `user_id` does not have `tag`
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, UserRole};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add a tag for the user
    /// nethsm.delete_user_tag("user1", "tag1")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_user_tag(&self, user_id: &str, tag: &str) -> Result<(), Error> {
        users_user_id_tags_tag_delete(&self.config.borrow(), user_id, tag).map_err(|error| {
            Error::Api(format!(
                "Deleting tag for user failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Gets all tags on a user in the operator role
    ///
    /// [Gets all tags](https://docs.nitrokey.com/nethsm/administration#tags-for-users)
    /// of a user in the operator role.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if getting the tags for the user fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the user identified by `user_id` does not exist
    /// * the user identified by `user_id` is not in the "operator" role
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, UserRole};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add a user in the operator role
    /// assert_eq!(
    ///     "user1",
    ///     nethsm.add_user(
    ///         "Operator One".to_string(),
    ///         UserRole::Operator,
    ///         "operator1-passphrase".to_string(),
    ///         Some("user1".to_string()),
    ///     )?
    /// );
    ///
    /// assert!(nethsm.get_user_tags("user1")?.is_empty());
    ///
    /// // add a tag for the user
    /// nethsm.add_user_tag("user1", "tag1")?;
    ///
    /// assert!(nethsm.get_user_tags("user1")?.contains(&"tag1".to_string()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_user_tags(&self, user_id: &str) -> Result<Vec<String>, Error> {
        Ok(users_user_id_tags_get(&self.config.borrow(), user_id)
            .map_err(|error| {
                Error::Api(format!(
                    "Getting tags of user failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Generates a new key on the device
    ///
    /// [Generates a new key](https://docs.nitrokey.com/nethsm/operation#generate-key)
    /// with custom features on the device.
    /// The provided [`KeyType`] and list of [`KeyMechanism`]s have to match:
    /// * [`KeyType::Rsa`] requires one of [`KeyMechanism::RsaDecryptionRaw`],
    ///   [`KeyMechanism::RsaDecryptionPkcs1`], [`KeyMechanism::RsaDecryptionOaepMd5`],
    ///   [`KeyMechanism::RsaDecryptionOaepSha1`], [`KeyMechanism::RsaDecryptionOaepSha224`],
    ///   [`KeyMechanism::RsaDecryptionOaepSha256`], [`KeyMechanism::RsaDecryptionOaepSha384`],
    ///   [`KeyMechanism::RsaDecryptionOaepSha512`], [`KeyMechanism::RsaSignaturePkcs1`],
    ///   [`KeyMechanism::RsaSignaturePssMd5`], [`KeyMechanism::RsaSignaturePssSha1`],
    ///   [`KeyMechanism::RsaSignaturePssSha224`], [`KeyMechanism::RsaSignaturePssSha256`],
    ///   [`KeyMechanism::RsaSignaturePssSha384`] or [`KeyMechanism::RsaSignaturePssSha512`]
    /// * [`KeyType::Curve25519`] requires [`KeyMechanism::EdDsaSignature`]
    /// * [`KeyType::EcP224`], [`KeyType::EcP256`], [`KeyType::EcP384`] and [`KeyType::EcP521`]
    ///   require [`KeyMechanism::EcdsaSignature`]
    /// * [`KeyType::Generic`] requires one of [`KeyMechanism::AesDecryptionCbc`] or
    ///   [`KeyMechanism::AesEncryptionCbc`]
    ///
    /// Optionally the key bit-length (using `length`), a custom key ID using `key_id`
    /// and a list of tags to be attached to the new key (using `tags`) can be provided.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if generating the key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided combination of `key_type` and `mechanisms` is not valid
    /// * a key identified by ` key_id` exists already
    /// * the chosen `length` or `tags` options are not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, KeyMechanism, KeyType, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // generate a Curve25519 key for signing with custom Key ID and tags
    /// nethsm.generate_key(
    ///     KeyType::Curve25519,
    ///     vec![KeyMechanism::EdDsaSignature],
    ///     None,
    ///     Some("signing1".to_string()),
    ///     Some(vec!["sign_tag1".to_string(), "sign_tag2".to_string()]),
    /// )?;
    ///
    /// // generate a generic key for symmetric encryption and decryption
    /// nethsm.generate_key(
    ///     KeyType::Generic,
    ///     vec![
    ///         KeyMechanism::AesEncryptionCbc,
    ///         KeyMechanism::AesDecryptionCbc,
    ///     ],
    ///     Some(4096),
    ///     Some("encryption1".to_string()),
    ///     Some(vec!["encryption_tag1".to_string()]),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn generate_key(
        &self,
        key_type: KeyType,
        mechanisms: Vec<KeyMechanism>,
        length: Option<i32>,
        key_id: Option<String>,
        tags: Option<Vec<String>>,
    ) -> Result<String, Error> {
        // ensure the key_type - mechanisms combinations are valid
        match_key_type_and_mechanisms(key_type, &mechanisms)?;

        Ok(keys_generate_post(
            &self.config.borrow(),
            KeyGenerateRequestData {
                mechanisms,
                r#type: key_type,
                length,
                id: key_id,
                restrictions: tags.map(|tags| Box::new(KeyRestrictions { tags: Some(tags) })),
            },
        )
        .map_err(|error| {
            Error::Api(format!(
                "Creating key failed: {}",
                NetHsmApiError::from(error)
            ))
        })?
        .entity
        .id)
    }

    /// Imports an existing private key
    ///
    /// [Imports an existing key](https://docs.nitrokey.com/nethsm/operation#import-key)
    /// with custom features into the device.
    /// The provided [`KeyType`] and list of [`KeyMechanism`]s have to match:
    /// * [`KeyType::Rsa`] requires one of [`KeyMechanism::RsaDecryptionRaw`],
    ///   [`KeyMechanism::RsaDecryptionPkcs1`], [`KeyMechanism::RsaDecryptionOaepMd5`],
    ///   [`KeyMechanism::RsaDecryptionOaepSha1`], [`KeyMechanism::RsaDecryptionOaepSha224`],
    ///   [`KeyMechanism::RsaDecryptionOaepSha256`], [`KeyMechanism::RsaDecryptionOaepSha384`],
    ///   [`KeyMechanism::RsaDecryptionOaepSha512`], [`KeyMechanism::RsaSignaturePkcs1`],
    ///   [`KeyMechanism::RsaSignaturePssMd5`], [`KeyMechanism::RsaSignaturePssSha1`],
    ///   [`KeyMechanism::RsaSignaturePssSha224`], [`KeyMechanism::RsaSignaturePssSha256`],
    ///   [`KeyMechanism::RsaSignaturePssSha384`] or [`KeyMechanism::RsaSignaturePssSha512`]
    /// * [`KeyType::Curve25519`] requires [`KeyMechanism::EdDsaSignature`]
    /// * [`KeyType::EcP224`], [`KeyType::EcP256`], [`KeyType::EcP384`] and [`KeyType::EcP521`]
    ///   require [`KeyMechanism::EcdsaSignature`]
    /// * [`KeyType::Generic`] requires one of [`KeyMechanism::AesDecryptionCbc`] or
    ///   [`KeyMechanism::AesEncryptionCbc`]
    ///
    /// Optionally a custom Key ID using `key_id` and a list of tags to be attached to the new key
    /// (using `tags`) can be provided.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if importing the key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the provided combination of `key_type` and `mechanisms` is not valid
    /// * the provided combination of `key_type` and `key_data` is not valid
    /// * a key identified by ` key_id` exists already
    /// * the chosen `tags` option is not valid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, KeyImportData, KeyMechanism, KeyType, NetHsm};
    /// use rsa::traits::PrivateKeyParts;
    /// use rsa::traits::PublicKeyParts;
    /// use rsa::RsaPrivateKey;
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // create an RSA private key and only extract prime p, q and the public exponent
    /// // (for import)
    /// let (prime_p, prime_q, public_exponent) = {
    ///     let mut rng = rand::thread_rng();
    ///     let private_key = RsaPrivateKey::new(&mut rng, 4096).unwrap();
    ///     let (prime_p, prime_q, public_exponent) = (
    ///         private_key.primes().first().unwrap(),
    ///         private_key.primes().get(1).unwrap(),
    ///         private_key.e(),
    ///     );
    ///     (
    ///         Some(prime_p.to_bytes_be()),
    ///         Some(prime_q.to_bytes_be()),
    ///         Some(public_exponent.to_bytes_be()),
    ///     )
    /// };
    /// // import an RSA key for PKCS1 signatures
    /// nethsm.import_key(
    ///     KeyType::Rsa,
    ///     vec![KeyMechanism::RsaSignaturePkcs1],
    ///     Box::new(KeyImportData {
    ///         prime_p,
    ///         prime_q,
    ///         public_exponent,
    ///         data: None,
    ///     }),
    ///     Some("signing2".to_string()),
    ///     Some(vec!["signing_tag3".to_string()]),
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn import_key(
        &self,
        key_type: KeyType,
        mechanisms: Vec<KeyMechanism>,
        key_data: Box<KeyImportData>,
        key_id: Option<String>,
        tags: Option<Vec<String>>,
    ) -> Result<String, Error> {
        // ensure the key_type - mechanisms combinations are valid
        match_key_type_and_mechanisms(key_type, &mechanisms)?;

        // ensure the key_type - key_data combination is valid
        key_data.validate_key_type(key_type)?;

        let restrictions = tags.map(|tags| Box::new(KeyRestrictions { tags: Some(tags) }));
        let private = key_data.into();

        if let Some(key_id) = key_id {
            keys_key_id_put(
                &self.config.borrow(),
                &key_id,
                nethsm_sdk_rs::apis::default_api::KeysKeyIdPutBody::ApplicationJson(PrivateKey {
                    mechanisms,
                    r#type: key_type,
                    private,
                    restrictions,
                }),
            )
            .map_err(|error| {
                Error::Api(format!(
                    "Importing key failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?;
            Ok(key_id)
        } else {
            Ok(keys_post(
                &self.config.borrow(),
                KeysPostBody::ApplicationJson(PrivateKey {
                    mechanisms,
                    r#type: key_type,
                    private,
                    restrictions,
                }),
            )
            .map_err(|error| {
                Error::Api(format!(
                    "Importing key failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .id)
        }
    }

    /// Deletes a key from the device
    ///
    /// [Deletes a key](https://docs.nitrokey.com/nethsm/operation#delete-key)
    /// from the device based on a Key ID provided using `key_id`.
    ///
    /// This call requires using credentials of a user in the "admin" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if deleting the key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // delete a key with the Key ID "signing1"
    /// assert!(nethsm.delete_key("signing1").is_ok());
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_key(&self, key_id: &str) -> Result<(), Error> {
        keys_key_id_delete(&self.config.borrow(), key_id).map_err(|error| {
            Error::Api(format!(
                "Deleting key failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Gets details of a key
    ///
    /// [Gets details of a key](https://docs.nitrokey.com/nethsm/operation#show-key-details)
    /// from the device based on a Key ID provided using `key_id`.
    ///
    /// This call requires using credentials of a user in the "admin" or "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if getting the key details fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * the used credentials are not correct
    /// * the used credentials are not those of a user in the "admin" or "operator" role
    /// * a user in the "operator" role lacks access to the key
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get details on a key with the Key ID "signing1"
    /// println!("{:?}", nethsm.get_key("signing1")?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_key(&self, key_id: &str) -> Result<PublicKey, Error> {
        Ok(keys_key_id_get(&self.config.borrow(), key_id)
            .map_err(|error| {
                Error::Api(format!(
                    "Getting key failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Gets a list of Key IDs on the device
    ///
    /// [Gets a list of Key IDs](https://docs.nitrokey.com/nethsm/operation#list-keys)
    /// from the device.
    /// Optionally `filter` can be provided for matching against Key IDs.
    ///
    /// This call requires using credentials of a user in the "admin" or "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if getting the list of Key IDs fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not those of a user in the "admin" or "operator" role
    /// * a user in the "operator" role lacks access to the key
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get all Key IDs
    /// println!("{:?}", nethsm.get_keys(None)?);
    ///
    /// // get all Key IDs that begin with "signing"
    /// println!("{:?}", nethsm.get_keys(Some("signing"))?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_keys(&self, filter: Option<&str>) -> Result<Vec<String>, Error> {
        Ok(keys_get(&self.config.borrow(), filter)
            .map_err(|error| {
                Error::Api(format!(
                    "Getting keys failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .iter()
            .map(|x| x.id.clone())
            .collect())
    }

    /// Gets the public key of a key on the device
    ///
    /// [Gets the public key of a key](https://docs.nitrokey.com/nethsm/operation#show-key-details)
    /// on the device specified by `key_id`.
    /// The public key is returned in PKCS#8 format.
    ///
    /// This call requires using credentials of a user in the "admin" or "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if getting the public key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" or "operator" role
    /// * a user in the "operator" role lacks access to the key
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get public key for a key with Key ID "signing1"
    /// println!("{:?}", nethsm.get_public_key("signing1")?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_public_key(&self, key_id: &str) -> Result<String, Error> {
        Ok(keys_key_id_public_pem_get(&self.config.borrow(), key_id)
            .map_err(|error| {
                Error::Api(format!(
                    "Getting public key failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Adds a tag to a key on the device
    ///
    /// [Adds a tag to a key](https://docs.nitrokey.com/nethsm/operation#tags-for-keys)
    /// on the device.
    /// The key is specified by `key_id` and the tag using `tag`.
    ///
    /// Afterwards the same `tag` can be associated with a user in the "operator" role, using
    /// [`NetHsm::add_user_tag`] to provide the user access to the respective key(s).
    ///
    /// This call requires using credentials of a user in the "admin"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding a tag to a key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * `tag` is already associated with the key
    /// * `tag` is invalid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" or "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // add the tag "important" to a key with Key ID "signing1"
    /// nethsm.add_key_tag("signing1", "important")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_key_tag(&self, key_id: &str, tag: &str) -> Result<(), Error> {
        keys_key_id_restrictions_tags_tag_put(&self.config.borrow(), tag, key_id).map_err(
            |error| {
                Error::Api(format!(
                    "Adding tag for key failed: {}",
                    NetHsmApiError::from(error)
                ))
            },
        )?;
        Ok(())
    }

    /// Deletes a tag from a key on the device
    ///
    /// [Deletes a tag from a key](https://docs.nitrokey.com/nethsm/operation#tags-for-keys)
    /// on the device. Any user in the "operator" role that has the same tag will lose access to the
    /// affected key.
    ///
    /// This call requires using credentials of a user in the "admin"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding a tag to a key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * `tag` is not associated with the key
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" or "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, KeyImportData, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // remove the tag "important" from a key with Key ID "signing1"
    /// nethsm.delete_key_tag("signing1", "important")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_key_tag(&self, key_id: &str, tag: &str) -> Result<(), Error> {
        keys_key_id_restrictions_tags_tag_delete(&self.config.borrow(), tag, key_id).map_err(
            |error| {
                Error::Api(format!(
                    "Deleting tag for key failed: {}",
                    NetHsmApiError::from(error)
                ))
            },
        )?;
        Ok(())
    }

    /// Imports a certificate for a key
    ///
    /// [Imports a certificate](https://docs.nitrokey.com/nethsm/operation#key-certificates)
    /// and associates it with a key on the device.
    /// Certificates are supported as the following MIME types:
    /// * *application/x-pem-file*
    /// * *application/x-x509-ca-cert*
    /// * *application/pgp-keys*
    ///
    /// This call requires using credentials of a user in the "admin"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding a tag to a key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * the `data` is invalid
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let cert_data = r#"
    /// -----BEGIN CERTIFICATE-----
    /// MIICeTCCAWECFCbuzdkAvc3Zx3W53IoSnmhUen42MA0GCSqGSIb3DQEBCwUAMHsx
    /// CzAJBgNVBAYTAkRFMQ8wDQYDVQQIDAZCZXJsaW4xDzANBgNVBAcMBkJlcmxpbjER
    /// MA8GA1UECgwITml0cm9rZXkxFTATBgNVBAMMDG5pdHJva2V5LmNvbTEgMB4GCSqG
    /// SIb3DQEJARYRaW5mb0BuaXRyb2tleS5jb20wHhcNMjIwODMwMjAxMzA2WhcNMjMw
    /// ODMwMjAxMzA2WjBxMW8wCQYDVQQGEwJERTANBgNVBAcMBkJlcmxpbjANBgNVBAgM
    /// BkJlcmxpbjAPBgNVBAoMCE5pdHJva2V5MBMGA1UEAwwMbml0cm9rZXkuY29tMB4G
    /// CSqGSIb3DQEJARYRaW5mb0BuaXRyb2tleS5jb20wKjAFBgMrZXADIQDc58LGDY9B
    /// wbJFdXTiDalNXrDC60Sxu3eHcpnh1MSoCjANBgkqhkiG9w0BAQsFAAOCAQEAGip8
    /// aU5nJnzm3eic3t1ihUA3VJ0mAPyfrb1Rn8tEKOZo3vg0jpRd9CSESlBsKqhvxsdQ
    /// A3eomM+W7R37TL5+ISm5QrbijLHz3OHoPM68c1Krz3bXTkJetf4YAxpLOPYfXXHv
    /// weRzwVJb4y3E0lJGhZxI3sUE8Yn/T1UvTbu/o/O5P/XTA8vfFrSNQkQxWBgYh4gC
    /// KjFFALqUPFrctSFIi34aqpdihNJWnjSS2Y7INm3oxwkR3NMKP8x4wBGfZK22nHnu
    /// PPzXuMGJTmQM8GHTzltNvLx5Iv2sXoSHClXSpdIT5IBIcR1GmZ78fmcr75OAU0+z
    /// 3XbJq/1ij3tKsjV6WA==
    /// -----END CERTIFICATE-----
    /// "#
    /// .to_string();
    ///
    /// // import a certificate for a key with Key ID "signing1"
    /// nethsm.import_key_certificate("signing1", cert_data.into_bytes())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn import_key_certificate(&self, key_id: &str, data: Vec<u8>) -> Result<(), Error> {
        keys_key_id_cert_put(&self.config.borrow(), key_id, data).map_err(|error| {
            Error::Api(format!(
                "Importing certificate for key failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Gets the certificate associated with a key
    ///
    /// [Gets the certificate](https://docs.nitrokey.com/nethsm/operation#key-certificates)
    /// associated with a key on the device.
    ///
    /// This call requires using credentials of a user in the "admin" or "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding a tag to a key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * no certificate is associated with the key
    /// * the user lacks access to the key
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" or "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get the certificate associated with a key
    /// println!("{:?}", nethsm.get_key_certificate("signing1")?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_key_certificate(&self, key_id: &str) -> Result<Vec<u8>, Error> {
        Ok(keys_key_id_cert_get(&self.config.borrow(), key_id)
            .map_err(|error| {
                Error::Api(format!(
                    "Getting certificate for key failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity)
    }

    /// Deletes the certificate associated with a key
    ///
    /// [Deletes a certificate](https://docs.nitrokey.com/nethsm/operation#key-certificates)
    /// associated with a key on the device.
    ///
    /// This call requires using credentials of a user in the "admin"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding a tag to a key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * no certificate is associated with the key
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // delete a certificate for a key with Key ID "signing1"
    /// nethsm.delete_key_certificate("signing1")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete_key_certificate(&self, key_id: &str) -> Result<(), Error> {
        keys_key_id_cert_delete(&self.config.borrow(), key_id).map_err(|error| {
            Error::Api(format!(
                "Deleting certificate for key failed: {}",
                NetHsmApiError::from(error)
            ))
        })?;
        Ok(())
    }

    /// Gets a Certificate Signing Request (CSR) for a key
    ///
    /// Based on data from an instance of [`nethsm_sdk_rs::models::DistinguishedName`] returns a
    /// [Certificate Signing Request (CSR)](https://en.wikipedia.org/wiki/Certificate_signing_request)
    /// in [PKCS#10](https://en.wikipedia.org/wiki/Certificate_signing_request#Structure_of_a_PKCS_#10_CSR) format
    /// for [a certificate](https://docs.nitrokey.com/nethsm/operation#key-certificate-signing-requests)
    /// associated with a key on the device.
    ///
    /// This call requires using credentials of a user in the "admin" or "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if adding a tag to a key fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists
    /// * no certificate is associated with the key
    /// * the user lacks access to the key
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "admin" or "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, DistinguishedName, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // get a CSR for a certificate associated with a key
    /// println!(
    ///     "{}",
    ///     nethsm.get_key_csr(
    ///         "signing1",
    ///         DistinguishedName {
    ///             country_name: Some("DE".to_string()),
    ///             state_or_province_name: Some("Berlin".to_string()),
    ///             locality_name: Some("Berlin".to_string()),
    ///             organization_name: Some("Foobar Inc".to_string()),
    ///             organizational_unit_name: Some("Department of Foo".to_string()),
    ///             common_name: "Foobar Inc".to_string(),
    ///             email_address: Some("foobar@mcfooface.com".to_string()),
    ///         }
    ///     )?
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_key_csr(
        &self,
        key_id: &str,
        distinguished_name: DistinguishedName,
    ) -> Result<String, Error> {
        Ok(
            keys_key_id_csr_pem_post(&self.config.borrow(), key_id, distinguished_name)
                .map_err(|error| {
                    Error::Api(format!(
                        "Getting CSR for key failed: {}",
                        NetHsmApiError::from(error)
                    ))
                })?
                .entity,
        )
    }

    /// Signs a message using a key
    ///
    /// [Signs](https://docs.nitrokey.com/nethsm/operation#sign) a `message` using a key
    /// identified by `key_id` and a specific `signature_type`.
    ///
    /// The `message` does not have to be hashed, as this function takes care of this based on the
    /// provided [`SignatureType`].
    ///
    /// This call requires using credentials of a user in the "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if signing the message fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists on the device
    /// * the chosen [`SignatureType`] is incompatible with the targeted key
    /// * the user lacks access to the key
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SignatureType};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // create an ed25519 signature
    /// // this assumes the key with Key ID "signing1" is of type KeyType::Curve25519
    /// println!(
    ///     "{:?}",
    ///     nethsm.sign("signing1", SignatureType::EdDsa, b"message")?
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn sign(
        &self,
        key_id: &str,
        signature_type: SignatureType,
        message: &[u8],
    ) -> Result<Vec<u8>, Error> {
        // Some algorithms require the data to be hashed first
        // The API requires data to be base64 encoded
        let message = match signature_type {
            SignatureType::Pkcs1 | SignatureType::PssSha256 | SignatureType::EcdsaP256 => {
                let mut hasher = Sha256::new();
                hasher.update(message);
                Base64::encode_string(&hasher.finalize()[..])
            }
            SignatureType::PssMd5 => {
                let mut hasher = Md5::new();
                hasher.update(message);
                Base64::encode_string(&hasher.finalize()[..])
            }
            SignatureType::PssSha1 => {
                let mut hasher = Sha1::new();
                hasher.update(message);
                Base64::encode_string(&hasher.finalize()[..])
            }
            SignatureType::PssSha224 | SignatureType::EcdsaP224 => {
                let mut hasher = Sha224::new();
                hasher.update(message);
                Base64::encode_string(&hasher.finalize()[..])
            }
            SignatureType::PssSha384 | SignatureType::EcdsaP384 => {
                let mut hasher = Sha384::new();
                hasher.update(message);
                Base64::encode_string(&hasher.finalize()[..])
            }
            SignatureType::PssSha512 | SignatureType::EcdsaP521 => {
                let mut hasher = Sha512::new();
                hasher.update(message);
                Base64::encode_string(&hasher.finalize()[..])
            }
            SignatureType::EdDsa => Base64::encode_string(message),
        };

        // decode base64 encoded data from the API
        Base64::decode_vec(
            &keys_key_id_sign_post(
                &self.config.borrow(),
                key_id,
                SignRequestData::new(signature_type.into(), message),
            )
            .map_err(|error| {
                Error::Api(format!(
                    "Signing message failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .signature,
        )
        .map_err(Error::Base64Decode)
    }

    /// Encrypts a message using a symmetric key
    ///
    /// [Encrypts](https://docs.nitrokey.com/nethsm/operation#encrypt) a `message` using a *symmetric* key
    /// identified by `key_id`, a specific [`EncryptMode`] `mode` and initialization vector `iv`.
    ///
    /// The targeted key must be of type [`KeyType::Generic`] and feature the mechanism
    /// [`KeyMechanism::AesDecryptionCbc`] and [`KeyMechanism::AesEncryptionCbc`].
    ///
    /// This call requires using credentials of a user in the "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if signing the message fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists on the device
    /// * the chosen `mode` is incompatible with the targeted key
    /// * the user lacks access to the key
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, EncryptMode, Error, NetHsm};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // assuming we have an AES128 encryption key, the message must be a multiple of 32 bytes long
    /// let message = b"Hello World! This is a message!!";
    /// // we have an AES128 encryption key. the initialization vector must be a multiple of 16 bytes long
    /// let iv = b"This is unsafe!!";
    ///
    /// // encrypt message using
    /// println!(
    ///     "{:?}",
    ///     nethsm.encrypt("signing1", EncryptMode::AesCbc, message, Some(iv))?
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn encrypt(
        &self,
        key_id: &str,
        mode: EncryptMode,
        message: &[u8],
        iv: Option<&[u8]>,
    ) -> Result<Vec<u8>, Error> {
        // the API requires data to be base64 encoded
        let message = Base64::encode_string(message);
        let iv = iv.map(Base64::encode_string);

        // decode base64 encoded data from the API
        Base64::decode_vec(
            &keys_key_id_encrypt_post(
                &self.config.borrow(),
                key_id,
                EncryptRequestData { mode, message, iv },
            )
            .map_err(|error| {
                Error::Api(format!(
                    "Encrypting message failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .encrypted,
        )
        .map_err(Error::Base64Decode)
    }

    /// Decrypts a message using a key
    ///
    /// [Decrypts](https://docs.nitrokey.com/nethsm/operation#decrypt) a `message` using a key
    /// identified by `key_id`, a specific [`DecryptMode`] `mode` and initialization vector `iv`.
    ///
    /// This function can be used to decrypt messages encrypted using a symmetric key (e.g. using
    /// [`NetHsm::encrypt`]) by providing [`DecryptMode::AesCbc`] as `mode`. The targeted key must
    /// be of type [`KeyType::Generic`] and feature the mechanism
    /// [`KeyMechanism::AesDecryptionCbc`] and [`KeyMechanism::AesEncryptionCbc`].
    ///
    /// Decryption for messages encrypted using asymmetric keys is also possible. Foreign entities
    /// can use the public key of an asymmetric key (see [`NetHsm::get_public_key`]) to encrypt a
    /// message and the private key on the device is used for decryption.
    ///
    /// This call requires using credentials of a user in the "operator"
    /// [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if signing the message fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * no key identified by `key_id` exists on the device
    /// * the chosen `mode` is incompatible with the targeted key
    /// * the user lacks access to the key
    /// * the encrypted message can not be decrypted
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, DecryptMode, EncryptMode, Error, NetHsm};
    /// use rsa::pkcs8::DecodePublicKey;
    /// use rsa::Pkcs1v15Encrypt;
    /// use rsa::RsaPublicKey;
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "admin" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("admin".to_string(), Some("admin-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// // assuming we have an AES128 encryption key, the message must be a multiple of 32 bytes long
    /// let message = "Hello World! This is a message!!".to_string();
    /// // we have an AES128 encryption key. the initialization vector must be a multiple of 16 bytes long
    /// let iv = "This is unsafe!!".to_string();
    ///
    /// // encrypt message using a symmetric key
    /// let encrypted_message = nethsm.encrypt("encryption1", EncryptMode::AesCbc, message.as_bytes(), Some(iv.as_bytes()))?;
    ///
    /// // decrypt message using the same symmetric key and the same initialization vector
    /// assert_eq!(
    ///     message.as_bytes(),
    ///     &nethsm.decrypt("encryption1", DecryptMode::AesCbc, &encrypted_message, Some(iv.as_bytes()))?
    /// );
    ///
    /// // get the public key of an asymmetric key and encrypt the message with it
    /// let pubkey = RsaPublicKey::from_public_key_pem(&nethsm.get_public_key("encryption2")?).unwrap();
    /// let mut rng = rand::thread_rng();
    /// let encrypted_message = pubkey.encrypt(&mut rng, Pkcs1v15Encrypt, message.as_bytes()).unwrap();
    /// println!("raw encrypted message: {:?}", encrypted_message);
    ///
    /// let decrypted_message =
    ///     nethsm.decrypt("encryption2", DecryptMode::Pkcs1, &encrypted_message, None)?;
    /// println!("raw decrypted message: {:?}", decrypted_message);
    ///
    /// assert_eq!(&decrypted_message, message.as_bytes());
    /// # Ok(())
    /// # }
    /// ```
    pub fn decrypt(
        &self,
        key_id: &str,
        mode: DecryptMode,
        message: &[u8],
        iv: Option<&[u8]>,
    ) -> Result<Vec<u8>, Error> {
        // the API requires data to be base64 encoded
        let encrypted = Base64::encode_string(message);
        let iv = iv.map(Base64::encode_string);

        // decode base64 encoded data from the API
        Base64::decode_vec(
            &keys_key_id_decrypt_post(
                &self.config.borrow(),
                key_id,
                DecryptRequestData {
                    mode,
                    encrypted,
                    iv,
                },
            )
            .map_err(|error| {
                Error::Api(format!(
                    "Decrypting message failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .decrypted,
        )
        .map_err(Error::Base64Decode)
    }

    /// Get random bytes
    ///
    /// Retrieves `length` [random](https://docs.nitrokey.com/nethsm/operation#random) bytes
    /// from the device, if it is in state [`SystemState::Operational`].
    ///
    /// This call requires using credentials of a user in the "operator" [role](https://docs.nitrokey.com/nethsm/administration#roles).
    ///
    /// # Errors
    ///
    /// Returns an [`Error::Api`] if retrieving random bytes fails:
    /// * the device is not in state [`SystemState::Operational`]
    /// * the used credentials are not correct
    /// * the used credentials are not that of a user in the "operator" role
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nethsm::{ConnectionSecurity, Error, NetHsm, SystemState};
    ///
    /// # fn main() -> Result<(), Error> {
    /// // create a connection with a user in the "operator" role
    /// let nethsm = NetHsm::new(
    ///     "https://example.org/api/v1".to_string(),
    ///     ConnectionSecurity::Unsafe,
    ///     Some(("user1".to_string(), Some("user1-passphrase".to_string()))),
    ///     None,
    ///     None,
    /// )?;
    ///
    /// assert_eq!(nethsm.state()?, SystemState::Operational);
    /// // get 10 random bytes
    /// println!("{:#?}", nethsm.random(10)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn random(&self, length: i32) -> Result<Vec<u8>, Error> {
        let base64_bytes = random_post(&self.config.borrow(), RandomRequestData::new(length))
            .map_err(|error| {
                Error::Api(format!(
                    "Getting random bytes failed: {}",
                    NetHsmApiError::from(error)
                ))
            })?
            .entity
            .random;
        Base64::decode_vec(&base64_bytes).map_err(Error::Base64Decode)
    }
}