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
//! Keys, their associated signatures, and some useful methods.
//!
//! A [`KeyAmalgamation`] is similar to a [`ComponentAmalgamation`],
//! but a `KeyAmalgamation` includes some additional functionality
//! that is needed to correctly implement a [`Key`] component's
//! semantics.  In particular, unlike other components where the
//! binding signature stores the component's meta-data, a Primary Key
//! doesn't have a binding signature (it is the thing that other
//! components are bound to!), and, as a consequence, the associated
//! meta-data is stored elsewhere.
//!
//! Unfortunately, a primary Key's meta-data is usually not stored on
//! a direct key signature, which would be convenient as it is located
//! at the same place as a binding signature would be, but on the
//! primary User ID's binding signature.  This requires some
//! acrobatics on the implementation side to realize the correct
//! semantics.  In particular, a `Key` needs to memorize its role
//! (i.e., whether it is a primary key or a subkey) in order to know
//! whether to consider its own self signatures or the primary User
//! ID's self signatures when looking for its meta-data.
//!
//! Ideally, a `KeyAmalgamation`'s role would be encoded in its type.
//! This increases safety, and reduces the run-time overhead.
//! However, we want [`Cert::keys`] to return an iterator over all
//! keys; we don't want the user to have to specially handle the
//! primary key when that fact is not relevant.  This means that
//! `Cert::keys` has to erase the returned `Key`s' roles: all items in
//! an iterator must have the same type.  To support this, we have to
//! keep track of a `KeyAmalgamation`'s role at run-time.
//!
//! But, just because we need to erase a `KeyAmalgamation`'s role to
//! implement `Cert::keys` doesn't mean that we have to always erase
//! it.  To achieve this, we use three data types:
//! [`PrimaryKeyAmalgamation`], [`SubordinateKeyAmalgamation`], and
//! [`ErasedKeyAmalgamation`].  The first two encode the role
//! information in their type, and the last one stores it at run time.
//! We provide conversion functions to convert the static type
//! information into dynamic type information, and vice versa.
//!
//! Note: `KeyBundle`s and `KeyAmalgamation`s have a notable
//! difference: whereas a `KeyBundle`'s role is a marker, a
//! `KeyAmalgamation`'s role determines its semantics.  A consequence
//! of this is that it is not possible to convert a
//! `PrimaryKeyAmalgamation` into a `SubordinateAmalgamation`s, or
//! vice versa even though we support changing a `KeyBundle`'s role:
//!
//! ```
//! # fn main() -> sequoia_openpgp::Result<()> {
//! # use std::convert::TryInto;
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::cert::prelude::*;
//! # use openpgp::packet::prelude::*;
//! # let (cert, _) = CertBuilder::new()
//! #     .add_userid("Alice")
//! #     .add_signing_subkey()
//! #     .add_transport_encryption_subkey()
//! #     .generate()?;
//! // This works:
//! cert.primary_key().bundle().role_as_subordinate();
//!
//! // But this doesn't:
//! let ka: ErasedKeyAmalgamation<_> = cert.keys().nth(0).expect("primary key");
//! let ka: openpgp::Result<SubordinateKeyAmalgamation<key::PublicParts>> = ka.try_into();
//! assert!(ka.is_err());
//! # Ok(()) }
//! ```
//!
//! The use of the prefix `Erased` instead of `Unspecified`
//! (cf. [`KeyRole::UnspecifiedRole`]) emphasizes this.
//!
//! # Selecting Keys
//!
//! It is essential to choose the right keys, and to make sure that
//! they are appropriate.  Below, we present some guidelines for the most
//! common situations.
//!
//! ## Encrypting and Signing Messages
//!
//! As a general rule of thumb, when encrypting or signing a message,
//! you want to use keys that are alive, not revoked, and have the
//! appropriate capabilities right now.  For example, the following
//! code shows how to find a key, which is appropriate for signing a
//! message:
//!
//! ```rust
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::Result;
//! # use openpgp::cert::prelude::*;
//! use openpgp::types::RevocationStatus;
//! use sequoia_openpgp::policy::StandardPolicy;
//!
//! # fn main() -> Result<()> {
//! #     let (cert, _) =
//! #         CertBuilder::general_purpose(None, Some("alice@example.org"))
//! #         .generate()?;
//! #     let mut i = 0;
//! let p = &StandardPolicy::new();
//!
//! let cert = cert.with_policy(p, None)?;
//!
//! if let RevocationStatus::Revoked(_) = cert.revocation_status() {
//!     // The certificate is revoked, don't use any keys from it.
//! #   unreachable!();
//! } else if let Err(_) = cert.alive() {
//!     // The certificate is not alive, don't use any keys from it.
//! #   unreachable!();
//! } else {
//!     for ka in cert.keys() {
//!         if let RevocationStatus::Revoked(_) = ka.revocation_status() {
//!             // The key is revoked.
//! #           unreachable!();
//!         } else if let Err(_) = ka.alive() {
//!             // The key is not alive.
//! #           unreachable!();
//!         } else if ! ka.for_signing() {
//!             // The key is not signing capable.
//!         } else {
//!             // Use it!
//! #           i += 1;
//!         }
//!     }
//! }
//! # assert_eq!(i, 1);
//! #     Ok(())
//! # }
//! ```
//!
//! ## Verifying a Message
//!
//! When verifying a message, you only want to use keys that were
//! alive, not revoked, and signing capable *when the message was
//! signed*.  These are the keys that the signer would have used, and
//! they reflect the signer's policy when they made the signature.
//! (See the [`Policy` discussion] for an explanation.)
//!
//! For version 4 Signature packets, the `Signature Creation Time`
//! subpacket indicates when the signature was allegedly created.  For
//! the purpose of finding the key to verify the signature, this time
//! stamp should be trusted: if the key is authenticated and the
//! signature is valid, then the time stamp is valid; if the signature
//! is not valid, then forging the time stamp won't help an attacker.
//!
//! ```rust
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::Result;
//! # use openpgp::cert::prelude::*;
//! use openpgp::types::RevocationStatus;
//! use sequoia_openpgp::policy::StandardPolicy;
//!
//! # fn main() -> Result<()> {
//! let p = &StandardPolicy::new();
//!
//! #     let (cert, _) =
//! #         CertBuilder::general_purpose(None, Some("alice@example.org"))
//! #         .generate()?;
//! #     let timestamp = None;
//! #     let issuer = cert.with_policy(p, None)?.keys()
//! #         .for_signing().nth(0).unwrap().fingerprint();
//! #     let mut i = 0;
//! let cert = cert.with_policy(p, timestamp)?;
//! if let RevocationStatus::Revoked(_) = cert.revocation_status() {
//!     // The certificate is revoked, don't use any keys from it.
//! #   unreachable!();
//! } else if let Err(_) = cert.alive() {
//!     // The certificate is not alive, don't use any keys from it.
//! #   unreachable!();
//! } else {
//!     for ka in cert.keys().key_handle(issuer) {
//!         if let RevocationStatus::Revoked(_) = ka.revocation_status() {
//!             // The key is revoked, don't use it!
//! #           unreachable!();
//!         } else if let Err(_) = ka.alive() {
//!             // The key was not alive when the signature was made!
//!             // Something fishy is going on.
//! #           unreachable!();
//!         } else if ! ka.for_signing() {
//!             // The key was not signing capable!  Better be safe
//!             // than sorry.
//! #           unreachable!();
//!         } else {
//!             // Try verifying the message with this key.
//! #           i += 1;
//!         }
//!     }
//! }
//! #     assert_eq!(i, 1);
//! #     Ok(())
//! # }
//! ```
//!
//! ## Decrypting a Message
//!
//! When decrypting a message, it seems like one ought to only use keys
//! that were alive, not revoked, and encryption-capable when the
//! message was encrypted.  Unfortunately, we don't know when a
//! message was encrypted.  But anyway, due to the slow propagation of
//! revocation certificates, we can't assume that senders won't
//! mistakenly use a revoked key.
//!
//! However, wanting to decrypt a message encrypted using an expired
//! or revoked key is reasonable.  If someone is trying to decrypt a
//! message using an expired key, then they are the certificate
//! holder, and probably attempting to access archived data using a
//! key that they themselves revoked!  We don't want to prevent that.
//!
//! We do, however, want to check whether a key is really encryption
//! capable.  [This discussion] explains why using a signing key to
//! decrypt a message can be dangerous.  Since we need a binding
//! signature to determine this, but we don't have the time that the
//! message was encrypted, we need a workaround.  One approach would
//! be to check whether the key is encryption capable now.  Since a
//! key's key flags don't typically change, this will correctly filter
//! out keys that are not encryption capable.  But, it will skip keys
//! whose self signature has expired.  But that is not a problem
//! either: no one sets self signatures to expire; if anything, they
//! set keys to expire.  Thus, this will not result in incorrectly
//! failing to decrypt messages in practice, and is a reasonable
//! approach.
//!
//! ```rust
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::Result;
//! # use openpgp::cert::prelude::*;
//! use sequoia_openpgp::policy::StandardPolicy;
//!
//! # fn main() -> Result<()> {
//! let p = &StandardPolicy::new();
//!
//! #     let (cert, _) =
//! #         CertBuilder::general_purpose(None, Some("alice@example.org"))
//! #         .generate()?;
//! let decryption_keys = cert.keys().with_policy(p, None)
//!     .for_storage_encryption().for_transport_encryption()
//!     .collect::<Vec<_>>();
//! #     Ok(())
//! # }
//! ```
//!
//! [`ComponentAmalgamation`]: super::ComponentAmalgamation
//! [`Key`]: crate::packet::key
//! [`Cert::keys`]: super::super::Cert::keys()
//! [`PrimaryKeyAmalgamation`]: super::PrimaryKeyAmalgamation
//! [`SubordinateKeyAmalgamation`]: super::SubordinateKeyAmalgamation
//! [`ErasedKeyAmalgamation`]: super::ErasedKeyAmalgamation
//! [`KeyRole::UnspecifiedRole`]: crate::packet::key::KeyRole
//! [`Policy` discussion]: super
//! [This discussion]: https://crypto.stackexchange.com/a/12138
use std::time;
use std::time::SystemTime;
use std::ops::Deref;
use std::borrow::Borrow;
use std::convert::TryFrom;
use std::convert::TryInto;

use anyhow::Context;

use crate::{
    Cert,
    cert::bundle::KeyBundle,
    cert::amalgamation::{
        ComponentAmalgamation,
        ValidAmalgamation,
        ValidateAmalgamation,
    },
    cert::ValidCert,
    crypto::Signer,
    Error,
    packet::Key,
    packet::key,
    packet::Signature,
    packet::signature,
    packet::signature::subpacket::SubpacketTag,
    policy::Policy,
    Result,
    seal,
    types::{
        KeyFlags,
        RevocationKey,
        RevocationStatus,
        SignatureType,
    },
};

mod iter;
pub use iter::{
    KeyAmalgamationIter,
    ValidKeyAmalgamationIter,
};

/// Whether the key is a primary key.
///
/// This trait is an implementation detail.  It exists so that we can
/// have a blanket implementation of [`ValidAmalgamation`] for
/// [`ValidKeyAmalgamation`], for instance, even though we only have
/// specialized implementations of `PrimaryKey`.
///
/// [`ValidAmalgamation`]: super::ValidAmalgamation
///
/// # Sealed trait
///
/// This trait is [sealed] and cannot be implemented for types outside this crate.
/// Therefore it can be extended in a non-breaking way.
/// If you want to implement the trait inside the crate
/// you also need to implement the `seal::Sealed` marker trait.
///
/// [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
pub trait PrimaryKey<'a, P, R>: seal::Sealed
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
{
    /// Returns whether the key amalgamation is a primary key
    /// amalgamation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::policy::StandardPolicy;
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// #     let p = &StandardPolicy::new();
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// #     let fpr = cert.fingerprint();
    /// // This works if the type is concrete:
    /// let ka: PrimaryKeyAmalgamation<_> = cert.primary_key();
    /// assert!(ka.primary());
    ///
    /// // Or if it has been erased:
    /// for (i, ka) in cert.keys().enumerate() {
    ///     let ka: ErasedKeyAmalgamation<_> = ka;
    ///     if i == 0 {
    ///         // The primary key is always the first key returned by
    ///         // `Cert::keys`.
    ///         assert!(ka.primary());
    ///     } else {
    ///         // The rest are subkeys.
    ///         assert!(! ka.primary());
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    fn primary(&self) -> bool;
}

/// A key, and its associated data, and useful methods.
///
/// A `KeyAmalgamation` is like a [`ComponentAmalgamation`], but
/// specialized for keys.  Due to the requirement to keep track of the
/// key's role when it is erased ([see the module's documentation] for
/// more details), this is a different data structure rather than a
/// specialized type alias.
///
/// Generally, you won't use this type directly, but instead use
/// [`PrimaryKeyAmalgamation`], [`SubordinateKeyAmalgamation`], or
/// [`ErasedKeyAmalgamation`].
///
/// A `KeyAmalgamation` is returned by [`Cert::primary_key`], and
/// [`Cert::keys`].
///
/// `KeyAmalgamation` implements [`ValidateAmalgamation`], which
/// allows you to turn a `KeyAmalgamation` into a
/// [`ValidKeyAmalgamation`] using [`KeyAmalgamation::with_policy`].
///
/// # Examples
///
/// Iterating over all keys:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// #     let p = &StandardPolicy::new();
/// #     let (cert, _) =
/// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #         .generate()?;
/// #     let fpr = cert.fingerprint();
/// for ka in cert.keys() {
///     let ka: ErasedKeyAmalgamation<_> = ka;
/// }
/// #     Ok(())
/// # }
/// ```
///
/// Getting the primary key:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// #     let p = &StandardPolicy::new();
/// #     let (cert, _) =
/// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #         .generate()?;
/// #     let fpr = cert.fingerprint();
/// let ka: PrimaryKeyAmalgamation<_> = cert.primary_key();
/// #     Ok(())
/// # }
/// ```
///
/// Iterating over just the subkeys:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// # use openpgp::policy::StandardPolicy;
/// #
/// # fn main() -> openpgp::Result<()> {
/// #     let p = &StandardPolicy::new();
/// #     let (cert, _) =
/// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
/// #         .generate()?;
/// #     let fpr = cert.fingerprint();
/// // We can skip the primary key (it's always first):
/// for ka in cert.keys().skip(1) {
///     let ka: ErasedKeyAmalgamation<_> = ka;
/// }
///
/// // Or use `subkeys`, which returns a more accurate type:
/// for ka in cert.keys().subkeys() {
///     let ka: SubordinateKeyAmalgamation<_> = ka;
/// }
/// #     Ok(())
/// # }
/// ```
///
/// [`ComponentAmalgamation`]: super::ComponentAmalgamation
/// [see the module's documentation]: self
/// [`Cert::primary_key`]: crate::cert::Cert::primary_key()
/// [`Cert::keys`]: crate::cert::Cert::keys()
/// [`ValidateAmalgamation`]: super::ValidateAmalgamation
/// [`KeyAmalgamation::with_policy`]: super::ValidateAmalgamation::with_policy()
#[derive(Debug)]
pub struct KeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
{
    ca: ComponentAmalgamation<'a, Key<P, R>>,
    primary: R2,
}
assert_send_and_sync!(KeyAmalgamation<'_, P, R, R2>
    where P: key::KeyParts,
          R: key::KeyRole,
          R2,
);

// derive(Clone) doesn't work with generic parameters that don't
// implement clone.  But, we don't need to require that C implements
// Clone, because we're not cloning C, just the reference.
//
// See: https://github.com/rust-lang/rust/issues/26925
impl<'a, P, R, R2> Clone for KeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
{
    fn clone(&self) -> Self {
        Self {
            ca: self.ca.clone(),
            primary: self.primary,
        }
    }
}


/// A primary key amalgamation.
///
/// A specialized version of [`KeyAmalgamation`].
///
pub type PrimaryKeyAmalgamation<'a, P>
    = KeyAmalgamation<'a, P, key::PrimaryRole, ()>;

/// A subordinate key amalgamation.
///
/// A specialized version of [`KeyAmalgamation`].
///
pub type SubordinateKeyAmalgamation<'a, P>
    = KeyAmalgamation<'a, P, key::SubordinateRole, ()>;

/// An amalgamation whose role is not known at compile time.
///
/// A specialized version of [`KeyAmalgamation`].
///
/// Unlike a [`Key`] or a [`KeyBundle`] with an unspecified role, an
/// `ErasedKeyAmalgamation` remembers its role; it is just not exposed
/// to the type system.  For details, see the [module-level
/// documentation].
///
/// [`Key`]: crate::packet::key
/// [`KeyBundle`]: super::super::bundle
/// [module-level documentation]: self
pub type ErasedKeyAmalgamation<'a, P>
    = KeyAmalgamation<'a, P, key::UnspecifiedRole, bool>;


impl<'a, P, R, R2> Deref for KeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
{
    type Target = ComponentAmalgamation<'a, Key<P, R>>;

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


impl<'a, P> seal::Sealed
    for PrimaryKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::PrimaryRole>>
    for PrimaryKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    type V = ValidPrimaryKeyAmalgamation<'a, P>;

    fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
        -> Result<Self::V>
        where T: Into<Option<time::SystemTime>>
    {
        let ka : ErasedKeyAmalgamation<P> = self.into();
        Ok(ka.with_policy(policy, time)?
               .try_into().expect("conversion is symmetric"))
    }
}

impl<'a, P> seal::Sealed
    for SubordinateKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::SubordinateRole>>
    for SubordinateKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    type V = ValidSubordinateKeyAmalgamation<'a, P>;

    fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
        -> Result<Self::V>
        where T: Into<Option<time::SystemTime>>
    {
        let ka : ErasedKeyAmalgamation<P> = self.into();
        Ok(ka.with_policy(policy, time)?
               .try_into().expect("conversion is symmetric"))
    }
}

impl<'a, P> seal::Sealed
    for ErasedKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{}
impl<'a, P> ValidateAmalgamation<'a, Key<P, key::UnspecifiedRole>>
    for ErasedKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    type V = ValidErasedKeyAmalgamation<'a, P>;

    fn with_policy<T>(self, policy: &'a dyn Policy, time: T)
        -> Result<Self::V>
        where T: Into<Option<time::SystemTime>>
    {
        let time = time.into().unwrap_or_else(crate::now);

        // We need to make sure the certificate is okay.  This means
        // checking the primary key.  But, be careful: we don't need
        // to double check.
        if ! self.primary() {
            let pka = PrimaryKeyAmalgamation::new(self.cert());
            pka.with_policy(policy, time).context("primary key")?;
        }

        let binding_signature = self.binding_signature(policy, time)?;
        let cert = self.ca.cert();
        let vka = ValidErasedKeyAmalgamation {
            ka: KeyAmalgamation {
                ca: self.ca.parts_into_public(),
                primary: self.primary,
            },
            // We need some black magic to avoid infinite
            // recursion: a ValidCert must be valid for the
            // specified policy and reference time.  A ValidCert
            // is consider valid if the primary key is valid.
            // ValidCert::with_policy checks that by calling this
            // function.  So, if we call ValidCert::with_policy
            // here we'll recurse infinitely.
            //
            // But, hope is not lost!  We know that if we get
            // here, we've already checked that the primary key is
            // valid (see above), or that we're in the process of
            // evaluating the primary key's validity and we just
            // need to check the user's policy.  So, it is safe to
            // create a ValidCert from scratch.
            cert: ValidCert {
                cert,
                policy,
                time,
            },
            binding_signature
        };
        policy.key(&vka)?;
        Ok(ValidErasedKeyAmalgamation {
            ka: KeyAmalgamation {
                ca: P::convert_key_amalgamation(
                    vka.ka.ca.parts_into_unspecified()).expect("roundtrip"),
                primary: vka.ka.primary,
            },
            cert: vka.cert,
            binding_signature,
        })
    }
}

impl<'a, P> PrimaryKey<'a, P, key::PrimaryRole>
    for PrimaryKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    fn primary(&self) -> bool {
        true
    }
}

impl<'a, P> PrimaryKey<'a, P, key::SubordinateRole>
    for SubordinateKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    fn primary(&self) -> bool {
        false
    }
}

impl<'a, P> PrimaryKey<'a, P, key::UnspecifiedRole>
    for ErasedKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    fn primary(&self) -> bool {
        self.primary
    }
}


impl<'a, P: 'a + key::KeyParts> From<PrimaryKeyAmalgamation<'a, P>>
    for ErasedKeyAmalgamation<'a, P>
{
    fn from(ka: PrimaryKeyAmalgamation<'a, P>) -> Self {
        ErasedKeyAmalgamation {
            ca: ka.ca.role_into_unspecified(),
            primary: true,
        }
    }
}

impl<'a, P: 'a + key::KeyParts> From<SubordinateKeyAmalgamation<'a, P>>
    for ErasedKeyAmalgamation<'a, P>
{
    fn from(ka: SubordinateKeyAmalgamation<'a, P>) -> Self {
        ErasedKeyAmalgamation {
            ca: ka.ca.role_into_unspecified(),
            primary: false,
        }
    }
}


// We can infallibly convert part X to part Y for everything but
// Public -> Secret and Unspecified -> Secret.
macro_rules! impl_conversion {
    ($s:ident, $primary:expr, $p1:path, $p2:path) => {
        impl<'a> From<$s<'a, $p1>>
            for ErasedKeyAmalgamation<'a, $p2>
        {
            fn from(ka: $s<'a, $p1>) -> Self {
                ErasedKeyAmalgamation {
                    ca: ka.ca.into(),
                    primary: $primary,
                }
            }
        }
    }
}

impl_conversion!(PrimaryKeyAmalgamation, true,
                 key::SecretParts, key::PublicParts);
impl_conversion!(PrimaryKeyAmalgamation, true,
                 key::SecretParts, key::UnspecifiedParts);
impl_conversion!(PrimaryKeyAmalgamation, true,
                 key::PublicParts, key::UnspecifiedParts);
impl_conversion!(PrimaryKeyAmalgamation, true,
                 key::UnspecifiedParts, key::PublicParts);

impl_conversion!(SubordinateKeyAmalgamation, false,
                 key::SecretParts, key::PublicParts);
impl_conversion!(SubordinateKeyAmalgamation, false,
                 key::SecretParts, key::UnspecifiedParts);
impl_conversion!(SubordinateKeyAmalgamation, false,
                 key::PublicParts, key::UnspecifiedParts);
impl_conversion!(SubordinateKeyAmalgamation, false,
                 key::UnspecifiedParts, key::PublicParts);


impl<'a, P, P2> TryFrom<ErasedKeyAmalgamation<'a, P>>
    for PrimaryKeyAmalgamation<'a, P2>
    where P: 'a + key::KeyParts,
          P2: 'a + key::KeyParts,
{
    type Error = anyhow::Error;

    fn try_from(ka: ErasedKeyAmalgamation<'a, P>) -> Result<Self> {
        if ka.primary {
            Ok(Self {
                ca: P2::convert_key_amalgamation(
                    ka.ca.role_into_primary().parts_into_unspecified())?,
                primary: (),
            })
        } else {
            Err(Error::InvalidArgument(
                "can't convert a SubordinateKeyAmalgamation \
                 to a PrimaryKeyAmalgamation".into()).into())
        }
    }
}

impl<'a, P, P2> TryFrom<ErasedKeyAmalgamation<'a, P>>
    for SubordinateKeyAmalgamation<'a, P2>
    where P: 'a + key::KeyParts,
          P2: 'a + key::KeyParts,
{
    type Error = anyhow::Error;

    fn try_from(ka: ErasedKeyAmalgamation<'a, P>) -> Result<Self> {
        if ka.primary {
            Err(Error::InvalidArgument(
                "can't convert a PrimaryKeyAmalgamation \
                 to a SubordinateKeyAmalgamation".into()).into())
        } else {
            Ok(Self {
                ca: P2::convert_key_amalgamation(
                    ka.ca.role_into_subordinate().parts_into_unspecified())?,
                primary: (),
            })
        }
    }
}

impl<'a> PrimaryKeyAmalgamation<'a, key::PublicParts> {
    pub(crate) fn new(cert: &'a Cert) -> Self {
        PrimaryKeyAmalgamation {
            ca: ComponentAmalgamation::new(cert, &cert.primary),
            primary: (),
        }
    }
}

impl<'a, P: 'a + key::KeyParts> SubordinateKeyAmalgamation<'a, P> {
    pub(crate) fn new(
        cert: &'a Cert, bundle: &'a KeyBundle<P, key::SubordinateRole>)
        -> Self
    {
        SubordinateKeyAmalgamation {
            ca: ComponentAmalgamation::new(cert, bundle),
            primary: (),
        }
    }
}

impl<'a, P: 'a + key::KeyParts> ErasedKeyAmalgamation<'a, P> {
    /// Returns the key's binding signature as of the reference time,
    /// if any.
    ///
    /// Note: this function is not exported.  Users of this interface
    /// should instead do: `ka.with_policy(policy,
    /// time)?.binding_signature()`.
    fn binding_signature<T>(&self, policy: &'a dyn Policy, time: T)
        -> Result<&'a Signature>
        where T: Into<Option<time::SystemTime>>
    {
        let time = time.into().unwrap_or_else(crate::now);
        if self.primary {
            self.cert().primary_userid_relaxed(policy, time, false)
                .map(|u| u.binding_signature())
                .or_else(|e0| {
                    // Lookup of the primary user id binding failed.
                    // Look for direct key signatures.
                    self.cert().primary_key().bundle()
                        .binding_signature(policy, time)
                        .map_err(|e1| {
                            // Both lookups failed.  Keep the more
                            // meaningful error.
                            if let Some(Error::NoBindingSignature(_))
                                = e1.downcast_ref()
                            {
                                e0 // Return the original error.
                            } else {
                                e1
                            }
                        })
                })
        } else {
            self.bundle().binding_signature(policy, time)
        }
    }
}


impl<'a, P, R, R2> KeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,

{
    /// Returns the `KeyAmalgamation`'s `ComponentAmalgamation`.
    pub fn component_amalgamation(&self)
        -> &ComponentAmalgamation<'a, Key<P, R>> {
        &self.ca
    }

    /// Returns the `KeyAmalgamation`'s key.
    ///
    /// Normally, a type implementing `KeyAmalgamation` eventually
    /// derefs to a `Key`, however, this method provides a more
    /// accurate lifetime.  See the documentation for
    /// `ComponentAmalgamation::component` for an explanation.
    pub fn key(&self) -> &'a Key<P, R> {
        self.ca.component()
    }
}

/// A `KeyAmalgamation` plus a `Policy` and a reference time.
///
/// In the same way that a [`ValidComponentAmalgamation`] extends a
/// [`ComponentAmalgamation`], a `ValidKeyAmalgamation` extends a
/// [`KeyAmalgamation`]: a `ValidKeyAmalgamation` combines a
/// `KeyAmalgamation`, a [`Policy`], and a reference time.  This
/// allows it to implement the [`ValidAmalgamation`] trait, which
/// provides methods like [`ValidAmalgamation::binding_signature`] that require a
/// `Policy` and a reference time.  Although `KeyAmalgamation` could
/// implement these methods by requiring that the caller explicitly
/// pass them in, embedding them in the `ValidKeyAmalgamation` helps
/// ensure that multipart operations, even those that span multiple
/// functions, use the same `Policy` and reference time.
///
/// A `ValidKeyAmalgamation` can be obtained by transforming a
/// `KeyAmalgamation` using [`ValidateAmalgamation::with_policy`].  A
/// [`KeyAmalgamationIter`] can also be changed to yield
/// `ValidKeyAmalgamation`s.
///
/// A `ValidKeyAmalgamation` is guaranteed to come from a valid
/// certificate, and have a valid and live *binding* signature at the
/// specified reference time.  Note: this only means that the binding
/// signatures are live; it says nothing about whether the
/// *certificate* or the *`Key`* is live and non-revoked.  If you care
/// about those things, you need to check them separately.
///
/// # Examples:
///
/// Find all non-revoked, live, signing-capable keys:
///
/// ```
/// # use sequoia_openpgp as openpgp;
/// # use openpgp::cert::prelude::*;
/// use openpgp::policy::StandardPolicy;
/// use openpgp::types::RevocationStatus;
///
/// # fn main() -> openpgp::Result<()> {
/// let p = &StandardPolicy::new();
///
/// # let (cert, _) = CertBuilder::new()
/// #     .add_userid("Alice")
/// #     .add_signing_subkey()
/// #     .add_transport_encryption_subkey()
/// #     .generate().unwrap();
/// // `with_policy` ensures that the certificate and any components
/// // that it returns have valid *binding signatures*.  But, we still
/// // need to check that the certificate and `Key` are not revoked,
/// // and live.
/// //
/// // Note: `ValidKeyAmalgamation::revocation_status`, etc. use the
/// // embedded policy and timestamp.  Even though we used `None` for
/// // the timestamp (i.e., now), they are guaranteed to use the same
/// // timestamp, because `with_policy` eagerly transforms it into
/// // the current time.
/// let cert = cert.with_policy(p, None)?;
/// if let RevocationStatus::Revoked(_revs) = cert.revocation_status() {
///     // Revoked by the certificate holder.  (If we care about
///     // designated revokers, then we need to check those
///     // ourselves.)
/// #   unreachable!();
/// } else if let Err(_err) = cert.alive() {
///     // Certificate was created in the future or is expired.
/// #   unreachable!();
/// } else {
///     // `ValidCert::keys` returns `ValidKeyAmalgamation`s.
///     for ka in cert.keys() {
///         if let RevocationStatus::Revoked(_revs) = ka.revocation_status() {
///             // Revoked by the key owner.  (If we care about
///             // designated revokers, then we need to check those
///             // ourselves.)
/// #           unreachable!();
///         } else if let Err(_err) = ka.alive() {
///             // Key was created in the future or is expired.
/// #           unreachable!();
///         } else if ! ka.for_signing() {
///             // We're looking for a signing-capable key, skip this one.
///         } else {
///             // Use it!
///         }
///     }
/// }
/// # Ok(()) }
/// ```
///
/// [`ValidComponentAmalgamation`]: super::ValidComponentAmalgamation
/// [`ComponentAmalgamation`]: super::ComponentAmalgamation
/// [`Policy`]: crate::policy::Policy
/// [`ValidAmalgamation`]: super::ValidAmalgamation
/// [`ValidAmalgamation::binding_signature`]: super::ValidAmalgamation::binding_signature()
/// [`ValidateAmalgamation::with_policy`]: super::ValidateAmalgamation::with_policy
#[derive(Debug, Clone)]
pub struct ValidKeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
{
    // Ouch, ouch, ouch!  ka is a `KeyAmalgamation`, which contains a
    // reference to a `Cert`.  `cert` is a `ValidCert` and contains a
    // reference to the same `Cert`!  We do this so that
    // `ValidKeyAmalgamation` can deref to a `KeyAmalgamation` and
    // `ValidKeyAmalgamation::cert` can return a `&ValidCert`.

    ka: KeyAmalgamation<'a, P, R, R2>,
    cert: ValidCert<'a>,

    // The binding signature at time `time`.  (This is just a cache.)
    binding_signature: &'a Signature,
}
assert_send_and_sync!(ValidKeyAmalgamation<'_, P, R, R2>
    where P: key::KeyParts,
          R: key::KeyRole,
          R2: Copy,
);

/// A Valid primary Key, and its associated data.
///
/// A specialized version of [`ValidKeyAmalgamation`].
///
pub type ValidPrimaryKeyAmalgamation<'a, P>
    = ValidKeyAmalgamation<'a, P, key::PrimaryRole, ()>;

/// A Valid subkey, and its associated data.
///
/// A specialized version of [`ValidKeyAmalgamation`].
///
pub type ValidSubordinateKeyAmalgamation<'a, P>
    = ValidKeyAmalgamation<'a, P, key::SubordinateRole, ()>;

/// A valid key whose role is not known at compile time.
///
/// A specialized version of [`ValidKeyAmalgamation`].
///
pub type ValidErasedKeyAmalgamation<'a, P>
    = ValidKeyAmalgamation<'a, P, key::UnspecifiedRole, bool>;


impl<'a, P, R, R2> Deref for ValidKeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
{
    type Target = KeyAmalgamation<'a, P, R, R2>;

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


impl<'a, P, R, R2> From<ValidKeyAmalgamation<'a, P, R, R2>>
    for KeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
{
    fn from(vka: ValidKeyAmalgamation<'a, P, R, R2>) -> Self {
        assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
        vka.ka
    }
}

impl<'a, P: 'a + key::KeyParts> From<ValidPrimaryKeyAmalgamation<'a, P>>
    for ValidErasedKeyAmalgamation<'a, P>
{
    fn from(vka: ValidPrimaryKeyAmalgamation<'a, P>) -> Self {
        assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
        ValidErasedKeyAmalgamation {
            ka: vka.ka.into(),
            cert: vka.cert,
            binding_signature: vka.binding_signature,
        }
    }
}

impl<'a, P: 'a + key::KeyParts> From<&ValidPrimaryKeyAmalgamation<'a, P>>
    for ValidErasedKeyAmalgamation<'a, P>
{
    fn from(vka: &ValidPrimaryKeyAmalgamation<'a, P>) -> Self {
        assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
        ValidErasedKeyAmalgamation {
            ka: vka.ka.clone().into(),
            cert: vka.cert.clone(),
            binding_signature: vka.binding_signature,
        }
    }
}

impl<'a, P: 'a + key::KeyParts> From<ValidSubordinateKeyAmalgamation<'a, P>>
    for ValidErasedKeyAmalgamation<'a, P>
{
    fn from(vka: ValidSubordinateKeyAmalgamation<'a, P>) -> Self {
        assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
        ValidErasedKeyAmalgamation {
            ka: vka.ka.into(),
            cert: vka.cert,
            binding_signature: vka.binding_signature,
        }
    }
}

impl<'a, P: 'a + key::KeyParts> From<&ValidSubordinateKeyAmalgamation<'a, P>>
    for ValidErasedKeyAmalgamation<'a, P>
{
    fn from(vka: &ValidSubordinateKeyAmalgamation<'a, P>) -> Self {
        assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
        ValidErasedKeyAmalgamation {
            ka: vka.ka.clone().into(),
            cert: vka.cert.clone(),
            binding_signature: vka.binding_signature,
        }
    }
}

// We can infallibly convert part X to part Y for everything but
// Public -> Secret and Unspecified -> Secret.
macro_rules! impl_conversion {
    ($s:ident, $p1:path, $p2:path) => {
        impl<'a> From<$s<'a, $p1>>
            for ValidErasedKeyAmalgamation<'a, $p2>
        {
            fn from(vka: $s<'a, $p1>) -> Self {
                assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
                ValidErasedKeyAmalgamation {
                    ka: vka.ka.into(),
                    cert: vka.cert,
                    binding_signature: vka.binding_signature,
                }
            }
        }

        impl<'a> From<&$s<'a, $p1>>
            for ValidErasedKeyAmalgamation<'a, $p2>
        {
            fn from(vka: &$s<'a, $p1>) -> Self {
                assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
                ValidErasedKeyAmalgamation {
                    ka: vka.ka.clone().into(),
                    cert: vka.cert.clone(),
                    binding_signature: vka.binding_signature,
                }
            }
        }
    }
}

impl_conversion!(ValidPrimaryKeyAmalgamation,
                 key::SecretParts, key::PublicParts);
impl_conversion!(ValidPrimaryKeyAmalgamation,
                 key::SecretParts, key::UnspecifiedParts);
impl_conversion!(ValidPrimaryKeyAmalgamation,
                 key::PublicParts, key::UnspecifiedParts);
impl_conversion!(ValidPrimaryKeyAmalgamation,
                 key::UnspecifiedParts, key::PublicParts);

impl_conversion!(ValidSubordinateKeyAmalgamation,
                 key::SecretParts, key::PublicParts);
impl_conversion!(ValidSubordinateKeyAmalgamation,
                 key::SecretParts, key::UnspecifiedParts);
impl_conversion!(ValidSubordinateKeyAmalgamation,
                 key::PublicParts, key::UnspecifiedParts);
impl_conversion!(ValidSubordinateKeyAmalgamation,
                 key::UnspecifiedParts, key::PublicParts);


impl<'a, P, P2> TryFrom<ValidErasedKeyAmalgamation<'a, P>>
    for ValidPrimaryKeyAmalgamation<'a, P2>
    where P: 'a + key::KeyParts,
          P2: 'a + key::KeyParts,
{
    type Error = anyhow::Error;

    fn try_from(vka: ValidErasedKeyAmalgamation<'a, P>) -> Result<Self> {
        assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
        Ok(ValidPrimaryKeyAmalgamation {
            ka: vka.ka.try_into()?,
            cert: vka.cert,
            binding_signature: vka.binding_signature,
        })
    }
}

impl<'a, P, P2> TryFrom<ValidErasedKeyAmalgamation<'a, P>>
    for ValidSubordinateKeyAmalgamation<'a, P2>
    where P: 'a + key::KeyParts,
          P2: 'a + key::KeyParts,
{
    type Error = anyhow::Error;

    fn try_from(vka: ValidErasedKeyAmalgamation<'a, P>) -> Result<Self> {
        Ok(ValidSubordinateKeyAmalgamation {
            ka: vka.ka.try_into()?,
            cert: vka.cert,
            binding_signature: vka.binding_signature,
        })
    }
}


impl<'a, P> ValidateAmalgamation<'a, Key<P, key::PrimaryRole>>
    for ValidPrimaryKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    type V = Self;

    fn with_policy<T>(self, policy: &'a dyn Policy, time: T) -> Result<Self::V>
        where T: Into<Option<time::SystemTime>>,
              Self: Sized
    {
        assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
        self.ka.with_policy(policy, time)
            .map(|vka| {
                assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
                vka
            })
    }
}

impl<'a, P> ValidateAmalgamation<'a, Key<P, key::SubordinateRole>>
    for ValidSubordinateKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    type V = Self;

    fn with_policy<T>(self, policy: &'a dyn Policy, time: T) -> Result<Self::V>
        where T: Into<Option<time::SystemTime>>,
              Self: Sized
    {
        assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
        self.ka.with_policy(policy, time)
            .map(|vka| {
                assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
                vka
            })
    }
}


impl<'a, P> ValidateAmalgamation<'a, Key<P, key::UnspecifiedRole>>
    for ValidErasedKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    type V = Self;

    fn with_policy<T>(self, policy: &'a dyn Policy, time: T) -> Result<Self::V>
        where T: Into<Option<time::SystemTime>>,
              Self: Sized
    {
        assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
        self.ka.with_policy(policy, time)
            .map(|vka| {
                assert!(std::ptr::eq(vka.ka.cert(), vka.cert.cert()));
                vka
            })
    }
}

impl<'a, P, R, R2> seal::Sealed for ValidKeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
          Self: PrimaryKey<'a, P, R>,
{}

impl<'a, P, R, R2> ValidAmalgamation<'a, Key<P, R>>
    for ValidKeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
          Self: PrimaryKey<'a, P, R>,
{
    fn cert(&self) -> &ValidCert<'a> {
        assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
        &self.cert
    }

    fn time(&self) -> SystemTime {
        self.cert.time()
    }

    fn policy(&self) -> &'a dyn Policy {
        assert!(std::ptr::eq(self.ka.cert(), self.cert.cert()));
        self.cert.policy()
    }

    fn binding_signature(&self) -> &'a Signature {
        self.binding_signature
    }

    fn revocation_status(&self) -> RevocationStatus<'a> {
        if self.primary() {
            self.cert.revocation_status()
        } else {
            self.bundle()._revocation_status(self.policy(), self.time(),
                                             true, Some(self.binding_signature))
        }
    }

    fn revocation_keys(&self)
                       -> Box<dyn Iterator<Item = &'a RevocationKey> + 'a>
    {
        let mut keys = std::collections::HashSet::new();

        let policy = self.policy();
        let pk_sec = self.cert().primary_key().hash_algo_security();

        // All valid self-signatures.
        let sec = self.hash_algo_security;
        self.self_signatures()
            .filter(move |sig| {
                policy.signature(sig, sec).is_ok()
            })
        // All direct-key signatures.
            .chain(self.cert().primary_key()
                   .self_signatures()
                   .filter(|sig| {
                       policy.signature(sig, pk_sec).is_ok()
                   }))
            .flat_map(|sig| sig.revocation_keys())
            .for_each(|rk| { keys.insert(rk); });

        Box::new(keys.into_iter())
    }
}


impl<'a, P> PrimaryKey<'a, P, key::PrimaryRole>
    for ValidPrimaryKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    fn primary(&self) -> bool {
        true
    }
}

impl<'a, P> PrimaryKey<'a, P, key::SubordinateRole>
    for ValidSubordinateKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    fn primary(&self) -> bool {
        false
    }
}

impl<'a, P> PrimaryKey<'a, P, key::UnspecifiedRole>
    for ValidErasedKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    fn primary(&self) -> bool {
        self.ka.primary
    }
}


impl<'a, P, R, R2> ValidKeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
          Self: ValidAmalgamation<'a, Key<P, R>>,
          Self: PrimaryKey<'a, P, R>,
{
    /// Returns whether the key is alive as of the amalgamation's
    /// reference time.
    ///
    /// A `ValidKeyAmalgamation` is guaranteed to have a live binding
    /// signature.  This is independent of whether the component is
    /// live.
    ///
    /// If the certificate is not alive as of the reference time, no
    /// subkey can be alive.
    ///
    /// This function considers both the binding signature and the
    /// direct key signature.  Information in the binding signature
    /// takes precedence over the direct key signature.  See [Section
    /// 5.2.3.3 of RFC 4880].
    ///
    ///   [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
    ///
    /// For a definition of liveness, see the [`key_alive`] method.
    ///
    /// [`key_alive`]: crate::packet::signature::subpacket::SubpacketAreas::key_alive()
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let (cert, _) = CertBuilder::new()
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// let ka = cert.primary_key().with_policy(p, None)?;
    /// if let Err(_err) = ka.alive() {
    ///     // Not alive.
    /// #   unreachable!();
    /// }
    /// # Ok(()) }
    /// ```
    pub fn alive(&self) -> Result<()>
    {
        if ! self.primary() {
            // First, check the certificate.
            self.cert().alive()
                .context("The certificate is not live")?;
        }

        let sig = {
            let binding : &Signature = self.binding_signature();
            if binding.key_validity_period().is_some() {
                Some(binding)
            } else {
                self.direct_key_signature().ok()
            }
        };
        if let Some(sig) = sig {
            sig.key_alive(self.key(), self.time())
                .with_context(|| if self.primary() {
                    "The primary key is not live"
                } else {
                    "The subkey is not live"
                })
        } else {
            // There is no key expiration time on the binding
            // signature.  This key does not expire.
            Ok(())
        }
    }

    /// Returns the wrapped `KeyAmalgamation`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let (cert, _) = CertBuilder::new()
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// let ka = cert.primary_key();
    ///
    /// // `with_policy` takes ownership of `ka`.
    /// let vka = ka.with_policy(p, None)?;
    ///
    /// // And here we get it back:
    /// let ka = vka.into_key_amalgamation();
    /// # Ok(()) }
    /// ```
    pub fn into_key_amalgamation(self) -> KeyAmalgamation<'a, P, R, R2> {
        self.ka
    }

}

impl<'a, P> ValidPrimaryKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    /// Sets the key to expire in delta seconds.
    ///
    /// Note: the time is relative to the key's creation time, not the
    /// current time!
    ///
    /// This function exists to facilitate testing, which is why it is
    /// not exported.
    #[cfg(test)]
    pub(crate) fn set_validity_period_as_of(&self,
                                            primary_signer: &mut dyn Signer,
                                            expiration: Option<time::Duration>,
                                            now: time::SystemTime)
        -> Result<Vec<Signature>>
    {
        ValidErasedKeyAmalgamation::<P>::from(self)
            .set_validity_period_as_of(primary_signer, None, expiration, now)
    }

    /// Creates signatures that cause the key to expire at the specified time.
    ///
    /// This function creates new binding signatures that cause the
    /// key to expire at the specified time when integrated into the
    /// certificate.  For the primary key, it is necessary to
    /// create a new self-signature for each non-revoked User ID, and
    /// to create a direct key signature.  This is needed, because the
    /// primary User ID is first consulted when determining the
    /// primary key's expiration time, and certificates can be
    /// distributed with a possibly empty subset of User IDs.
    ///
    /// Setting a key's expiry time means updating an existing binding
    /// signature---when looking up information, only one binding
    /// signature is normally considered, and we don't want to drop
    /// the other information stored in the current binding signature.
    /// This function uses the binding signature determined by
    /// `ValidKeyAmalgamation`'s policy and reference time for this.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time;
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let t = time::SystemTime::now() - time::Duration::from_secs(10);
    /// # let (cert, _) = CertBuilder::new()
    /// #     .set_creation_time(t)
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    ///
    /// // Assert that the primary key is not expired.
    /// assert!(vc.primary_key().alive().is_ok());
    ///
    /// // Make the primary key expire in a week.
    /// let t = time::SystemTime::now()
    ///     + time::Duration::from_secs(7 * 24 * 60 * 60);
    ///
    /// // We assume that the secret key material is available, and not
    /// // password protected.
    /// let mut signer = vc.primary_key()
    ///     .key().clone().parts_into_secret()?.into_keypair()?;
    ///
    /// let sigs = vc.primary_key().set_expiration_time(&mut signer, Some(t))?;
    /// let cert = cert.insert_packets(sigs)?;
    ///
    /// // The primary key isn't expired yet.
    /// let vc = cert.with_policy(p, None)?;
    /// assert!(vc.primary_key().alive().is_ok());
    ///
    /// // But in two weeks, it will be...
    /// let t = time::SystemTime::now()
    ///     + time::Duration::from_secs(2 * 7 * 24 * 60 * 60);
    /// let vc = cert.with_policy(p, t)?;
    /// assert!(vc.primary_key().alive().is_err());
    /// # Ok(()) }
    pub fn set_expiration_time(&self,
                               primary_signer: &mut dyn Signer,
                               expiration: Option<time::SystemTime>)
        -> Result<Vec<Signature>>
    {
        ValidErasedKeyAmalgamation::<P>::from(self)
            .set_expiration_time(primary_signer, None, expiration)
    }
}

impl<'a, P> ValidSubordinateKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    /// Creates signatures that cause the key to expire at the specified time.
    ///
    /// This function creates new binding signatures that cause the
    /// key to expire at the specified time when integrated into the
    /// certificate.  For subkeys, a single `Signature` is returned.
    ///
    /// Setting a key's expiry time means updating an existing binding
    /// signature---when looking up information, only one binding
    /// signature is normally considered, and we don't want to drop
    /// the other information stored in the current binding signature.
    /// This function uses the binding signature determined by
    /// `ValidKeyAmalgamation`'s policy and reference time for this.
    ///
    /// When updating the expiration time of signing-capable subkeys,
    /// we need to create a new [primary key binding signature].
    /// Therefore, we need a signer for the subkey.  If
    /// `subkey_signer` is `None`, and this is a signing-capable
    /// subkey, this function fails with [`Error::InvalidArgument`].
    /// Likewise, this function fails if `subkey_signer` is not `None`
    /// when updating the expiration of an non signing-capable subkey.
    ///
    ///   [primary key binding signature]: https://tools.ietf.org/html/rfc4880#section-5.2.1
    ///   [`Error::InvalidArgument`]: super::super::super::Error::InvalidArgument
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time;
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let t = time::SystemTime::now() - time::Duration::from_secs(10);
    /// # let (cert, _) = CertBuilder::new()
    /// #     .set_creation_time(t)
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    ///
    /// // Assert that the keys are not expired.
    /// for ka in vc.keys() {
    ///     assert!(ka.alive().is_ok());
    /// }
    ///
    /// // Make the keys expire in a week.
    /// let t = time::SystemTime::now()
    ///     + time::Duration::from_secs(7 * 24 * 60 * 60);
    ///
    /// // We assume that the secret key material is available, and not
    /// // password protected.
    /// let mut primary_signer = vc.primary_key()
    ///     .key().clone().parts_into_secret()?.into_keypair()?;
    /// let mut signing_subkey_signer = vc.keys().for_signing().nth(0).unwrap()
    ///     .key().clone().parts_into_secret()?.into_keypair()?;
    ///
    /// let mut sigs = Vec::new();
    /// for ka in vc.keys() {
    ///     if ! ka.for_signing() {
    ///         // Non-signing-capable subkeys are easy to update.
    ///         sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
    ///                                                 None, Some(t))?);
    ///     } else {
    ///         // Signing-capable subkeys need to create a primary
    ///         // key binding signature with the subkey:
    ///         assert!(ka.set_expiration_time(&mut primary_signer,
    ///                                        None, Some(t)).is_err());
    ///
    ///         // Here, we need the subkey's signer:
    ///         sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
    ///                                                 Some(&mut signing_subkey_signer),
    ///                                                 Some(t))?);
    ///     }
    /// }
    /// let cert = cert.insert_packets(sigs)?;
    ///
    /// // They aren't expired yet.
    /// let vc = cert.with_policy(p, None)?;
    /// for ka in vc.keys() {
    ///     assert!(ka.alive().is_ok());
    /// }
    ///
    /// // But in two weeks, they will be...
    /// let t = time::SystemTime::now()
    ///     + time::Duration::from_secs(2 * 7 * 24 * 60 * 60);
    /// let vc = cert.with_policy(p, t)?;
    /// for ka in vc.keys() {
    ///     assert!(ka.alive().is_err());
    /// }
    /// # Ok(()) }
    pub fn set_expiration_time(&self,
                               primary_signer: &mut dyn Signer,
                               subkey_signer: Option<&mut dyn Signer>,
                               expiration: Option<time::SystemTime>)
        -> Result<Vec<Signature>>
    {
        ValidErasedKeyAmalgamation::<P>::from(self)
            .set_expiration_time(primary_signer, subkey_signer, expiration)
    }
}

impl<'a, P> ValidErasedKeyAmalgamation<'a, P>
    where P: 'a + key::KeyParts
{
    /// Sets the key to expire in delta seconds.
    ///
    /// Note: the time is relative to the key's creation time, not the
    /// current time!
    ///
    /// This function exists to facilitate testing, which is why it is
    /// not exported.
    pub(crate) fn set_validity_period_as_of(&self,
                                            primary_signer: &mut dyn Signer,
                                            subkey_signer:
                                                Option<&mut dyn Signer>,
                                            expiration: Option<time::Duration>,
                                            now: time::SystemTime)
        -> Result<Vec<Signature>>
    {
        let mut sigs = Vec::new();

        // There are two cases to consider.  If we are extending the
        // validity of the primary key, we also need to create new
        // binding signatures for all userids.
        if self.primary() {
            // First, update or create a direct key signature.
            let template = self.direct_key_signature()
                .map(|sig| {
                    signature::SignatureBuilder::from(sig.clone())
                })
                .unwrap_or_else(|_| {
                    let mut template = signature::SignatureBuilder::from(
                        self.binding_signature().clone())
                        .set_type(SignatureType::DirectKey);

                    // We're creating a direct signature from a User
                    // ID self signature.  Remove irrelevant packets.
                    use SubpacketTag::*;
                    let ha = template.hashed_area_mut();
                    ha.remove_all(ExportableCertification);
                    ha.remove_all(Revocable);
                    ha.remove_all(TrustSignature);
                    ha.remove_all(RegularExpression);
                    ha.remove_all(PrimaryUserID);
                    ha.remove_all(SignersUserID);
                    ha.remove_all(ReasonForRevocation);
                    ha.remove_all(SignatureTarget);
                    ha.remove_all(EmbeddedSignature);

                    template
                });
            let mut builder = template
                .set_signature_creation_time(now)?
                .set_key_validity_period(expiration)?;
            builder.hashed_area_mut().remove_all(
                signature::subpacket::SubpacketTag::PrimaryUserID);

            // Generate the signature.
            sigs.push(builder.sign_direct_key(primary_signer, None)?);

            // Second, generate a new binding signature for every
            // userid.  We need to be careful not to change the
            // primary userid, so we make it explicit using the
            // primary userid subpacket.
            for userid in self.cert().userids().revoked(false) {
                // To extend the validity of the subkey, create a new
                // binding signature with updated key validity period.
                let binding_signature = userid.binding_signature();

                let builder = signature::SignatureBuilder::from(binding_signature.clone())
                    .set_signature_creation_time(now)?
                    .set_key_validity_period(expiration)?
                    .set_primary_userid(
                        self.cert().primary_userid().map(|primary| {
                            userid.userid() == primary.userid()
                        }).unwrap_or(false))?;

                sigs.push(builder.sign_userid_binding(primary_signer,
                                                      self.cert().primary_key().component(),
                                                      &userid)?);
            }
        } else {
            // To extend the validity of the subkey, create a new
            // binding signature with updated key validity period.
            let backsig = if self.for_certification() || self.for_signing()
                || self.for_authentication()
            {
                if let Some(subkey_signer) = subkey_signer {
                    Some(signature::SignatureBuilder::new(
                        SignatureType::PrimaryKeyBinding)
                         .set_signature_creation_time(now)?
                         .set_hash_algo(self.binding_signature.hash_algo())
                         .sign_primary_key_binding(
                             subkey_signer,
                             &self.cert().primary_key(),
                             self.key().role_as_subordinate())?)
                } else {
                    return Err(Error::InvalidArgument(
                        "Changing expiration of signing-capable subkeys \
                         requires subkey signer".into()).into());
                }
            } else {
                if subkey_signer.is_some() {
                    return Err(Error::InvalidArgument(
                        "Subkey signer given but subkey is not signing-capable"
                            .into()).into());
                }
                None
            };

            let mut sig =
                signature::SignatureBuilder::from(
                        self.binding_signature().clone())
                    .set_signature_creation_time(now)?
                    .set_key_validity_period(expiration)?;

            if let Some(bs) = backsig {
                sig = sig.set_embedded_signature(bs)?;
            }

            sigs.push(sig.sign_subkey_binding(
                primary_signer,
                self.cert().primary_key().component(),
                self.key().role_as_subordinate())?);
        }

        Ok(sigs)
    }

    /// Creates signatures that cause the key to expire at the specified time.
    ///
    /// This function creates new binding signatures that cause the
    /// key to expire at the specified time when integrated into the
    /// certificate.  For subkeys, only a single `Signature` is
    /// returned.  For the primary key, however, it is necessary to
    /// create a new self-signature for each non-revoked User ID, and
    /// to create a direct key signature.  This is needed, because the
    /// primary User ID is first consulted when determining the
    /// primary key's expiration time, and certificates can be
    /// distributed with a possibly empty subset of User IDs.
    ///
    /// Setting a key's expiry time means updating an existing binding
    /// signature---when looking up information, only one binding
    /// signature is normally considered, and we don't want to drop
    /// the other information stored in the current binding signature.
    /// This function uses the binding signature determined by
    /// `ValidKeyAmalgamation`'s policy and reference time for this.
    ///
    /// When updating the expiration time of signing-capable subkeys,
    /// we need to create a new [primary key binding signature].
    /// Therefore, we need a signer for the subkey.  If
    /// `subkey_signer` is `None`, and this is a signing-capable
    /// subkey, this function fails with [`Error::InvalidArgument`].
    /// Likewise, this function fails if `subkey_signer` is not `None`
    /// when updating the expiration of the primary key, or an non
    /// signing-capable subkey.
    ///
    ///   [primary key binding signature]: https://tools.ietf.org/html/rfc4880#section-5.2.1
    ///   [`Error::InvalidArgument`]: super::super::super::Error::InvalidArgument
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time;
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// # let t = time::SystemTime::now() - time::Duration::from_secs(10);
    /// # let (cert, _) = CertBuilder::new()
    /// #     .set_creation_time(t)
    /// #     .add_userid("Alice")
    /// #     .add_signing_subkey()
    /// #     .add_transport_encryption_subkey()
    /// #     .generate()?;
    /// let vc = cert.with_policy(p, None)?;
    ///
    /// // Assert that the keys are not expired.
    /// for ka in vc.keys() {
    ///     assert!(ka.alive().is_ok());
    /// }
    ///
    /// // Make the keys expire in a week.
    /// let t = time::SystemTime::now()
    ///     + time::Duration::from_secs(7 * 24 * 60 * 60);
    ///
    /// // We assume that the secret key material is available, and not
    /// // password protected.
    /// let mut primary_signer = vc.primary_key()
    ///     .key().clone().parts_into_secret()?.into_keypair()?;
    /// let mut signing_subkey_signer = vc.keys().for_signing().nth(0).unwrap()
    ///     .key().clone().parts_into_secret()?.into_keypair()?;
    ///
    /// let mut sigs = Vec::new();
    /// for ka in vc.keys() {
    ///     if ! ka.for_signing() {
    ///         // Non-signing-capable subkeys are easy to update.
    ///         sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
    ///                                                 None, Some(t))?);
    ///     } else {
    ///         // Signing-capable subkeys need to create a primary
    ///         // key binding signature with the subkey:
    ///         assert!(ka.set_expiration_time(&mut primary_signer,
    ///                                        None, Some(t)).is_err());
    ///
    ///         // Here, we need the subkey's signer:
    ///         sigs.append(&mut ka.set_expiration_time(&mut primary_signer,
    ///                                                 Some(&mut signing_subkey_signer),
    ///                                                 Some(t))?);
    ///     }
    /// }
    /// let cert = cert.insert_packets(sigs)?;
    ///
    /// // They aren't expired yet.
    /// let vc = cert.with_policy(p, None)?;
    /// for ka in vc.keys() {
    ///     assert!(ka.alive().is_ok());
    /// }
    ///
    /// // But in two weeks, they will be...
    /// let t = time::SystemTime::now()
    ///     + time::Duration::from_secs(2 * 7 * 24 * 60 * 60);
    /// let vc = cert.with_policy(p, t)?;
    /// for ka in vc.keys() {
    ///     assert!(ka.alive().is_err());
    /// }
    /// # Ok(()) }
    pub fn set_expiration_time(&self,
                               primary_signer: &mut dyn Signer,
                               subkey_signer: Option<&mut dyn Signer>,
                               expiration: Option<time::SystemTime>)
        -> Result<Vec<Signature>>
    {
        let expiration =
            if let Some(e) = expiration.map(crate::types::normalize_systemtime)
        {
            let ct = self.creation_time();
            match e.duration_since(ct) {
                Ok(v) => Some(v),
                Err(_) => return Err(Error::InvalidArgument(
                    format!("Expiration time {:?} predates creation time \
                             {:?}", e, ct)).into()),
            }
        } else {
            None
        };

        self.set_validity_period_as_of(primary_signer, subkey_signer,
                                       expiration, crate::now())
    }
}

impl<'a, P, R, R2> ValidKeyAmalgamation<'a, P, R, R2>
    where P: 'a + key::KeyParts,
          R: 'a + key::KeyRole,
          R2: Copy,
          Self: ValidAmalgamation<'a, Key<P, R>>
{
    /// Returns the key's `Key Flags`.
    ///
    /// A Key's [`Key Flags`] holds information about the key.  As of
    /// RFC 4880, this information is primarily concerned with the
    /// key's capabilities (e.g., whether it may be used for signing).
    /// The other information that has been defined is: whether the
    /// key has been split using something like [SSS], and whether the
    /// primary key material is held by multiple parties.  In
    /// practice, the latter two flags are ignored.
    ///
    /// As per [Section 5.2.3.3 of RFC 4880], when looking for the
    /// `Key Flags`, the key's binding signature is first consulted
    /// (in the case of the primary Key, this is the binding signature
    /// of the primary User ID).  If the `Key Flags` subpacket is not
    /// present, then the direct key signature is consulted.
    ///
    /// Since the key flags are taken from the active self signature,
    /// a key's flags may change depending on the policy and the
    /// reference time.
    ///
    /// To increase compatibility with early v4 certificates, if there
    /// is no key flags subpacket on the considered signatures, we
    /// infer the key flags from the key's role and public key
    /// algorithm.
    ///
    ///   [`Key Flags`]: https://tools.ietf.org/html/rfc4880#section-5.2.3.21
    ///   [SSS]: https://de.wikipedia.org/wiki/Shamir%E2%80%99s_Secret_Sharing
    ///   [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
    ///
    /// # Examples
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// # use openpgp::policy::{Policy, StandardPolicy};
    /// #
    /// # fn main() -> openpgp::Result<()> {
    /// #     let p: &dyn Policy = &StandardPolicy::new();
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// #     let cert = cert.with_policy(p, None)?;
    /// let ka = cert.primary_key();
    /// println!("Primary Key's Key Flags: {:?}", ka.key_flags());
    /// # assert!(ka.key_flags().unwrap().for_certification());
    /// # Ok(()) }
    /// ```
    pub fn key_flags(&self) -> Option<KeyFlags> {
        self.map(|s| s.key_flags())
            .or_else(|| {
                // There is no key flags subpacket.  Match on the key
                // role and algorithm and synthesize one.  We do this
                // to better support very early v4 certificates, where
                // either the binding signature is a v3 signature and
                // cannot contain subpackets, or it is a v4 signature,
                // but the key's capabilities were implied by the
                // public key algorithm.
                use crate::types::PublicKeyAlgorithm;

                // XXX: We cannot know whether this is a primary key
                // or not because of
                // https://gitlab.com/sequoia-pgp/sequoia/-/issues/1036
                let is_primary = false;

                // We only match on public key algorithms used at the
                // time.
                #[allow(deprecated)]
                match (is_primary, self.key().pk_algo()) {
                    (true, PublicKeyAlgorithm::RSAEncryptSign) =>
                        Some(KeyFlags::empty()
                             .set_certification()
                             .set_transport_encryption()
                             .set_storage_encryption()
                             .set_signing()),

                    (true, _) =>
                        Some(KeyFlags::empty()
                             .set_certification()
                             .set_signing()),

                    (false, PublicKeyAlgorithm::RSAEncryptSign) =>
                        Some(KeyFlags::empty()
                             .set_transport_encryption()
                             .set_storage_encryption()
                             .set_signing()),

                    (false,
                     | PublicKeyAlgorithm::RSASign
                     | PublicKeyAlgorithm::DSA) =>
                        Some(KeyFlags::empty().set_signing()),

                    (false,
                     | PublicKeyAlgorithm::RSAEncrypt
                     | PublicKeyAlgorithm::ElGamalEncrypt
                     | PublicKeyAlgorithm::ElGamalEncryptSign) =>
                        Some(KeyFlags::empty()
                             .set_transport_encryption()
                             .set_storage_encryption()),

                    // Be conservative: newer algorithms don't get to
                    // benefit from implicit key flags.
                    (false, _) => None,
                }
            })
    }

    /// Returns whether the key has at least one of the specified key
    /// flags.
    ///
    /// The key flags are looked up as described in
    /// [`ValidKeyAmalgamation::key_flags`].
    ///
    /// # Examples
    ///
    /// Finds keys that may be used for transport encryption (data in
    /// motion) *or* storage encryption (data at rest):
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    /// use openpgp::types::KeyFlags;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// for ka in cert.keys().with_policy(p, None) {
    ///     if ka.has_any_key_flag(KeyFlags::empty()
    ///        .set_storage_encryption()
    ///        .set_transport_encryption())
    ///     {
    ///         // `ka` is encryption capable.
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
    pub fn has_any_key_flag<F>(&self, flags: F) -> bool
        where F: Borrow<KeyFlags>
    {
        let our_flags = self.key_flags().unwrap_or_else(KeyFlags::empty);
        !(&our_flags & flags.borrow()).is_empty()
    }

    /// Returns whether the key is certification capable.
    ///
    /// Note: [Section 12.1 of RFC 4880] says that the primary key is
    /// certification capable independent of the `Key Flags`
    /// subpacket:
    ///
    /// > In a V4 key, the primary key MUST be a key capable of
    /// > certification.
    ///
    /// This function only reflects what is stored in the `Key Flags`
    /// packet; it does not implicitly set this flag.  In practice,
    /// there are keys whose primary key's `Key Flags` do not have the
    /// certification capable flag set.  Some versions of netpgp, for
    /// instance, create keys like this.  Sequoia's higher-level
    /// functionality correctly handles these keys by always
    /// considering the primary key to be certification capable.
    /// Users of this interface should too.
    ///
    /// The key flags are looked up as described in
    /// [`ValidKeyAmalgamation::key_flags`].
    ///
    /// # Examples
    ///
    /// Finds keys that are certification capable:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// for ka in cert.keys().with_policy(p, None) {
    ///     if ka.primary() || ka.for_certification() {
    ///         // `ka` is certification capable.
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// [Section 12.1 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.21
    /// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
    pub fn for_certification(&self) -> bool {
        self.has_any_key_flag(KeyFlags::empty().set_certification())
    }

    /// Returns whether the key is signing capable.
    ///
    /// The key flags are looked up as described in
    /// [`ValidKeyAmalgamation::key_flags`].
    ///
    /// # Examples
    ///
    /// Finds keys that are signing capable:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// for ka in cert.keys().with_policy(p, None) {
    ///     if ka.for_signing() {
    ///         // `ka` is signing capable.
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
    pub fn for_signing(&self) -> bool {
        self.has_any_key_flag(KeyFlags::empty().set_signing())
    }

    /// Returns whether the key is authentication capable.
    ///
    /// The key flags are looked up as described in
    /// [`ValidKeyAmalgamation::key_flags`].
    ///
    /// # Examples
    ///
    /// Finds keys that are authentication capable:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// for ka in cert.keys().with_policy(p, None) {
    ///     if ka.for_authentication() {
    ///         // `ka` is authentication capable.
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
    pub fn for_authentication(&self) -> bool
    {
        self.has_any_key_flag(KeyFlags::empty().set_authentication())
    }

    /// Returns whether the key is storage-encryption capable.
    ///
    /// OpenPGP distinguishes two types of encryption keys: those for
    /// storage ([data at rest]) and those for transport ([data in
    /// transit]).  Most OpenPGP implementations, however, don't
    /// distinguish between them in practice.  Instead, when they
    /// create a new encryption key, they just set both flags.
    /// Likewise, when encrypting a message, it is not typically
    /// possible to indicate the type of protection that is needed.
    /// Sequoia supports creating keys with only one of these flags
    /// set, and makes it easy to select the right type of key when
    /// encrypting messages.
    ///
    /// The key flags are looked up as described in
    /// [`ValidKeyAmalgamation::key_flags`].
    ///
    /// # Examples
    ///
    /// Finds keys that are storage-encryption capable:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// for ka in cert.keys().with_policy(p, None) {
    ///     if ka.for_storage_encryption() {
    ///         // `ka` is storage-encryption capable.
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// [data at rest]: https://en.wikipedia.org/wiki/Data_at_rest
    /// [data in transit]: https://en.wikipedia.org/wiki/Data_in_transit
    /// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
    pub fn for_storage_encryption(&self) -> bool
    {
        self.has_any_key_flag(KeyFlags::empty().set_storage_encryption())
    }

    /// Returns whether the key is transport-encryption capable.
    ///
    /// OpenPGP distinguishes two types of encryption keys: those for
    /// storage ([data at rest]) and those for transport ([data in
    /// transit]).  Most OpenPGP implementations, however, don't
    /// distinguish between them in practice.  Instead, when they
    /// create a new encryption key, they just set both flags.
    /// Likewise, when encrypting a message, it is not typically
    /// possible to indicate the type of protection that is needed.
    /// Sequoia supports creating keys with only one of these flags
    /// set, and makes it easy to select the right type of key when
    /// encrypting messages.
    ///
    /// The key flags are looked up as described in
    /// [`ValidKeyAmalgamation::key_flags`].
    ///
    /// # Examples
    ///
    /// Finds keys that are transport-encryption capable:
    ///
    /// ```
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// #     let (cert, _) =
    /// #         CertBuilder::general_purpose(None, Some("alice@example.org"))
    /// #         .generate()?;
    /// for ka in cert.keys().with_policy(p, None) {
    ///     if ka.for_transport_encryption() {
    ///         // `ka` is transport-encryption capable.
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// [data at rest]: https://en.wikipedia.org/wiki/Data_at_rest
    /// [data in transit]: https://en.wikipedia.org/wiki/Data_in_transit
    /// [`ValidKeyAmalgamation::key_flags`]: ValidKeyAmalgamation::key_flags()
    pub fn for_transport_encryption(&self) -> bool
    {
        self.has_any_key_flag(KeyFlags::empty().set_transport_encryption())
    }

    /// Returns how long the key is live.
    ///
    /// This returns how long the key is live relative to its creation
    /// time.  Use [`ValidKeyAmalgamation::key_expiration_time`] to
    /// get the key's absolute expiry time.
    ///
    /// This function considers both the binding signature and the
    /// direct key signature.  Information in the binding signature
    /// takes precedence over the direct key signature.  See [Section
    /// 5.2.3.3 of RFC 4880].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time;
    /// use std::convert::TryInto;
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    /// use openpgp::types::Timestamp;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// // OpenPGP Timestamps have a one-second resolution.  Since we
    /// // want to round trip the time, round it down.
    /// let now: Timestamp = time::SystemTime::now().try_into()?;
    /// let now: time::SystemTime = now.try_into()?;
    ///
    /// let a_week = time::Duration::from_secs(7 * 24 * 60 * 60);
    ///
    /// let (cert, _) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .set_creation_time(now)
    ///     .set_validity_period(a_week)
    ///     .generate()?;
    ///
    /// assert_eq!(cert.primary_key().with_policy(p, None)?.key_validity_period(),
    ///            Some(a_week));
    /// # Ok(()) }
    /// ```
    ///
    ///   [`ValidKeyAmalgamation::key_expiration_time`]: ValidKeyAmalgamation::key_expiration_time()
    ///   [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
    pub fn key_validity_period(&self) -> Option<std::time::Duration> {
        self.map(|s| s.key_validity_period())
    }

    /// Returns the key's expiration time.
    ///
    /// If this function returns `None`, the key does not expire.
    ///
    /// This returns the key's expiration time.  Use
    /// [`ValidKeyAmalgamation::key_validity_period`] to get the
    /// duration of the key's lifetime.
    ///
    /// This function considers both the binding signature and the
    /// direct key signature.  Information in the binding signature
    /// takes precedence over the direct key signature.  See [Section
    /// 5.2.3.3 of RFC 4880].
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time;
    /// use std::convert::TryInto;
    /// # use sequoia_openpgp as openpgp;
    /// # use openpgp::cert::prelude::*;
    /// use openpgp::policy::StandardPolicy;
    /// use openpgp::types::Timestamp;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// let p = &StandardPolicy::new();
    ///
    /// // OpenPGP Timestamps have a one-second resolution.  Since we
    /// // want to round trip the time, round it down.
    /// let now: Timestamp = time::SystemTime::now().try_into()?;
    /// let now: time::SystemTime = now.try_into()?;
    //
    /// let a_week = time::Duration::from_secs(7 * 24 * 60 * 60);
    /// let a_week_later = now + a_week;
    ///
    /// let (cert, _) =
    ///     CertBuilder::general_purpose(None, Some("alice@example.org"))
    ///     .set_creation_time(now)
    ///     .set_validity_period(a_week)
    ///     .generate()?;
    ///
    /// assert_eq!(cert.primary_key().with_policy(p, None)?.key_expiration_time(),
    ///            Some(a_week_later));
    /// # Ok(()) }
    /// ```
    ///
    ///   [`ValidKeyAmalgamation::key_validity_period`]: ValidKeyAmalgamation::key_validity_period()
    ///   [Section 5.2.3.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.2.3.3
    pub fn key_expiration_time(&self) -> Option<time::SystemTime> {
        match self.key_validity_period() {
            Some(vp) if vp.as_secs() > 0 => Some(self.key().creation_time() + vp),
            _ => None,
        }
    }

    // NOTE: If you add a method to ValidKeyAmalgamation that takes
    // ownership of self, then don't forget to write a forwarder for
    // it for ValidPrimaryKeyAmalgamation.
}


#[cfg(test)]
mod test {
    use crate::policy::StandardPolicy as P;
    use crate::cert::prelude::*;
    use crate::packet::Packet;

    use super::*;

    #[test]
    fn expire_subkeys() {
        let p = &P::new();

        // Timeline:
        //
        // -1: Key created with no key expiration.
        // 0: Setkeys set to expire in 1 year
        // 1: Subkeys expire

        let now = crate::now();
        let a_year = time::Duration::from_secs(365 * 24 * 60 * 60);
        let in_a_year = now + a_year;
        let in_two_years = now + 2 * a_year;

        let (cert, _) = CertBuilder::new()
            .set_creation_time(now - a_year)
            .add_signing_subkey()
            .add_transport_encryption_subkey()
            .generate().unwrap();

        for ka in cert.keys().with_policy(p, None) {
            assert!(ka.alive().is_ok());
        }

        let mut primary_signer = cert.primary_key().key().clone()
            .parts_into_secret().unwrap().into_keypair().unwrap();
        let mut signing_subkey_signer = cert.with_policy(p, None).unwrap()
            .keys().for_signing().next().unwrap()
            .key().clone().parts_into_secret().unwrap()
            .into_keypair().unwrap();

        // Only expire the subkeys.
        let sigs = cert.keys().subkeys().with_policy(p, None)
            .flat_map(|ka| {
                if ! ka.for_signing() {
                    ka.set_expiration_time(&mut primary_signer,
                                           None,
                                           Some(in_a_year)).unwrap()
                } else {
                    ka.set_expiration_time(&mut primary_signer,
                                           Some(&mut signing_subkey_signer),
                                           Some(in_a_year)).unwrap()
                }
                    .into_iter()
                    .map(Into::into)
            })
            .collect::<Vec<Packet>>();
        let cert = cert.insert_packets(sigs).unwrap();

        for ka in cert.keys().with_policy(p, None) {
            assert!(ka.alive().is_ok());
        }

        // Primary should not be expired two years from now.
        assert!(cert.primary_key().with_policy(p, in_two_years).unwrap()
                .alive().is_ok());
        // But the subkeys should be.
        for ka in cert.keys().subkeys().with_policy(p, in_two_years) {
            assert!(ka.alive().is_err());
        }
    }

    /// Test that subkeys of expired certificates are also considered
    /// expired.
    #[test]
    fn issue_564() -> Result<()> {
        use crate::parse::Parse;
        use crate::packet::signature::subpacket::SubpacketTag;
        let p = &P::new();
        let cert = Cert::from_bytes(crate::tests::key("testy.pgp"))?;
        assert!(cert.with_policy(p, None)?.alive().is_err());
        let subkey = cert.with_policy(p, None)?.keys().nth(1).unwrap();
        assert!(subkey.binding_signature().hashed_area()
                .subpacket(SubpacketTag::KeyExpirationTime).is_none());
        assert!(subkey.alive().is_err());
        Ok(())
    }

    /// When setting the primary key's validity period, we create a
    /// direct key signature.  Check that this works even when the
    /// original certificate doesn't have a direct key signature.
    #[test]
    fn set_expiry_on_certificate_without_direct_signature() -> Result<()> {
        use crate::policy::StandardPolicy;

        let p = &StandardPolicy::new();

        let (cert, _) =
            CertBuilder::general_purpose(None, Some("alice@example.org"))
            .set_validity_period(None)
            .generate()?;

        // Remove the direct key signatures.
        let cert = Cert::from_packets(Vec::from(cert)
            .into_iter()
            .filter(|p| ! matches!(
                        p,
                        Packet::Signature(s) if s.typ() == SignatureType::DirectKey
            )))?;

        let vc = cert.with_policy(p, None)?;

        // Assert that the keys are not expired.
        for ka in vc.keys() {
            assert!(ka.alive().is_ok());
        }

        // Make the primary key expire in a week.
        let t = crate::now()
            + time::Duration::from_secs(7 * 24 * 60 * 60);

        let mut signer = vc
            .primary_key().key().clone().parts_into_secret()?
            .into_keypair()?;
        let sigs = vc.primary_key()
            .set_expiration_time(&mut signer, Some(t))?;

        assert!(sigs.iter().any(|s| {
            s.typ() == SignatureType::DirectKey
        }));

        let cert = cert.insert_packets(sigs)?;

        // Make sure the primary key *and* all subkeys expire in a
        // week: the subkeys inherit the KeyExpirationTime subpacket
        // from the direct key signature.
        for ka in cert.keys() {
            let ka = ka.with_policy(p, None)?;
            assert!(ka.alive().is_ok());

            let ka = ka.with_policy(p, t + std::time::Duration::new(1, 0))?;
            assert!(ka.alive().is_err());
        }

        Ok(())
    }
}