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
//! TUF metadata.
use chrono::DateTime;
use chrono::offset::Utc;
use serde::de::{Deserialize, DeserializeOwned, Deserializer, Error as DeserializeError};
use serde::ser::{Serialize, Serializer, Error as SerializeError};
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug, Display};
use std::io::Read;
use std::iter::FromIterator;
use std::marker::PhantomData;
use Result;
use crypto::{self, KeyId, PublicKey, Signature, HashAlgorithm, HashValue, PrivateKey};
use error::Error;
use interchange::DataInterchange;
use shims;
static PATH_ILLEGAL_COMPONENTS: &'static [&str] = &[
".", // current dir
"..", // parent dir
// TODO ? "0", // may translate to nul in windows
];
static PATH_ILLEGAL_COMPONENTS_CASE_INSENSITIVE: &'static [&str] = &[
// DOS device files
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
"KEYBD$",
"CLOCK$",
"SCREEN$",
"$IDLE$",
"CONFIG$",
];
static PATH_ILLEGAL_STRINGS: &'static [&str] = &[
"\\", // for windows compatibility
"<",
">",
"\"",
"|",
"?",
"*",
// control characters, all illegal in FAT
"\u{000}",
"\u{001}",
"\u{002}",
"\u{003}",
"\u{004}",
"\u{005}",
"\u{006}",
"\u{007}",
"\u{008}",
"\u{009}",
"\u{00a}",
"\u{00b}",
"\u{00c}",
"\u{00d}",
"\u{00e}",
"\u{00f}",
"\u{010}",
"\u{011}",
"\u{012}",
"\u{013}",
"\u{014}",
"\u{015}",
"\u{016}",
"\u{017}",
"\u{018}",
"\u{019}",
"\u{01a}",
"\u{01b}",
"\u{01c}",
"\u{01d}",
"\u{01e}",
"\u{01f}",
"\u{07f}",
];
fn safe_path(path: &str) -> Result<()> {
if path.is_empty() {
return Err(Error::IllegalArgument("Path cannot be empty".into()));
}
if path.starts_with("/") {
return Err(Error::IllegalArgument("Cannot start with '/'".into()));
}
for bad_str in PATH_ILLEGAL_STRINGS {
if path.contains(bad_str) {
return Err(Error::IllegalArgument(
format!("Path cannot contain {:?}", bad_str),
));
}
}
for component in path.split('/') {
for bad_str in PATH_ILLEGAL_COMPONENTS {
if component == *bad_str {
return Err(Error::IllegalArgument(
format!("Path cannot have component {:?}", component),
));
}
}
let component_lower = component.to_lowercase();
for bad_str in PATH_ILLEGAL_COMPONENTS_CASE_INSENSITIVE {
if component_lower.as_str() == *bad_str {
return Err(Error::IllegalArgument(
format!("Path cannot have component {:?}", component),
));
}
}
}
Ok(())
}
/// The TUF role.
#[derive(Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Role {
/// The root role.
#[serde(rename = "root")]
Root,
/// The snapshot role.
#[serde(rename = "snapshot")]
Snapshot,
/// The targets role.
#[serde(rename = "targets")]
Targets,
/// The timestamp role.
#[serde(rename = "timestamp")]
Timestamp,
}
impl Role {
/// Check if this role could be associated with a given path.
///
/// ```
/// use tuf::metadata::{MetadataPath, Role};
///
/// assert!(Role::Root.fuzzy_matches_path(&MetadataPath::from_role(&Role::Root)));
/// assert!(Role::Snapshot.fuzzy_matches_path(&MetadataPath::from_role(&Role::Snapshot)));
/// assert!(Role::Targets.fuzzy_matches_path(&MetadataPath::from_role(&Role::Targets)));
/// assert!(Role::Timestamp.fuzzy_matches_path(&MetadataPath::from_role(&Role::Timestamp)));
///
/// assert!(!Role::Root.fuzzy_matches_path(&MetadataPath::from_role(&Role::Snapshot)));
/// assert!(!Role::Root.fuzzy_matches_path(&MetadataPath::new("wat".into()).unwrap()));
/// ```
pub fn fuzzy_matches_path(&self, path: &MetadataPath) -> bool {
match self {
&Role::Root if &path.0 == "root" => true,
&Role::Snapshot if &path.0 == "snapshot" => true,
&Role::Timestamp if &path.0 == "timestamp" => true,
&Role::Targets if &path.0 == "targets" => true,
&Role::Targets if !&["root", "snapshot", "targets"].contains(&path.0.as_str()) => true,
_ => false,
}
}
}
impl Display for Role {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Role::Root => write!(f, "root"),
&Role::Snapshot => write!(f, "snapshot"),
&Role::Targets => write!(f, "targets"),
&Role::Timestamp => write!(f, "timestamp"),
}
}
}
/// Enum used for addressing versioned TUF metadata.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum MetadataVersion {
/// The metadata is unversioned. This is the latest version of the metadata.
None,
/// The metadata is addressed by a specific version number.
Number(u32),
/// The metadata is addressed by a hash prefix. Used with TUF's consistent snapshot feature.
Hash(HashValue),
}
impl MetadataVersion {
/// Converts this struct into the string used for addressing metadata.
pub fn prefix(&self) -> String {
match self {
&MetadataVersion::None => String::new(),
&MetadataVersion::Number(ref x) => format!("{}.", x),
&MetadataVersion::Hash(ref v) => format!("{}.", v),
}
}
}
/// Top level trait used for role metadata.
pub trait Metadata: Debug + PartialEq + Serialize + DeserializeOwned {
/// The role associated with the metadata.
fn role() -> Role;
}
/// A piece of raw metadata with attached signatures.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignedMetadata<D, M>
where
D: DataInterchange,
M: Metadata,
{
signatures: Vec<Signature>,
signed: D::RawData,
#[serde(skip_serializing, skip_deserializing)]
_interchage: PhantomData<D>,
#[serde(skip_serializing, skip_deserializing)]
metadata: PhantomData<M>,
}
impl<D, M> SignedMetadata<D, M>
where
D: DataInterchange,
M: Metadata,
{
/// Create a new `SignedMetadata`. The supplied private key is used to sign the canonicalized
/// bytes of the provided metadata with the provided scheme.
///
/// ```
/// # extern crate chrono;
/// # extern crate tuf;
/// #
/// # use chrono::prelude::*;
/// # use tuf::crypto::{PrivateKey, SignatureScheme, HashAlgorithm};
/// # use tuf::interchange::Json;
/// # use tuf::metadata::{MetadataDescription, TimestampMetadata, SignedMetadata};
/// #
/// # fn main() {
/// # let key: &[u8] = include_bytes!("../tests/ed25519/ed25519-1.pk8.der");
/// let key = PrivateKey::from_pkcs8(&key, SignatureScheme::Ed25519).unwrap();
///
/// let timestamp = TimestampMetadata::new(
/// 1,
/// Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
/// MetadataDescription::from_reader(&*vec![0x01, 0x02, 0x03], 1,
/// &[HashAlgorithm::Sha256]).unwrap()
/// ).unwrap();
///
/// SignedMetadata::<Json, TimestampMetadata>::new(×tamp, &key).unwrap();
/// # }
/// ```
pub fn new(metadata: &M, private_key: &PrivateKey) -> Result<SignedMetadata<D, M>> {
let raw = D::serialize(metadata)?;
let bytes = D::canonicalize(&raw)?;
let sig = private_key.sign(&bytes)?;
Ok(SignedMetadata {
signatures: vec![sig],
signed: raw,
_interchage: PhantomData,
metadata: PhantomData,
})
}
/// Append a signature to this signed metadata. Will overwrite signature by keys with the same
/// ID.
///
/// **WARNING**: You should never have multiple TUF private keys on the same machine, so if
/// you're using this to append several signatures are once, you are doing something wrong. The
/// preferred method is to generate your copy of the metadata locally and use `merge_signatures`
/// to perform the "append" operations.
///
/// ```
/// # extern crate chrono;
/// # extern crate tuf;
/// #
/// # use chrono::prelude::*;
/// # use tuf::crypto::{PrivateKey, SignatureScheme, HashAlgorithm};
/// # use tuf::interchange::Json;
/// # use tuf::metadata::{MetadataDescription, TimestampMetadata, SignedMetadata};
/// #
/// # fn main() {
/// let key_1: &[u8] = include_bytes!("../tests/ed25519/ed25519-1.pk8.der");
/// let key_1 = PrivateKey::from_pkcs8(&key_1, SignatureScheme::Ed25519).unwrap();
///
/// // Note: This is for demonstration purposes only.
/// // You should never have multiple private keys on the same device.
/// let key_2: &[u8] = include_bytes!("../tests/ed25519/ed25519-2.pk8.der");
/// let key_2 = PrivateKey::from_pkcs8(&key_2, SignatureScheme::Ed25519).unwrap();
///
/// let timestamp = TimestampMetadata::new(
/// 1,
/// Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
/// MetadataDescription::from_reader(&*vec![0x01, 0x02, 0x03], 1,
/// &[HashAlgorithm::Sha256]).unwrap()
/// ).unwrap();
/// let mut timestamp = SignedMetadata::<Json, TimestampMetadata>::new(
/// ×tamp, &key_1).unwrap();
///
/// timestamp.add_signature(&key_2).unwrap();
/// assert_eq!(timestamp.signatures().len(), 2);
///
/// timestamp.add_signature(&key_2).unwrap();
/// assert_eq!(timestamp.signatures().len(), 2);
/// # }
/// ```
pub fn add_signature(&mut self, private_key: &PrivateKey) -> Result<()> {
let raw = D::serialize(&self.signed)?;
let bytes = D::canonicalize(&raw)?;
let sig = private_key.sign(&bytes)?;
self.signatures.retain(
|s| s.key_id() != private_key.key_id(),
);
self.signatures.push(sig);
Ok(())
}
/// Merge the singatures from `other` into `self` if and only if
/// `self.signed() == other.signed()`. If `self` and `other` contain signatures from the same
/// key ID, then the signatures from `self` will replace the signatures from `other`.
pub fn merge_signatures(&mut self, other: &Self) -> Result<()> {
if self.signed() != other.signed() {
return Err(Error::IllegalArgument(
"Attempted to merge unequal metadata".into(),
));
}
let key_ids = self.signatures
.iter()
.map(|s| s.key_id().clone())
.collect::<HashSet<KeyId>>();
self.signatures.extend(
other
.signatures
.iter()
.filter(|s| !key_ids.contains(s.key_id()))
.cloned(),
);
Ok(())
}
/// An immutable reference to the signatures.
pub fn signatures(&self) -> &[Signature] {
&self.signatures
}
/// A mutable reference to the signatures.
pub fn signatures_mut(&mut self) -> &mut Vec<Signature> {
&mut self.signatures
}
/// An immutable reference to the raw data.
pub fn signed(&self) -> &D::RawData {
&self.signed
}
/// Verify this metadata.
///
/// ```
/// # extern crate chrono;
/// # #[macro_use]
/// # extern crate maplit;
/// # extern crate tuf;
///
/// # use chrono::prelude::*;
/// # use tuf::crypto::{PrivateKey, SignatureScheme, HashAlgorithm};
/// # use tuf::interchange::Json;
/// # use tuf::metadata::{MetadataDescription, TimestampMetadata, SignedMetadata};
///
/// # fn main() {
/// let key_1: &[u8] = include_bytes!("../tests/ed25519/ed25519-1.pk8.der");
/// let key_1 = PrivateKey::from_pkcs8(&key_1, SignatureScheme::Ed25519).unwrap();
///
/// let key_2: &[u8] = include_bytes!("../tests/ed25519/ed25519-2.pk8.der");
/// let key_2 = PrivateKey::from_pkcs8(&key_2, SignatureScheme::Ed25519).unwrap();
///
/// let timestamp = TimestampMetadata::new(
/// 1,
/// Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
/// MetadataDescription::from_reader(&*vec![0x01, 0x02, 0x03], 1,
/// &[HashAlgorithm::Sha256]).unwrap()
/// ).unwrap();
/// let timestamp = SignedMetadata::<Json, TimestampMetadata>::new(
/// ×tamp, &key_1).unwrap();
///
/// assert!(timestamp.verify(
/// 1,
/// vec![key_1.public()],
/// ).is_ok());
///
/// // fail with increased threshold
/// assert!(timestamp.verify(
/// 2,
/// vec![key_1.public()],
/// ).is_err());
///
/// // fail when the keys aren't authorized
/// assert!(timestamp.verify(
/// 1,
/// vec![key_2.public()],
/// ).is_err());
///
/// // fail when the keys don't exist
/// assert!(timestamp.verify(
/// 1,
/// &[],
/// ).is_err());
/// # }
pub fn verify<'a, I>(&self, threshold: u32, authorized_keys: I) -> Result<()>
where
I: IntoIterator<Item = &'a PublicKey>,
{
if self.signatures.len() < 1 {
return Err(Error::VerificationFailure(
"The metadata was not signed with any authorized keys."
.into(),
));
}
if threshold < 1 {
return Err(Error::VerificationFailure(
"Threshold must be strictly greater than zero".into(),
));
}
let authorized_keys = authorized_keys
.into_iter()
.map(|k| (k.key_id(), k))
.collect::<HashMap<&KeyId, &PublicKey>>();
let canonical_bytes = D::canonicalize(&self.signed)?;
let mut signatures_needed = threshold;
for sig in self.signatures.iter() {
match authorized_keys.get(sig.key_id()) {
Some(ref pub_key) => {
match pub_key.verify(&canonical_bytes, &sig) {
Ok(()) => {
debug!("Good signature from key ID {:?}", pub_key.key_id());
signatures_needed -= 1;
}
Err(e) => {
warn!("Bad signature from key ID {:?}: {:?}", pub_key.key_id(), e);
}
}
}
None => {
warn!(
"Key ID {:?} was not found in the set of authorized keys.",
sig.key_id()
);
}
}
if signatures_needed == 0 {
break;
}
}
if signatures_needed == 0 {
Ok(())
} else {
Err(Error::VerificationFailure(format!(
"Signature threshold not met: {}/{}",
threshold - signatures_needed,
threshold
)))
}
}
}
/// Metadata for the root role.
#[derive(Debug, Clone, PartialEq)]
pub struct RootMetadata {
version: u32,
expires: DateTime<Utc>,
consistent_snapshot: bool,
keys: HashMap<KeyId, PublicKey>,
root: RoleDefinition,
snapshot: RoleDefinition,
targets: RoleDefinition,
timestamp: RoleDefinition,
}
impl RootMetadata {
/// Create new `RootMetadata`.
pub fn new(
version: u32,
expires: DateTime<Utc>,
consistent_snapshot: bool,
mut keys: Vec<PublicKey>,
root: RoleDefinition,
snapshot: RoleDefinition,
targets: RoleDefinition,
timestamp: RoleDefinition,
) -> Result<Self> {
if version < 1 {
return Err(Error::IllegalArgument(format!(
"Metadata version must be greater than zero. Found: {}",
version
)));
}
let keys_len = keys.len();
let keys = HashMap::from_iter(keys.drain(..).map(|k| (k.key_id().clone(), k)));
if keys.len() != keys_len {
return Err(Error::IllegalArgument("Cannot have duplicate keys".into()));
}
Ok(RootMetadata {
version: version,
expires: expires,
consistent_snapshot: consistent_snapshot,
keys: keys,
root: root,
snapshot: snapshot,
targets: targets,
timestamp: timestamp,
})
}
/// The version number.
pub fn version(&self) -> u32 {
self.version
}
/// An immutable reference to the metadata's expiration `DateTime`.
pub fn expires(&self) -> &DateTime<Utc> {
&self.expires
}
/// Whether or not this repository is currently implementing that TUF consistent snapshot
/// feature.
pub fn consistent_snapshot(&self) -> bool {
self.consistent_snapshot
}
/// An immutable reference to the map of trusted keys.
pub fn keys(&self) -> &HashMap<KeyId, PublicKey> {
&self.keys
}
/// An immutable reference to the root role's definition.
pub fn root(&self) -> &RoleDefinition {
&self.root
}
/// An immutable reference to the snapshot role's definition.
pub fn snapshot(&self) -> &RoleDefinition {
&self.snapshot
}
/// An immutable reference to the targets role's definition.
pub fn targets(&self) -> &RoleDefinition {
&self.targets
}
/// An immutable reference to the timestamp role's definition.
pub fn timestamp(&self) -> &RoleDefinition {
&self.timestamp
}
}
impl Metadata for RootMetadata {
fn role() -> Role {
Role::Root
}
}
impl Serialize for RootMetadata {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let m = shims::RootMetadata::from(self).map_err(|e| {
SerializeError::custom(format!("{:?}", e))
})?;
m.serialize(ser)
}
}
impl<'de> Deserialize<'de> for RootMetadata {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::RootMetadata = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// The definition of what allows a role to be trusted.
#[derive(Clone, Debug, PartialEq)]
pub struct RoleDefinition {
threshold: u32,
key_ids: HashSet<KeyId>,
}
impl RoleDefinition {
/// Create a new `RoleDefinition` with a given threshold and set of authorized `KeyID`s.
pub fn new(threshold: u32, key_ids: HashSet<KeyId>) -> Result<Self> {
if threshold < 1 {
return Err(Error::IllegalArgument(format!("Threshold: {}", threshold)));
}
if key_ids.is_empty() {
return Err(Error::IllegalArgument(
"Cannot define a role with no associated key IDs".into(),
));
}
if (key_ids.len() as u64) < (threshold as u64) {
return Err(Error::IllegalArgument(format!(
"Cannot have a threshold greater than the number of associated key IDs. {} vs. {}",
threshold,
key_ids.len()
)));
}
Ok(RoleDefinition {
threshold: threshold,
key_ids: key_ids,
})
}
/// The threshold number of signatures required for the role to be trusted.
pub fn threshold(&self) -> u32 {
self.threshold
}
/// An immutable reference to the set of `KeyID`s that are authorized to sign the role.
pub fn key_ids(&self) -> &HashSet<KeyId> {
&self.key_ids
}
}
impl Serialize for RoleDefinition {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
shims::RoleDefinition::from(self)
.map_err(|e| SerializeError::custom(format!("{:?}", e)))?
.serialize(ser)
}
}
impl<'de> Deserialize<'de> for RoleDefinition {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::RoleDefinition = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// Wrapper for a path to metadata.
///
/// Note: This should **not** contain the file extension. This is automatically added by the
/// library depending on what type of data interchange format is being used.
///
/// ```
/// use tuf::metadata::MetadataPath;
///
/// // right
/// let _ = MetadataPath::new("root".into());
///
/// // wrong
/// let _ = MetadataPath::new("root.json".into());
/// ```
#[derive(Debug, Clone, PartialEq, Hash, Eq, Serialize)]
pub struct MetadataPath(String);
impl MetadataPath {
/// Create a new `MetadataPath` from a `String`.
///
/// ```
/// # use tuf::metadata::MetadataPath;
/// assert!(MetadataPath::new("foo".into()).is_ok());
/// assert!(MetadataPath::new("/foo".into()).is_err());
/// assert!(MetadataPath::new("../foo".into()).is_err());
/// assert!(MetadataPath::new("foo/..".into()).is_err());
/// assert!(MetadataPath::new("foo/../bar".into()).is_err());
/// assert!(MetadataPath::new("..foo".into()).is_ok());
/// assert!(MetadataPath::new("foo/..bar".into()).is_ok());
/// assert!(MetadataPath::new("foo/bar..".into()).is_ok());
/// ```
pub fn new(path: String) -> Result<Self> {
safe_path(&path)?;
Ok(MetadataPath(path))
}
/// Create a metadata path from the given role.
///
/// ```
/// # use tuf::metadata::{Role, MetadataPath};
/// assert_eq!(MetadataPath::from_role(&Role::Root),
/// MetadataPath::new("root".into()).unwrap());
/// assert_eq!(MetadataPath::from_role(&Role::Snapshot),
/// MetadataPath::new("snapshot".into()).unwrap());
/// assert_eq!(MetadataPath::from_role(&Role::Targets),
/// MetadataPath::new("targets".into()).unwrap());
/// assert_eq!(MetadataPath::from_role(&Role::Timestamp),
/// MetadataPath::new("timestamp".into()).unwrap());
/// ```
pub fn from_role(role: &Role) -> Self {
Self::new(format!("{}", role)).unwrap()
}
/// Split `MetadataPath` into components that can be joined to create URL paths, Unix paths, or
/// Windows paths.
///
/// ```
/// # use tuf::crypto::HashValue;
/// # use tuf::interchange::Json;
/// # use tuf::metadata::{MetadataPath, MetadataVersion};
/// #
/// let path = MetadataPath::new("foo/bar".into()).unwrap();
/// assert_eq!(path.components::<Json>(&MetadataVersion::None),
/// ["foo".to_string(), "bar.json".to_string()]);
/// assert_eq!(path.components::<Json>(&MetadataVersion::Number(1)),
/// ["foo".to_string(), "1.bar.json".to_string()]);
/// assert_eq!(path.components::<Json>(
/// &MetadataVersion::Hash(HashValue::new(vec![0x69, 0xb7, 0x1d]))),
/// ["foo".to_string(), "abcd.bar.json".to_string()]);
/// ```
pub fn components<D>(&self, version: &MetadataVersion) -> Vec<String>
where
D: DataInterchange,
{
let mut buf: Vec<String> = self.0.split('/').map(|s| s.to_string()).collect();
let len = buf.len();
buf[len - 1] = format!("{}{}.{}", version.prefix(), buf[len - 1], D::extension());
buf
}
}
impl ToString for MetadataPath {
fn to_string(&self) -> String {
self.0.clone()
}
}
impl<'de> Deserialize<'de> for MetadataPath {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let s: String = Deserialize::deserialize(de)?;
MetadataPath::new(s).map_err(|e| DeserializeError::custom(format!("{:?}", e)))
}
}
/// Metadata for the timestamp role.
#[derive(Debug, Clone, PartialEq)]
pub struct TimestampMetadata {
version: u32,
expires: DateTime<Utc>,
snapshot: MetadataDescription,
}
impl TimestampMetadata {
/// Create new `TimestampMetadata`.
pub fn new(
version: u32,
expires: DateTime<Utc>,
snapshot: MetadataDescription,
) -> Result<Self> {
if version < 1 {
return Err(Error::IllegalArgument(format!(
"Metadata version must be greater than zero. Found: {}",
version
)));
}
Ok(TimestampMetadata {
version: version,
expires: expires,
snapshot: snapshot,
})
}
/// The version number.
pub fn version(&self) -> u32 {
self.version
}
/// An immutable reference to the metadata's expiration `DateTime`.
pub fn expires(&self) -> &DateTime<Utc> {
&self.expires
}
/// An immutable reference to the snapshot description.
pub fn snapshot(&self) -> &MetadataDescription {
&self.snapshot
}
}
impl Metadata for TimestampMetadata {
fn role() -> Role {
Role::Timestamp
}
}
impl Serialize for TimestampMetadata {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
shims::TimestampMetadata::from(self)
.map_err(|e| SerializeError::custom(format!("{:?}", e)))?
.serialize(ser)
}
}
impl<'de> Deserialize<'de> for TimestampMetadata {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::TimestampMetadata = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// Description of a piece of metadata, used in verification.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct MetadataDescription {
version: u32,
size: usize,
hashes: HashMap<HashAlgorithm, HashValue>,
}
impl MetadataDescription {
/// Create a `MetadataDescription` from a given reader. Size and hashes will be calculated.
pub fn from_reader<R: Read>(
read: R,
version: u32,
hash_algs: &[HashAlgorithm],
) -> Result<Self> {
if version < 1 {
return Err(Error::IllegalArgument(
"Version must be greater than zero".into(),
));
}
let (size, hashes) = crypto::calculate_hashes(read, hash_algs)?;
if size > ::std::usize::MAX as u64 {
return Err(Error::IllegalArgument(
"Calculated size exceeded usize".into(),
));
}
Ok(MetadataDescription {
version: version,
size: size as usize,
hashes: hashes,
})
}
/// Create a new `MetadataDescription`.
pub fn new(
version: u32,
size: usize,
hashes: HashMap<HashAlgorithm, HashValue>,
) -> Result<Self> {
if version < 1 {
return Err(Error::IllegalArgument(format!(
"Metadata version must be greater than zero. Found: {}",
version
)));
}
if hashes.is_empty() {
return Err(Error::IllegalArgument(
"Cannot have empty set of hashes".into(),
));
}
Ok(MetadataDescription {
version: version,
size: size,
hashes: hashes,
})
}
/// The version of the described metadata.
pub fn version(&self) -> u32 {
self.version
}
/// The size of the described metadata.
pub fn size(&self) -> usize {
self.size
}
/// An immutable reference to the hashes of the described metadata.
pub fn hashes(&self) -> &HashMap<HashAlgorithm, HashValue> {
&self.hashes
}
}
impl<'de> Deserialize<'de> for MetadataDescription {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::MetadataDescription = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// Metadata for the snapshot role.
#[derive(Debug, Clone, PartialEq)]
pub struct SnapshotMetadata {
version: u32,
expires: DateTime<Utc>,
meta: HashMap<MetadataPath, MetadataDescription>,
}
impl SnapshotMetadata {
/// Create new `SnapshotMetadata`.
pub fn new(
version: u32,
expires: DateTime<Utc>,
meta: HashMap<MetadataPath, MetadataDescription>,
) -> Result<Self> {
if version < 1 {
return Err(Error::IllegalArgument(format!(
"Metadata version must be greater than zero. Found: {}",
version
)));
}
Ok(SnapshotMetadata {
version: version,
expires: expires,
meta: meta,
})
}
/// The version number.
pub fn version(&self) -> u32 {
self.version
}
/// An immutable reference to the metadata's expiration `DateTime`.
pub fn expires(&self) -> &DateTime<Utc> {
&self.expires
}
/// An immutable reference to the metadata paths and descriptions.
pub fn meta(&self) -> &HashMap<MetadataPath, MetadataDescription> {
&self.meta
}
}
impl Metadata for SnapshotMetadata {
fn role() -> Role {
Role::Snapshot
}
}
impl Serialize for SnapshotMetadata {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
shims::SnapshotMetadata::from(self)
.map_err(|e| SerializeError::custom(format!("{:?}", e)))?
.serialize(ser)
}
}
impl<'de> Deserialize<'de> for SnapshotMetadata {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::SnapshotMetadata = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// Wrapper for the virtual path to a target.
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord, Serialize)]
pub struct VirtualTargetPath(String);
impl VirtualTargetPath {
/// Create a new `VirtualTargetPath` from a `String`.
///
/// ```
/// # use tuf::metadata::VirtualTargetPath;
/// assert!(VirtualTargetPath::new("foo".into()).is_ok());
/// assert!(VirtualTargetPath::new("/foo".into()).is_err());
/// assert!(VirtualTargetPath::new("../foo".into()).is_err());
/// assert!(VirtualTargetPath::new("foo/..".into()).is_err());
/// assert!(VirtualTargetPath::new("foo/../bar".into()).is_err());
/// assert!(VirtualTargetPath::new("..foo".into()).is_ok());
/// assert!(VirtualTargetPath::new("foo/..bar".into()).is_ok());
/// assert!(VirtualTargetPath::new("foo/bar..".into()).is_ok());
/// ```
pub fn new(path: String) -> Result<Self> {
safe_path(&path)?;
Ok(VirtualTargetPath(path))
}
/// Split `VirtualTargetPath` into components that can be joined to create URL paths, Unix
/// paths, or Windows paths.
///
/// ```
/// # use tuf::metadata::VirtualTargetPath;
/// let path = VirtualTargetPath::new("foo/bar".into()).unwrap();
/// assert_eq!(path.components(), ["foo".to_string(), "bar".to_string()]);
/// ```
pub fn components(&self) -> Vec<String> {
self.0.split('/').map(|s| s.to_string()).collect()
}
/// Return whether this path is the child of another path.
///
/// ```
/// # use tuf::metadata::VirtualTargetPath;
/// let path1 = VirtualTargetPath::new("foo".into()).unwrap();
/// let path2 = VirtualTargetPath::new("foo/bar".into()).unwrap();
/// assert!(!path2.is_child(&path1));
///
/// let path1 = VirtualTargetPath::new("foo/".into()).unwrap();
/// let path2 = VirtualTargetPath::new("foo/bar".into()).unwrap();
/// assert!(path2.is_child(&path1));
///
/// let path2 = VirtualTargetPath::new("foo/bar/baz".into()).unwrap();
/// assert!(path2.is_child(&path1));
///
/// let path2 = VirtualTargetPath::new("wat".into()).unwrap();
/// assert!(!path2.is_child(&path1))
/// ```
pub fn is_child(&self, parent: &Self) -> bool {
if !parent.0.ends_with('/') {
return false;
}
self.0.starts_with(&parent.0)
}
/// Whether or not the current target is available at the end of the given chain of target
/// paths. For the chain to be valid, each target path in a group must be a child of of all
/// previous groups.
// TODO this is hideous and uses way too much clone/heap but I think recursively,
// so here we are
pub fn matches_chain(&self, parents: &[HashSet<VirtualTargetPath>]) -> bool {
if parents.is_empty() {
return false;
}
if parents.len() == 1 {
return parents[0].iter().any(|p| p == self || self.is_child(p));
}
let new = parents[1..]
.iter()
.map(|group| {
group
.iter()
.filter(|parent| {
parents[0].iter().any(
|p| parent.is_child(p) || parent == &p,
)
})
.cloned()
.collect::<HashSet<_>>()
})
.collect::<Vec<_>>();
self.matches_chain(&*new)
}
/// The string value of the path.
pub fn value(&self) -> &str {
&self.0
}
}
impl ToString for VirtualTargetPath {
fn to_string(&self) -> String {
self.0.clone()
}
}
impl<'de> Deserialize<'de> for VirtualTargetPath {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let s: String = Deserialize::deserialize(de)?;
VirtualTargetPath::new(s).map_err(|e| DeserializeError::custom(format!("{:?}", e)))
}
}
/// Wrapper for the real path to a target.
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord, Serialize)]
pub struct TargetPath(String);
impl TargetPath {
/// Create a new `TargetPath`.
pub fn new(path: String) -> Result<Self> {
safe_path(&path)?;
Ok(TargetPath(path))
}
/// Split `TargetPath` into components that can be joined to create URL paths, Unix paths, or
/// Windows paths.
///
/// ```
/// # use tuf::metadata::TargetPath;
/// let path = TargetPath::new("foo/bar".into()).unwrap();
/// assert_eq!(path.components(), ["foo".to_string(), "bar".to_string()]);
/// ```
pub fn components(&self) -> Vec<String> {
self.0.split('/').map(|s| s.to_string()).collect()
}
/// The string value of the path.
pub fn value(&self) -> &str {
&self.0
}
}
/// Description of a target, used in verification.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TargetDescription {
size: u64,
hashes: HashMap<HashAlgorithm, HashValue>,
}
impl TargetDescription {
/// Create a new `TargetDescription`.
///
/// Note: Creating this manually could lead to errors, and the `from_reader` method is
/// preferred.
pub fn new(size: u64, hashes: HashMap<HashAlgorithm, HashValue>) -> Result<Self> {
if hashes.is_empty() {
return Err(Error::IllegalArgument(
"Cannot have empty set of hashes".into(),
));
}
Ok(TargetDescription {
size: size,
hashes: hashes,
})
}
/// Read the from the given reader and calculate the size and hash values.
///
/// ```
/// extern crate data_encoding;
/// extern crate tuf;
/// use data_encoding::BASE64URL;
/// use tuf::crypto::{HashAlgorithm,HashValue};
/// use tuf::metadata::TargetDescription;
///
/// fn main() {
/// let bytes: &[u8] = b"it was a pleasure to burn";
///
/// let s = "Rd9zlbzrdWfeL7gnIEi05X-Yv2TCpy4qqZM1N72ZWQs=";
/// let sha256 = HashValue::new(BASE64URL.decode(s.as_bytes()).unwrap());
///
/// let target_description =
/// TargetDescription::from_reader(bytes, &[HashAlgorithm::Sha256]).unwrap();
/// assert_eq!(target_description.size(), bytes.len() as u64);
/// assert_eq!(target_description.hashes().get(&HashAlgorithm::Sha256), Some(&sha256));
///
/// let s ="tuIxwKybYdvJpWuUj6dubvpwhkAozWB6hMJIRzqn2jOUdtDTBg381brV4K\
/// BU1zKP8GShoJuXEtCf5NkDTCEJgQ==";
/// let sha512 = HashValue::new(BASE64URL.decode(s.as_bytes()).unwrap());
///
/// let target_description =
/// TargetDescription::from_reader(bytes, &[HashAlgorithm::Sha512]).unwrap();
/// assert_eq!(target_description.size(), bytes.len() as u64);
/// assert_eq!(target_description.hashes().get(&HashAlgorithm::Sha512), Some(&sha512));
/// }
/// ```
pub fn from_reader<R>(read: R, hash_algs: &[HashAlgorithm]) -> Result<Self>
where
R: Read,
{
let (size, hashes) = crypto::calculate_hashes(read, hash_algs)?;
Ok(TargetDescription {
size: size,
hashes: hashes,
})
}
/// The maximum size of the target.
pub fn size(&self) -> u64 {
self.size
}
/// An immutable reference to the list of calculated hashes.
pub fn hashes(&self) -> &HashMap<HashAlgorithm, HashValue> {
&self.hashes
}
}
impl<'de> Deserialize<'de> for TargetDescription {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::TargetDescription = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// Metadata for the targets role.
#[derive(Debug, Clone, PartialEq)]
pub struct TargetsMetadata {
version: u32,
expires: DateTime<Utc>,
targets: HashMap<VirtualTargetPath, TargetDescription>,
delegations: Option<Delegations>,
}
impl TargetsMetadata {
/// Create new `TargetsMetadata`.
pub fn new(
version: u32,
expires: DateTime<Utc>,
targets: HashMap<VirtualTargetPath, TargetDescription>,
delegations: Option<Delegations>,
) -> Result<Self> {
if version < 1 {
return Err(Error::IllegalArgument(format!(
"Metadata version must be greater than zero. Found: {}",
version
)));
}
Ok(TargetsMetadata {
version: version,
expires: expires,
targets: targets,
delegations: delegations,
})
}
/// The version number.
pub fn version(&self) -> u32 {
self.version
}
/// An immutable reference to the metadata's expiration `DateTime`.
pub fn expires(&self) -> &DateTime<Utc> {
&self.expires
}
/// An immutable reference to the descriptions of targets.
pub fn targets(&self) -> &HashMap<VirtualTargetPath, TargetDescription> {
&self.targets
}
/// An immutable reference to the optional delegations.
pub fn delegations(&self) -> Option<&Delegations> {
self.delegations.as_ref()
}
}
impl Metadata for TargetsMetadata {
fn role() -> Role {
Role::Targets
}
}
impl Serialize for TargetsMetadata {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
shims::TargetsMetadata::from(self)
.map_err(|e| SerializeError::custom(format!("{:?}", e)))?
.serialize(ser)
}
}
impl<'de> Deserialize<'de> for TargetsMetadata {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::TargetsMetadata = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// Wrapper to described a collections of delegations.
#[derive(Debug, PartialEq, Clone)]
pub struct Delegations {
keys: HashMap<KeyId, PublicKey>,
roles: Vec<Delegation>,
}
impl Delegations {
// TODO check all keys are used
// TODO check all roles have their ID in the set of keys
/// Create a new `Delegations` wrapper from the given set of trusted keys and roles.
pub fn new(keys: HashSet<PublicKey>, roles: Vec<Delegation>) -> Result<Self> {
if keys.is_empty() {
return Err(Error::IllegalArgument("Keys cannot be empty.".into()));
}
if roles.is_empty() {
return Err(Error::IllegalArgument("Roles cannot be empty.".into()));
}
if roles.len() !=
roles
.iter()
.map(|r| &r.role)
.collect::<HashSet<&MetadataPath>>()
.len()
{
return Err(Error::IllegalArgument(
"Cannot have duplicated roles in delegations.".into(),
));
}
Ok(Delegations {
keys: keys.iter()
.cloned()
.map(|k| (k.key_id().clone(), k))
.collect(),
roles: roles,
})
}
/// An immutable reference to the keys used for this set of delegations.
pub fn keys(&self) -> &HashMap<KeyId, PublicKey> {
&self.keys
}
/// An immutable reference to the delegated roles.
pub fn roles(&self) -> &Vec<Delegation> {
&self.roles
}
}
impl Serialize for Delegations {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
shims::Delegations::from(self).serialize(ser)
}
}
impl<'de> Deserialize<'de> for Delegations {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::Delegations = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
/// A delegated targets role.
#[derive(Debug, PartialEq, Clone)]
pub struct Delegation {
role: MetadataPath,
terminating: bool,
threshold: u32,
key_ids: HashSet<KeyId>,
paths: HashSet<VirtualTargetPath>,
}
impl Delegation {
/// Create a new delegation.
pub fn new(
role: MetadataPath,
terminating: bool,
threshold: u32,
key_ids: HashSet<KeyId>,
paths: HashSet<VirtualTargetPath>,
) -> Result<Self> {
if key_ids.is_empty() {
return Err(Error::IllegalArgument("Cannot have empty key IDs".into()));
}
if paths.is_empty() {
return Err(Error::IllegalArgument("Cannot have empty paths".into()));
}
if threshold < 1 {
return Err(Error::IllegalArgument("Cannot have threshold < 1".into()));
}
if (key_ids.len() as u64) < (threshold as u64) {
return Err(Error::IllegalArgument(
"Cannot have threshold less than number of keys".into(),
));
}
Ok(Delegation {
role: role,
terminating: terminating,
threshold: threshold,
key_ids: key_ids,
paths: paths,
})
}
/// An immutable reference to the delegations's metadata path (role).
pub fn role(&self) -> &MetadataPath {
&self.role
}
/// Whether or not this delegation is terminating.
pub fn terminating(&self) -> bool {
self.terminating
}
/// An immutable reference to the delegations's trusted key IDs.
pub fn key_ids(&self) -> &HashSet<KeyId> {
&self.key_ids
}
/// The delegation's threshold.
pub fn threshold(&self) -> u32 {
self.threshold
}
/// An immutable reference to the delegation's authorized paths.
pub fn paths(&self) -> &HashSet<VirtualTargetPath> {
&self.paths
}
}
impl Serialize for Delegation {
fn serialize<S>(&self, ser: S) -> ::std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
shims::Delegation::from(self).serialize(ser)
}
}
impl<'de> Deserialize<'de> for Delegation {
fn deserialize<D: Deserializer<'de>>(de: D) -> ::std::result::Result<Self, D::Error> {
let intermediate: shims::Delegation = Deserialize::deserialize(de)?;
intermediate.try_into().map_err(|e| {
DeserializeError::custom(format!("{:?}", e))
})
}
}
#[cfg(test)]
mod test {
use super::*;
use chrono::prelude::*;
use json;
use crypto::SignatureScheme;
use interchange::Json;
const ED25519_1_PK8: &'static [u8] = include_bytes!("../tests/ed25519/ed25519-1.pk8.der");
const ED25519_2_PK8: &'static [u8] = include_bytes!("../tests/ed25519/ed25519-2.pk8.der");
const ED25519_3_PK8: &'static [u8] = include_bytes!("../tests/ed25519/ed25519-3.pk8.der");
const ED25519_4_PK8: &'static [u8] = include_bytes!("../tests/ed25519/ed25519-4.pk8.der");
#[test]
fn path_matches_chain() {
let test_cases: &[(bool, &str, &[&[&str]])] =
&[
// simplest case
(true, "foo", &[&["foo"]]),
// direct delegation case
(true, "foo", &[&["foo"], &["foo"]]),
// is a dir
(false, "foo", &[&["foo/"]]),
// target not in last position
(false, "foo", &[&["foo"], &["bar"]]),
// target nested
(true, "foo/bar", &[&["foo/"], &["foo/bar"]]),
// target illegally nested
(false, "foo/bar", &[&["baz/"], &["foo/bar"]]),
// target illegally deeply nested
(
false,
"foo/bar/baz",
&[&["foo/"], &["foo/quux/"], &["foo/bar/baz"]],
),
// empty
(false, "foo", &[&[]]),
// empty 2
(false, "foo", &[&[], &["foo"]]),
// empty 3
(false, "foo", &[&["foo"], &[]]),
];
for case in test_cases {
let expected = case.0;
let target = VirtualTargetPath::new(case.1.into()).unwrap();
let parents = case.2
.iter()
.map(|group| {
group
.iter()
.map(|p| VirtualTargetPath::new(p.to_string()).unwrap())
.collect::<HashSet<_>>()
})
.collect::<Vec<_>>();
println!(
"CASE: expect: {} path: {:?} parents: {:?}",
expected,
target,
parents
);
assert_eq!(target.matches_chain(&parents), expected);
}
}
#[test]
fn serde_target_path() {
let s = "foo/bar";
let t = json::from_str::<VirtualTargetPath>(&format!("\"{}\"", s)).unwrap();
assert_eq!(t.to_string().as_str(), s);
assert_eq!(json::to_value(t).unwrap(), json!("foo/bar"));
}
#[test]
fn serde_metadata_path() {
let s = "foo/bar";
let m = json::from_str::<MetadataPath>(&format!("\"{}\"", s)).unwrap();
assert_eq!(m.to_string().as_str(), s);
assert_eq!(json::to_value(m).unwrap(), json!("foo/bar"));
}
#[test]
fn serde_target_description() {
let s: &[u8] = b"from water does all life begin";
let description = TargetDescription::from_reader(s, &[HashAlgorithm::Sha256]).unwrap();
let jsn_str = json::to_string(&description).unwrap();
let jsn = json!({
"size": 30,
"hashes": {
"sha256": "_F10XHEryG6poxJk2sDJVu61OFf2d-7QWCm7cQE8rhg=",
},
});
let parsed_str: TargetDescription = json::from_str(&jsn_str).unwrap();
let parsed_jsn: TargetDescription = json::from_value(jsn).unwrap();
assert_eq!(parsed_str, parsed_jsn);
}
#[test]
fn serde_role_definition() {
let hashes = hashset!(
"diNfThTFm0PI8R-Bq7NztUIvZbZiaC_weJBgcqaHlWw=",
"ar9AgoRsmeEcf6Ponta_1TZu1ds5uXbDemBig30O7ck=",
).iter()
.map(|k| KeyId::from_string(*k).unwrap())
.collect();
let role_def = RoleDefinition::new(2, hashes).unwrap();
let jsn = json!({
"threshold": 2,
"key_ids": [
// these need to be sorted for determinism
"ar9AgoRsmeEcf6Ponta_1TZu1ds5uXbDemBig30O7ck=",
"diNfThTFm0PI8R-Bq7NztUIvZbZiaC_weJBgcqaHlWw=",
],
});
let encoded = json::to_value(&role_def).unwrap();
assert_eq!(encoded, jsn);
let decoded: RoleDefinition = json::from_value(encoded).unwrap();
assert_eq!(decoded, role_def);
let jsn = json!({
"threshold": 0,
"key_ids": [
"diNfThTFm0PI8R-Bq7NztUIvZbZiaC_weJBgcqaHlWw=",
],
});
assert!(json::from_value::<RoleDefinition>(jsn).is_err());
let jsn = json!({
"threshold": -1,
"key_ids": [
"diNfThTFm0PI8R-Bq7NztUIvZbZiaC_weJBgcqaHlWw=",
],
});
assert!(json::from_value::<RoleDefinition>(jsn).is_err());
}
#[test]
fn serde_root_metadata() {
let root_key = PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519).unwrap();
let snapshot_key = PrivateKey::from_pkcs8(ED25519_2_PK8, SignatureScheme::Ed25519).unwrap();
let targets_key = PrivateKey::from_pkcs8(ED25519_3_PK8, SignatureScheme::Ed25519).unwrap();
let timestamp_key = PrivateKey::from_pkcs8(ED25519_4_PK8, SignatureScheme::Ed25519)
.unwrap();
let keys = vec![
root_key.public().clone(),
snapshot_key.public().clone(),
targets_key.public().clone(),
timestamp_key.public().clone(),
];
let root_def = RoleDefinition::new(1, hashset!(root_key.key_id().clone())).unwrap();
let snapshot_def = RoleDefinition::new(1, hashset!(snapshot_key.key_id().clone())).unwrap();
let targets_def = RoleDefinition::new(1, hashset!(targets_key.key_id().clone())).unwrap();
let timestamp_def = RoleDefinition::new(1, hashset!(timestamp_key.key_id().clone()))
.unwrap();
let root = RootMetadata::new(
1,
Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
false,
keys,
root_def,
snapshot_def,
targets_def,
timestamp_def,
).unwrap();
let jsn = json!({
"type": "root",
"version": 1,
"expires": "2017-01-01T00:00:00Z",
"consistent_snapshot": false,
"keys": [
{
"type": "ed25519",
"scheme": "ed25519",
"public_key": "MCwwBwYDK2VwBQADIQAUEK4wU6pwu_qYQoqHnWTTACo1\
ePffquscsHZOhg9-Cw==",
},
{
"type": "ed25519",
"scheme": "ed25519",
"public_key": "MCwwBwYDK2VwBQADIQDrisJrXJ7wJ5474-giYqk7zhb\
-WO5CJQDTjK9GHGWjtg==",
},
{
"type": "ed25519",
"scheme": "ed25519",
"public_key": "MCwwBwYDK2VwBQADIQAWY3bJCn9xfQJwVicvNhwlL7BQ\
vtGgZ_8giaAwL7q3PQ==",
},
{
"type": "ed25519",
"scheme": "ed25519",
"public_key": "MCwwBwYDK2VwBQADIQBo2eyzhzcQBajrjmAQUwXDQ1ao_\
NhZ1_7zzCKL8rKzsg==",
},
],
"root": {
"threshold": 1,
"key_ids": ["qfrfBrkB4lBBSDEBlZgaTGS_SrE6UfmON9kP4i3dJFY="],
},
"snapshot": {
"threshold": 1,
"key_ids": ["5WvZhiiSSUung_OhJVbPshKwD_ZNkgeg80i4oy2KAVs="],
},
"targets": {
"threshold": 1,
"key_ids": ["4hsyITLMQoWBg0ldCLKPlRZPIEf258cMg-xdAROsO6o="],
},
"timestamp": {
"threshold": 1,
"key_ids": ["C2hNB7qN99EAbHVGHPIJc5Hqa9RfEilnMqsCNJ5dGdw="],
},
});
let encoded = json::to_value(&root).unwrap();
assert_eq!(encoded, jsn);
let decoded: RootMetadata = json::from_value(encoded).unwrap();
assert_eq!(decoded, root);
}
#[test]
fn serde_timestamp_metadata() {
let timestamp = TimestampMetadata::new(
1,
Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
MetadataDescription::new(
1,
100,
hashmap! { HashAlgorithm::Sha256 => HashValue::new(vec![]) },
).unwrap(),
).unwrap();
let jsn = json!({
"type": "timestamp",
"version": 1,
"expires": "2017-01-01T00:00:00Z",
"snapshot": {
"version": 1,
"size": 100,
"hashes": {
"sha256": "",
},
},
});
let encoded = json::to_value(×tamp).unwrap();
assert_eq!(encoded, jsn);
let decoded: TimestampMetadata = json::from_value(encoded).unwrap();
assert_eq!(decoded, timestamp);
}
#[test]
fn serde_snapshot_metadata() {
let snapshot = SnapshotMetadata::new(
1,
Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
hashmap! {
MetadataPath::new("foo".into()).unwrap() =>
MetadataDescription::new(
1,
100,
hashmap! { HashAlgorithm::Sha256 => HashValue::new(vec![]) },
).unwrap(),
},
).unwrap();
let jsn = json!({
"type": "snapshot",
"version": 1,
"expires": "2017-01-01T00:00:00Z",
"meta": {
"foo": {
"version": 1,
"size": 100,
"hashes": {
"sha256": "",
},
},
},
});
let encoded = json::to_value(&snapshot).unwrap();
assert_eq!(encoded, jsn);
let decoded: SnapshotMetadata = json::from_value(encoded).unwrap();
assert_eq!(decoded, snapshot);
}
#[test]
fn serde_targets_metadata() {
let targets = TargetsMetadata::new(
1,
Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
hashmap! {
VirtualTargetPath::new("foo".into()).unwrap() =>
TargetDescription::from_reader(
b"foo" as &[u8],
&[HashAlgorithm::Sha256],
).unwrap(),
},
None,
).unwrap();
let jsn = json!({
"type": "targets",
"version": 1,
"expires": "2017-01-01T00:00:00Z",
"targets": {
"foo": {
"size": 3,
"hashes": {
"sha256": "LCa0a2j_xo_5m0U8HTBBNBNCLXBkg7-g-YpeiGJm564=",
},
},
},
});
let encoded = json::to_value(&targets).unwrap();
assert_eq!(encoded, jsn);
let decoded: TargetsMetadata = json::from_value(encoded).unwrap();
assert_eq!(decoded, targets);
}
#[test]
fn serde_targets_with_delegations_metadata() {
let key = PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519).unwrap();
let delegations = Delegations::new(
hashset![key.public().clone()],
vec![Delegation::new(
MetadataPath::new("foo/bar".into()).unwrap(),
false,
1,
hashset!(key.key_id().clone()),
hashset!(VirtualTargetPath::new("baz/quux".into()).unwrap()),
).unwrap()],
).unwrap();
let targets = TargetsMetadata::new(
1,
Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
HashMap::new(),
Some(delegations),
).unwrap();
let jsn = json!({
"type": "targets",
"version": 1,
"expires": "2017-01-01T00:00:00Z",
"targets": {},
"delegations": {
"keys": [
{
"type": "ed25519",
"scheme": "ed25519",
"public_key": "MCwwBwYDK2VwBQADIQDrisJrXJ7wJ5474-giYqk7zhb\
-WO5CJQDTjK9GHGWjtg==",
},
],
"roles": [
{
"role": "foo/bar",
"terminating": false,
"threshold": 1,
"key_ids": ["qfrfBrkB4lBBSDEBlZgaTGS_SrE6UfmON9kP4i3dJFY="],
"paths": ["baz/quux"],
},
],
}
});
let encoded = json::to_value(&targets).unwrap();
assert_eq!(encoded, jsn);
let decoded: TargetsMetadata = json::from_value(encoded).unwrap();
assert_eq!(decoded, targets);
}
#[test]
fn serde_signed_metadata() {
let snapshot = SnapshotMetadata::new(
1,
Utc.ymd(2017, 1, 1).and_hms(0, 0, 0),
hashmap! {
MetadataPath::new("foo".into()).unwrap() =>
MetadataDescription::new(
1,
100,
hashmap! { HashAlgorithm::Sha256 => HashValue::new(vec![]) },
).unwrap(),
},
).unwrap();
let key = PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519).unwrap();
let signed = SignedMetadata::<Json, SnapshotMetadata>::new(&snapshot, &key).unwrap();
let jsn = json!({
"signatures": [
{
"key_id": "qfrfBrkB4lBBSDEBlZgaTGS_SrE6UfmON9kP4i3dJFY=",
"value": "9QXO-Av15zaWEsheO9JbWdo8iAF9vEbUKVePJpGRX5s6b1G8eqH4kvAE2jZV349JvZ\
-2yPGLE20V_7JwhMLYCQ==",
}
],
"signed": {
"type": "snapshot",
"version": 1,
"expires": "2017-01-01T00:00:00Z",
"meta": {
"foo": {
"version": 1,
"size": 100,
"hashes": {
"sha256": "",
},
},
},
},
});
let encoded = json::to_value(&signed).unwrap();
assert_eq!(encoded, jsn);
let decoded: SignedMetadata<Json, SnapshotMetadata> = json::from_value(encoded).unwrap();
assert_eq!(decoded, signed);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//
// Here there be test cases about what metadata is allowed to be parsed wherein we do all sorts
// of naughty things and make sure the parsers puke appropriately.
// ______________
// ,===:'., `-._
// `:.`---.__ `-._
// `:. `--. `.
// \. `. `.
// (,,(, \. `. ____,-`.,
// (,' `/ \. ,--.___`.'
// , ,' ,--. `, \.;' `
// `{o, { \ : \;
// |,,' / / //
// j;; / ,' ,-//. ,---. ,
// \;' / ,' / _ \ / _ \ ,'/
// \ `' / \ `' / \ `.' /
// `.___,' `.__,' `.__,'
//
///////////////////////////////////////////////////////////////////////////////////////////////
// TODO test for mismatched ed25519/rsa keys/schemes
fn make_root() -> json::Value {
let root_def = RoleDefinition::new(
1,
hashset!(PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap().key_id().clone()),
).unwrap();
let snapshot_def = RoleDefinition::new(
1,
hashset!(PrivateKey::from_pkcs8(ED25519_2_PK8, SignatureScheme::Ed25519)
.unwrap().key_id().clone()),
).unwrap();
let targets_def = RoleDefinition::new(
1,
hashset!(PrivateKey::from_pkcs8(ED25519_3_PK8, SignatureScheme::Ed25519)
.unwrap().key_id().clone()),
).unwrap();
let timestamp_def = RoleDefinition::new(
1,
hashset!(PrivateKey::from_pkcs8(ED25519_4_PK8, SignatureScheme::Ed25519)
.unwrap().key_id().clone()),
).unwrap();
let root = RootMetadata::new(
1,
Utc.ymd(2038, 1, 1).and_hms(0, 0, 0),
false,
vec!(
PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap().public().clone(),
PrivateKey::from_pkcs8(ED25519_2_PK8, SignatureScheme::Ed25519)
.unwrap().public().clone(),
PrivateKey::from_pkcs8(ED25519_3_PK8, SignatureScheme::Ed25519)
.unwrap().public().clone(),
PrivateKey::from_pkcs8(ED25519_4_PK8, SignatureScheme::Ed25519)
.unwrap().public().clone(),
),
root_def,
snapshot_def,
targets_def,
timestamp_def,
).unwrap();
json::to_value(&root).unwrap()
}
fn make_snapshot() -> json::Value {
let snapshot = SnapshotMetadata::new(1, Utc.ymd(2038, 1, 1).and_hms(0, 0, 0), hashmap!())
.unwrap();
json::to_value(&snapshot).unwrap()
}
fn make_timestamp() -> json::Value {
let timestamp = TimestampMetadata::new(
1,
Utc.ymd(2038, 1, 1).and_hms(0, 0, 0),
MetadataDescription::from_reader(&*vec![], 1, &[HashAlgorithm::Sha256])
.unwrap(),
).unwrap();
json::to_value(×tamp).unwrap()
}
fn make_targets() -> json::Value {
let targets =
TargetsMetadata::new(1, Utc.ymd(2038, 1, 1).and_hms(0, 0, 0), hashmap!(), None)
.unwrap();
json::to_value(&targets).unwrap()
}
fn make_delegations() -> json::Value {
let key = PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap()
.public()
.clone();
let delegations = Delegations::new(
hashset![key.clone()],
vec![Delegation::new(
MetadataPath::new("foo".into()).unwrap(),
false,
1,
hashset!(key.key_id().clone()),
hashset!(VirtualTargetPath::new("bar".into()).unwrap()),
).unwrap()],
).unwrap();
json::to_value(&delegations).unwrap()
}
fn make_delegation() -> json::Value {
let key = PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap()
.public()
.clone();
let delegation = Delegation::new(
MetadataPath::new("foo".into()).unwrap(),
false,
1,
hashset!(key.key_id().clone()),
hashset!(VirtualTargetPath::new("bar".into()).unwrap()),
).unwrap();
json::to_value(&delegation).unwrap()
}
fn set_version(value: &mut json::Value, version: i64) {
match value.as_object_mut() {
Some(obj) => {
let _ = obj.insert("version".into(), json!(version));
}
None => panic!(),
}
}
// Refuse to deserialize root metadata if the version is not > 0
#[test]
fn deserialize_json_root_illegal_version() {
let mut root_json = make_root();
set_version(&mut root_json, 0);
assert!(json::from_value::<RootMetadata>(root_json.clone()).is_err());
let mut root_json = make_root();
set_version(&mut root_json, -1);
assert!(json::from_value::<RootMetadata>(root_json).is_err());
}
// Refuse to deserialize root metadata if it contains duplicate keys
#[test]
fn deserialize_json_root_duplicate_keys() {
let mut root_json = make_root();
let dupe = root_json
.as_object()
.unwrap()
.get("keys")
.unwrap()
.as_array()
.unwrap()
[0]
.clone();
root_json
.as_object_mut()
.unwrap()
.get_mut("keys")
.unwrap()
.as_array_mut()
.unwrap()
.push(dupe);
assert!(json::from_value::<RootMetadata>(root_json).is_err());
}
fn set_threshold(value: &mut json::Value, threshold: i32) {
match value.as_object_mut() {
Some(obj) => {
let _ = obj.insert("threshold".into(), json!(threshold));
}
None => panic!(),
}
}
// Refuse to deserialize role definitions with illegal thresholds
#[test]
fn deserialize_json_role_definition_illegal_threshold() {
let role_def = RoleDefinition::new(
1,
hashset!(PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap().key_id().clone()),
).unwrap();
let mut jsn = json::to_value(&role_def).unwrap();
set_threshold(&mut jsn, 0);
assert!(json::from_value::<RoleDefinition>(jsn).is_err());
let mut jsn = json::to_value(&role_def).unwrap();
set_threshold(&mut jsn, -1);
assert!(json::from_value::<RoleDefinition>(jsn).is_err());
let role_def = RoleDefinition::new(
2,
hashset!(
PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap().key_id().clone(),
PrivateKey::from_pkcs8(ED25519_2_PK8, SignatureScheme::Ed25519)
.unwrap().key_id().clone(),
),
).unwrap();
let mut jsn = json::to_value(&role_def).unwrap();
set_threshold(&mut jsn, 3);
assert!(json::from_value::<RoleDefinition>(jsn).is_err());
}
// Refuse to deserialilze root metadata with wrong type field
#[test]
fn deserialize_json_root_bad_type() {
let mut root = make_root();
let _ = root.as_object_mut().unwrap().insert(
"type".into(),
json!("snapshot"),
);
assert!(json::from_value::<RootMetadata>(root).is_err());
}
// Refuse to deserialize role definitions with duplicated key ids
#[test]
fn deserialize_json_role_definition_duplicate_key_ids() {
let key_id = PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap()
.key_id()
.clone();
let role_def = RoleDefinition::new(1, hashset!(key_id.clone())).unwrap();
let mut jsn = json::to_value(&role_def).unwrap();
match jsn.as_object_mut() {
Some(obj) => {
match obj.get_mut("key_ids").unwrap().as_array_mut() {
Some(arr) => arr.push(json!(key_id)),
None => panic!(),
}
}
None => panic!(),
}
assert!(json::from_value::<RoleDefinition>(jsn).is_err());
}
// Refuse to deserialize snapshot metadata with illegal versions
#[test]
fn deserialize_json_snapshot_illegal_version() {
let mut snapshot = make_snapshot();
set_version(&mut snapshot, 0);
assert!(json::from_value::<SnapshotMetadata>(snapshot).is_err());
let mut snapshot = make_snapshot();
set_version(&mut snapshot, -1);
assert!(json::from_value::<SnapshotMetadata>(snapshot).is_err());
}
// Refuse to deserialilze snapshot metadata with wrong type field
#[test]
fn deserialize_json_snapshot_bad_type() {
let mut snapshot = make_snapshot();
let _ = snapshot.as_object_mut().unwrap().insert(
"type".into(),
json!("root"),
);
assert!(json::from_value::<SnapshotMetadata>(snapshot).is_err());
}
// Refuse to deserialize timestamp metadata with illegal versions
#[test]
fn deserialize_json_timestamp_illegal_version() {
let mut timestamp = make_timestamp();
set_version(&mut timestamp, 0);
assert!(json::from_value::<TimestampMetadata>(timestamp).is_err());
let mut timestamp = make_timestamp();
set_version(&mut timestamp, -1);
assert!(json::from_value::<TimestampMetadata>(timestamp).is_err());
}
// Refuse to deserialilze timestamp metadata with wrong type field
#[test]
fn deserialize_json_timestamp_bad_type() {
let mut timestamp = make_timestamp();
let _ = timestamp.as_object_mut().unwrap().insert(
"type".into(),
json!("root"),
);
assert!(json::from_value::<TimestampMetadata>(timestamp).is_err());
}
// Refuse to deserialize targets metadata with illegal versions
#[test]
fn deserialize_json_targets_illegal_version() {
let mut targets = make_targets();
set_version(&mut targets, 0);
assert!(json::from_value::<TargetsMetadata>(targets).is_err());
let mut targets = make_targets();
set_version(&mut targets, -1);
assert!(json::from_value::<TargetsMetadata>(targets).is_err());
}
// Refuse to deserialilze targets metadata with wrong type field
#[test]
fn deserialize_json_targets_bad_type() {
let mut targets = make_targets();
let _ = targets.as_object_mut().unwrap().insert(
"type".into(),
json!("root"),
);
assert!(json::from_value::<TargetsMetadata>(targets).is_err());
}
// Refuse to deserialize delegations with no keys
#[test]
fn deserialize_json_delegations_no_keys() {
let mut delegations = make_delegations();
delegations
.as_object_mut()
.unwrap()
.get_mut("keys".into())
.unwrap()
.as_array_mut()
.unwrap()
.clear();
assert!(json::from_value::<Delegations>(delegations).is_err());
}
// Refuse to deserialize delegations with no roles
#[test]
fn deserialize_json_delegations_no_roles() {
let mut delegations = make_delegations();
delegations
.as_object_mut()
.unwrap()
.get_mut("roles".into())
.unwrap()
.as_array_mut()
.unwrap()
.clear();
assert!(json::from_value::<Delegations>(delegations).is_err());
}
// Refuse to deserialize delegations with duplicated roles
#[test]
fn deserialize_json_delegations_duplicated_roles() {
let mut delegations = make_delegations();
let dupe = delegations
.as_object()
.unwrap()
.get("roles".into())
.unwrap()
.as_array()
.unwrap()
[0]
.clone();
delegations
.as_object_mut()
.unwrap()
.get_mut("roles".into())
.unwrap()
.as_array_mut()
.unwrap()
.push(dupe);
assert!(json::from_value::<Delegations>(delegations).is_err());
}
// Refuse to deserialize a delegation with insufficient threshold
#[test]
fn deserialize_json_delegation_bad_threshold() {
let mut delegation = make_delegation();
set_threshold(&mut delegation, 0);
assert!(json::from_value::<Delegation>(delegation).is_err());
let mut delegation = make_delegation();
set_threshold(&mut delegation, 2);
assert!(json::from_value::<Delegation>(delegation).is_err());
}
// Refuse to deserialize a delegation with duplicate key IDs
#[test]
fn deserialize_json_delegation_duplicate_key_ids() {
let mut delegation = make_delegation();
let dupe = delegation
.as_object()
.unwrap()
.get("key_ids".into())
.unwrap()
.as_array()
.unwrap()
[0]
.clone();
delegation
.as_object_mut()
.unwrap()
.get_mut("key_ids".into())
.unwrap()
.as_array_mut()
.unwrap()
.push(dupe);
assert!(json::from_value::<Delegation>(delegation).is_err());
}
// Refuse to deserialize a delegation with duplicate paths
#[test]
fn deserialize_json_delegation_duplicate_paths() {
let mut delegation = make_delegation();
let dupe = delegation
.as_object()
.unwrap()
.get("paths".into())
.unwrap()
.as_array()
.unwrap()
[0]
.clone();
delegation
.as_object_mut()
.unwrap()
.get_mut("paths".into())
.unwrap()
.as_array_mut()
.unwrap()
.push(dupe);
assert!(json::from_value::<Delegation>(delegation).is_err());
}
// Refuse to deserialize a Delegations struct with duplicate keys
#[test]
fn deserialize_json_delegations_duplicate_keys() {
let key = PrivateKey::from_pkcs8(ED25519_1_PK8, SignatureScheme::Ed25519)
.unwrap()
.public()
.clone();
let delegations = Delegations::new(
hashset!(key.clone()),
vec![Delegation::new(
MetadataPath::new("foo".into()).unwrap(),
false,
1,
hashset!(key.key_id().clone()),
hashset!(VirtualTargetPath::new("bar".into()).unwrap()),
).unwrap()],
).unwrap();
let mut delegations = json::to_value(delegations).unwrap();
let dupe = delegations
.as_object()
.unwrap()
.get("keys".into())
.unwrap()
.as_array()
.unwrap()
[0]
.clone();
delegations
.as_object_mut()
.unwrap()
.get_mut("keys".into())
.unwrap()
.as_array_mut()
.unwrap()
.push(dupe);
assert!(json::from_value::<Delegations>(delegations).is_err());
}
}