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
//! Clients for high level interactions with TUF repositories.
//!
//! # Example
//!
//! ```no_run
//! # use futures_executor::block_on;
//! # #[cfg(feature = "hyper_013")]
//! # use hyper_013 as hyper;
//! # #[cfg(feature = "hyper_014")]
//! # use hyper_014 as hyper;
//! # use hyper::client::Client as HttpClient;
//! # use std::path::PathBuf;
//! # use std::str::FromStr;
//! # use tuf::{Result, Database};
//! # use tuf::crypto::PublicKey;
//! # use tuf::client::{Client, Config};
//! # use tuf::metadata::{RootMetadata, Role, MetadataPath, MetadataVersion};
//! # use tuf::interchange::Json;
//! # use tuf::repository::{FileSystemRepository, HttpRepositoryBuilder};
//! #
//! # const PUBLIC_KEY: &'static [u8] = include_bytes!("../tests/ed25519/ed25519-1.pub");
//! #
//! # fn load_root_public_keys() -> Vec<PublicKey> {
//! # vec![PublicKey::from_ed25519(PUBLIC_KEY).unwrap()]
//! # }
//! #
//! # fn main() -> Result<()> {
//! # block_on(async {
//! let root_public_keys = load_root_public_keys();
//! let local = FileSystemRepository::<Json>::new(PathBuf::from("~/.rustup"))?;
//!
//! let remote = HttpRepositoryBuilder::new_with_uri(
//! "https://static.rust-lang.org/".parse::<http::Uri>().unwrap(),
//! HttpClient::new(),
//! )
//! .user_agent("rustup/1.4.0")
//! .build();
//!
//! let mut client = Client::with_trusted_root_keys(
//! Config::default(),
//! &MetadataVersion::Number(1),
//! 1,
//! &root_public_keys,
//! local,
//! remote,
//! ).await?;
//!
//! let _ = client.update().await?;
//! # Ok(())
//! # })
//! # }
//! ```
use chrono::offset::Utc;
use futures_io::AsyncRead;
use log::{error, warn};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use crate::crypto::{self, HashAlgorithm, HashValue, PublicKey};
use crate::database::Database;
use crate::error::Error;
use crate::interchange::DataInterchange;
use crate::metadata::{
Metadata, MetadataPath, MetadataVersion, RawSignedMetadata, Role, RootMetadata,
SnapshotMetadata, TargetDescription, TargetPath, TargetsMetadata, TimestampMetadata,
};
use crate::repository::{Repository, RepositoryProvider, RepositoryStorage};
use crate::verify::Verified;
use crate::Result;
/// A client that interacts with TUF repositories.
#[derive(Debug)]
pub struct Client<D, L, R>
where
D: DataInterchange + Sync,
L: RepositoryProvider<D> + RepositoryStorage<D>,
R: RepositoryProvider<D>,
{
config: Config,
tuf: Database<D>,
local: Repository<L, D>,
remote: Repository<R, D>,
}
impl<D, L, R> Client<D, L, R>
where
D: DataInterchange + Sync,
L: RepositoryProvider<D> + RepositoryStorage<D>,
R: RepositoryProvider<D>,
{
/// Create a new TUF client. It will attempt to load the latest root metadata from the local
/// repo and use it as the initial trusted root metadata, or it will return an error if it
/// cannot do so.
///
/// **WARNING**: This is trust-on-first-use (TOFU) and offers weaker security guarantees than
/// the related methods [`Client::with_trusted_root`], [`Client::with_trusted_root_keys`].
///
/// # Examples
///
/// ```
/// # use chrono::offset::{Utc, TimeZone};
/// # use futures_executor::block_on;
/// # use tuf::{
/// # Error,
/// # interchange::Json,
/// # client::{Client, Config},
/// # crypto::{Ed25519PrivateKey, PrivateKey, SignatureScheme},
/// # metadata::{MetadataPath, MetadataVersion, Role, RootMetadataBuilder},
/// # repository::{EphemeralRepository, RepositoryStorage},
/// # };
/// # fn main() -> Result<(), Error> {
/// # block_on(async {
/// # let private_key = Ed25519PrivateKey::from_pkcs8(
/// # &Ed25519PrivateKey::pkcs8()?,
/// # )?;
/// # let public_key = private_key.public().clone();
/// let mut local = EphemeralRepository::<Json>::new();
/// let remote = EphemeralRepository::<Json>::new();
///
/// let root_version = 1;
/// let root = RootMetadataBuilder::new()
/// .version(root_version)
/// .expires(Utc.ymd(2038, 1, 1).and_hms(0, 0, 0))
/// .root_key(public_key.clone())
/// .snapshot_key(public_key.clone())
/// .targets_key(public_key.clone())
/// .timestamp_key(public_key.clone())
/// .signed::<Json>(&private_key)?;
///
/// let root_path = MetadataPath::from_role(&Role::Root);
/// let root_version = MetadataVersion::Number(root_version);
///
/// local.store_metadata(
/// &root_path,
/// &root_version,
/// &mut root.to_raw().unwrap().as_bytes()
/// ).await?;
///
/// let client = Client::with_trusted_local(
/// Config::default(),
/// local,
/// remote,
/// ).await?;
/// # Ok(())
/// # })
/// # }
/// ```
pub async fn with_trusted_local(config: Config, local: L, remote: R) -> Result<Self> {
let (local, remote) = (Repository::new(local), Repository::new(remote));
let root_path = MetadataPath::from_role(&Role::Root);
// FIXME should this be MetadataVersion::None so we bootstrap with the latest version?
let root_version = MetadataVersion::Number(1);
let raw_root: RawSignedMetadata<_, RootMetadata> = local
.fetch_metadata(&root_path, &root_version, config.max_root_length, vec![])
.await?;
let tuf = Database::from_trusted_root(&raw_root)?;
Self::new(config, tuf, local, remote).await
}
/// Create a new TUF client. It will trust this initial root metadata.
///
/// # Examples
///
/// ```
/// # use chrono::offset::{Utc, TimeZone};
/// # use futures_executor::block_on;
/// # use tuf::{
/// # Error,
/// # interchange::Json,
/// # client::{Client, Config},
/// # crypto::{Ed25519PrivateKey, KeyType, PrivateKey, SignatureScheme},
/// # metadata::{MetadataPath, MetadataVersion, Role, RootMetadataBuilder},
/// # repository::{EphemeralRepository},
/// # };
/// # fn main() -> Result<(), Error> {
/// # block_on(async {
/// # let private_key = Ed25519PrivateKey::from_pkcs8(
/// # &Ed25519PrivateKey::pkcs8()?,
/// # )?;
/// # let public_key = private_key.public().clone();
/// let local = EphemeralRepository::<Json>::new();
/// let remote = EphemeralRepository::<Json>::new();
///
/// let root_version = 1;
/// let root_threshold = 1;
/// let raw_root = RootMetadataBuilder::new()
/// .version(root_version)
/// .expires(Utc.ymd(2038, 1, 1).and_hms(0, 0, 0))
/// .root_key(public_key.clone())
/// .root_threshold(root_threshold)
/// .snapshot_key(public_key.clone())
/// .targets_key(public_key.clone())
/// .timestamp_key(public_key.clone())
/// .signed::<Json>(&private_key)
/// .unwrap()
/// .to_raw()
/// .unwrap();
///
/// let client = Client::with_trusted_root(
/// Config::default(),
/// &raw_root,
/// local,
/// remote,
/// ).await?;
/// # Ok(())
/// # })
/// # }
/// ```
pub async fn with_trusted_root(
config: Config,
trusted_root: &RawSignedMetadata<D, RootMetadata>,
local: L,
remote: R,
) -> Result<Self> {
let (local, remote) = (Repository::new(local), Repository::new(remote));
let tuf = Database::from_trusted_root(trusted_root)?;
Self::new(config, tuf, local, remote).await
}
/// Create a new TUF client. It will attempt to load initial root metadata from the local and remote
/// repositories using the provided keys to pin the verification.
///
/// # Examples
///
/// ```
/// # use chrono::offset::{Utc, TimeZone};
/// # use futures_executor::block_on;
/// # use std::iter::once;
/// # use tuf::{
/// # Error,
/// # interchange::Json,
/// # client::{Client, Config},
/// # crypto::{Ed25519PrivateKey, KeyType, PrivateKey, SignatureScheme},
/// # metadata::{MetadataPath, MetadataVersion, Role, RootMetadataBuilder},
/// # repository::{EphemeralRepository, RepositoryStorage},
/// # };
/// # fn main() -> Result<(), Error> {
/// # block_on(async {
/// # let private_key = Ed25519PrivateKey::from_pkcs8(
/// # &Ed25519PrivateKey::pkcs8()?,
/// # )?;
/// # let public_key = private_key.public().clone();
/// let local = EphemeralRepository::<Json>::new();
/// let mut remote = EphemeralRepository::<Json>::new();
///
/// let root_version = 1;
/// let root_threshold = 1;
/// let root = RootMetadataBuilder::new()
/// .version(root_version)
/// .expires(Utc.ymd(2038, 1, 1).and_hms(0, 0, 0))
/// .root_key(public_key.clone())
/// .root_threshold(root_threshold)
/// .snapshot_key(public_key.clone())
/// .targets_key(public_key.clone())
/// .timestamp_key(public_key.clone())
/// .signed::<Json>(&private_key)?;
///
/// let root_path = MetadataPath::from_role(&Role::Root);
/// let root_version = MetadataVersion::Number(root_version);
///
/// remote.store_metadata(
/// &root_path,
/// &root_version,
/// &mut root.to_raw().unwrap().as_bytes()
/// ).await?;
///
/// let client = Client::with_trusted_root_keys(
/// Config::default(),
/// &root_version,
/// root_threshold,
/// once(&public_key),
/// local,
/// remote,
/// ).await?;
/// # Ok(())
/// # })
/// # }
/// ```
pub async fn with_trusted_root_keys<'a, I>(
config: Config,
root_version: &MetadataVersion,
root_threshold: u32,
trusted_root_keys: I,
local: L,
remote: R,
) -> Result<Self>
where
I: IntoIterator<Item = &'a PublicKey>,
{
let (mut local, remote) = (Repository::new(local), Repository::new(remote));
let root_path = MetadataPath::from_role(&Role::Root);
let (fetched, raw_root) = fetch_metadata_from_local_or_else_remote(
&root_path,
root_version,
config.max_root_length,
vec![],
&local,
&remote,
)
.await?;
let tuf =
Database::from_root_with_trusted_keys(&raw_root, root_threshold, trusted_root_keys)?;
// FIXME(#253) verify the trusted root version matches the provided version.
let root_version = MetadataVersion::Number(tuf.trusted_root().version());
// Only store the metadata after we have validated it.
if fetched {
// NOTE(#301): The spec only states that the unversioned root metadata needs to be
// written to non-volatile storage. This enables a method like
// `Client::with_trusted_local` to initialize trust with the latest root version.
// However, this doesn't work well when trust is established with an externally
// provided root, such as with `Clietn::with_trusted_root` or
// `Client::with_trusted_root_keys`. In those cases, it's possible those initial roots
// could be multiple versions behind the latest cached root metadata. So we'd most
// likely never use the locally cached `root.json`.
//
// Instead, as an extension to the spec, we'll write the `$VERSION.root.json` metadata
// to the local store. This will eventually enable us to initialize metadata from the
// local store (see #301).
local
.store_metadata(&root_path, &root_version, &raw_root)
.await?;
// FIXME: should we also store the root as `MetadataVersion::None`?
}
Self::new(config, tuf, local, remote).await
}
/// Create a new TUF client. It will trust and update the TUF database.
pub async fn from_database(
config: Config,
tuf: Database<D>,
local: L,
remote: R,
) -> Result<Self> {
let (local, remote) = (Repository::new(local), Repository::new(remote));
Self::new(config, tuf, local, remote).await
}
/// Construct a client with the given parts.
///
/// Note: Since this was created by a prior [Client], it does not try to load
/// metadata from the included local repository, since we would have done
/// that when the prior [Client] was constructed.
pub fn from_parts(parts: Parts<D, L, R>) -> Self {
let Parts {
config,
database,
local,
remote,
} = parts;
Self {
config,
tuf: database,
local: Repository::new(local),
remote: Repository::new(remote),
}
}
/// Create a new TUF client. It will trust this TUF database.
async fn new(
config: Config,
mut tuf: Database<D>,
local: Repository<L, D>,
remote: Repository<R, D>,
) -> Result<Self> {
let res = async {
let _r = Self::update_root_with_repos(&config, &mut tuf, None, &local).await?;
let _ts = Self::update_timestamp_with_repos(&config, &mut tuf, None, &local).await?;
let _sn =
Self::update_snapshot_with_repos(&config, &mut tuf, None, &local, false).await?;
let _ta =
Self::update_targets_with_repos(&config, &mut tuf, None, &local, false).await?;
Ok(())
}
.await;
match res {
Ok(()) | Err(Error::NotFound) => {}
Err(err) => {
warn!("error loading local metadata: : {}", err);
}
}
Ok(Client {
tuf,
config,
local,
remote,
})
}
/// Update TUF metadata from the remote repository.
///
/// Returns `true` if an update occurred and `false` otherwise.
pub async fn update(&mut self) -> Result<bool> {
let r = self.update_root().await?;
let ts = self.update_timestamp().await?;
let sn = self.update_snapshot().await?;
let ta = self.update_targets().await?;
Ok(r || ts || sn || ta)
}
/// Consumes the [Client] and returns the inner [Database] and other parts.
pub fn into_parts(self) -> Parts<D, L, R> {
let Client {
config,
tuf,
local,
remote,
} = self;
Parts {
config,
database: tuf,
local: local.into_inner(),
remote: remote.into_inner(),
}
}
/// Returns the current trusted root version.
pub fn root_version(&self) -> u32 {
self.tuf.trusted_root().version()
}
/// Returns the current trusted timestamp version.
pub fn timestamp_version(&self) -> Option<u32> {
Some(self.tuf.trusted_timestamp()?.version())
}
/// Returns the current trusted snapshot version.
pub fn snapshot_version(&self) -> Option<u32> {
Some(self.tuf.trusted_snapshot()?.version())
}
/// Returns the current trusted targets version.
pub fn targets_version(&self) -> Option<u32> {
Some(self.tuf.trusted_targets()?.version())
}
/// Returns the current trusted delegations version for a given role.
pub fn delegations_version(&self, role: &MetadataPath) -> Option<u32> {
Some(self.tuf.trusted_delegations().get(role)?.version())
}
/// Returns the current trusted root.
pub fn trusted_root(&self) -> &Verified<RootMetadata> {
self.tuf.trusted_root()
}
/// Returns the current trusted timestamp.
pub fn trusted_timestamp(&self) -> Option<&Verified<TimestampMetadata>> {
self.tuf.trusted_timestamp()
}
/// Returns the current trusted snapshot.
pub fn trusted_snapshot(&self) -> Option<&Verified<SnapshotMetadata>> {
self.tuf.trusted_snapshot()
}
/// Returns the current trusted targets.
pub fn trusted_targets(&self) -> Option<&Verified<TargetsMetadata>> {
self.tuf.trusted_targets()
}
/// Returns the current trusted delegations.
pub fn trusted_delegations(&self) -> &HashMap<MetadataPath, Verified<TargetsMetadata>> {
self.tuf.trusted_delegations()
}
/// Update TUF root metadata from the remote repository.
///
/// Returns `true` if an update occurred and `false` otherwise.
pub async fn update_root(&mut self) -> Result<bool> {
Self::update_root_with_repos(
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
)
.await
}
async fn update_root_with_repos<Remote>(
config: &Config,
tuf: &mut Database<D>,
mut local: Option<&mut Repository<L, D>>,
remote: &Repository<Remote, D>,
) -> Result<bool>
where
Remote: RepositoryProvider<D>,
{
let root_path = MetadataPath::from_role(&Role::Root);
let mut updated = false;
loop {
/////////////////////////////////////////
// TUF-1.0.9 §5.1.2:
//
// Try downloading version N+1 of the root metadata file, up to some W number of
// bytes (because the size is unknown). The value for W is set by the authors of
// the application using TUF. For example, W may be tens of kilobytes. The filename
// used to download the root metadata file is of the fixed form
// VERSION_NUMBER.FILENAME.EXT (e.g., 42.root.json). If this file is not available,
// or we have downloaded more than Y number of root metadata files (because the
// exact number is as yet unknown), then go to step 5.1.9. The value for Y is set
// by the authors of the application using TUF. For example, Y may be 2^10.
// FIXME(#306) We do not have an upper bound on the number of root metadata we'll
// fetch. This means that an attacker that's stolen the root keys could cause a client
// to fall into an infinite loop (but if an attacker has stolen the root keys, the
// client probably has worse problems to worry about).
let next_version = MetadataVersion::Number(tuf.trusted_root().version() + 1);
let res = remote
.fetch_metadata(&root_path, &next_version, config.max_root_length, vec![])
.await;
let raw_signed_root = match res {
Ok(raw_signed_root) => raw_signed_root,
Err(Error::NotFound) => {
break;
}
Err(err) => {
return Err(err);
}
};
updated = true;
tuf.update_root(&raw_signed_root)?;
/////////////////////////////////////////
// TUF-1.0.9 §5.1.7:
//
// Persist root metadata. The client MUST write the file to non-volatile storage as
// FILENAME.EXT (e.g. root.json).
if let Some(ref mut local) = local {
local
.store_metadata(&root_path, &MetadataVersion::None, &raw_signed_root)
.await?;
// NOTE(#301): See the comment in `Client::with_trusted_root_keys`.
local
.store_metadata(&root_path, &next_version, &raw_signed_root)
.await?;
}
/////////////////////////////////////////
// TUF-1.0.9 §5.1.8:
//
// Repeat steps 5.1.1 to 5.1.8.
}
/////////////////////////////////////////
// TUF-1.0.9 §5.1.9:
//
// Check for a freeze attack. The latest known time MUST be lower than the expiration
// timestamp in the trusted root metadata file (version N). If the trusted root
// metadata file has expired, abort the update cycle, report the potential freeze
// attack. On the next update cycle, begin at step 5.0 and version N of the root
// metadata file.
// TODO: Consider moving the root metadata expiration check into `tuf::Database`, since that's
// where we check timestamp/snapshot/targets/delegations for expiration.
if tuf.trusted_root().expires() <= &Utc::now() {
error!("Root metadata expired, potential freeze attack");
return Err(Error::ExpiredMetadata(Role::Root));
}
/////////////////////////////////////////
// TUF-1.0.5 §5.1.10:
//
// Set whether consistent snapshots are used as per the trusted root metadata file (see
// Section 4.3).
Ok(updated)
}
/// Returns `true` if an update occurred and `false` otherwise.
async fn update_timestamp(&mut self) -> Result<bool> {
Self::update_timestamp_with_repos(
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
)
.await
}
async fn update_timestamp_with_repos<Remote>(
config: &Config,
tuf: &mut Database<D>,
local: Option<&mut Repository<L, D>>,
remote: &Repository<Remote, D>,
) -> Result<bool>
where
Remote: RepositoryProvider<D>,
{
let timestamp_path = MetadataPath::from_role(&Role::Timestamp);
/////////////////////////////////////////
// TUF-1.0.9 §5.2:
//
// Download the timestamp metadata file, up to X number of bytes (because the size is
// unknown). The value for X is set by the authors of the application using TUF. For
// example, X may be tens of kilobytes. The filename used to download the timestamp
// metadata file is of the fixed form FILENAME.EXT (e.g., timestamp.json).
let raw_signed_timestamp = remote
.fetch_metadata(
×tamp_path,
&MetadataVersion::None,
config.max_timestamp_length,
vec![],
)
.await?;
if tuf.update_timestamp(&raw_signed_timestamp)?.is_some() {
/////////////////////////////////////////
// TUF-1.0.9 §5.2.4:
//
// Persist timestamp metadata. The client MUST write the file to non-volatile
// storage as FILENAME.EXT (e.g. timestamp.json).
if let Some(local) = local {
local
.store_metadata(
×tamp_path,
&MetadataVersion::None,
&raw_signed_timestamp,
)
.await?;
}
Ok(true)
} else {
Ok(false)
}
}
/// Returns `true` if an update occurred and `false` otherwise.
async fn update_snapshot(&mut self) -> Result<bool> {
let consistent_snapshot = self.tuf.trusted_root().consistent_snapshot();
Self::update_snapshot_with_repos(
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
consistent_snapshot,
)
.await
}
async fn update_snapshot_with_repos<Remote>(
config: &Config,
tuf: &mut Database<D>,
local: Option<&mut Repository<L, D>>,
remote: &Repository<Remote, D>,
consistent_snapshots: bool,
) -> Result<bool>
where
Remote: RepositoryProvider<D>,
{
let snapshot_description = match tuf.trusted_timestamp() {
Some(ts) => Ok(ts.snapshot()),
None => Err(Error::MissingMetadata(Role::Timestamp)),
}?
.clone();
if snapshot_description.version()
<= tuf.trusted_snapshot().map(|s| s.version()).unwrap_or(0)
{
return Ok(false);
}
let version = if consistent_snapshots {
MetadataVersion::Number(snapshot_description.version())
} else {
MetadataVersion::None
};
let snapshot_path = MetadataPath::from_role(&Role::Snapshot);
// https://theupdateframework.github.io/specification/v1.0.26/#update-snapshot 5.5.1:
// Download snapshot metadata file, up to either the number of bytes specified in the
// timestamp metadata file, or some Y number of bytes.
let snapshot_length = snapshot_description.length().or(config.max_snapshot_length);
// https://theupdateframework.github.io/specification/v1.0.26/#update-snapshot 5.5.2:
//
// [...] The hashes of the new snapshot metadata file MUST match the hashes, if any, listed
// in the trusted timestamp metadata.
let snapshot_hashes = crypto::retain_supported_hashes(snapshot_description.hashes());
let raw_signed_snapshot = remote
.fetch_metadata(&snapshot_path, &version, snapshot_length, snapshot_hashes)
.await?;
// https://theupdateframework.github.io/specification/v1.0.26/#update-snapshot 5.5.3 through
// 5.5.6 are checked in [Database].
if tuf.update_snapshot(&raw_signed_snapshot)? {
// https://theupdateframework.github.io/specification/v1.0.26/#update-snapshot 5.5.7:
//
// Persist snapshot metadata. The client MUST write the file to non-volatile storage as
// FILENAME.EXT (e.g. snapshot.json).
if let Some(local) = local {
local
.store_metadata(&snapshot_path, &MetadataVersion::None, &raw_signed_snapshot)
.await?;
}
Ok(true)
} else {
Ok(false)
}
}
/// Returns `true` if an update occurred and `false` otherwise.
async fn update_targets(&mut self) -> Result<bool> {
let consistent_snapshot = self.tuf.trusted_root().consistent_snapshot();
Self::update_targets_with_repos(
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
consistent_snapshot,
)
.await
}
async fn update_targets_with_repos<Remote>(
config: &Config,
tuf: &mut Database<D>,
local: Option<&mut Repository<L, D>>,
remote: &Repository<Remote, D>,
consistent_snapshot: bool,
) -> Result<bool>
where
Remote: RepositoryProvider<D>,
{
let targets_description = match tuf.trusted_snapshot() {
Some(sn) => match sn.meta().get(&MetadataPath::from_role(&Role::Targets)) {
Some(d) => Ok(d),
None => Err(Error::VerificationFailure(
"Snapshot metadata did not contain a description of the \
current targets metadata."
.into(),
)),
},
None => Err(Error::MissingMetadata(Role::Snapshot)),
}?
.clone();
if targets_description.version() <= tuf.trusted_targets().map(|t| t.version()).unwrap_or(0)
{
return Ok(false);
}
let version = if consistent_snapshot {
MetadataVersion::Number(targets_description.version())
} else {
MetadataVersion::None
};
let targets_path = MetadataPath::from_role(&Role::Targets);
// https://theupdateframework.github.io/specification/v1.0.26/#update-targets 5.6.1:
//
// Download the top-level targets metadata file, up to either the number of bytes specified
// in the snapshot metadata file, or some Z number of bytes. [...]
let targets_length = targets_description.length().or(config.max_targets_length);
// https://theupdateframework.github.io/specification/v1.0.26/#update-targets 5.6.2:
//
// Check against snapshot role’s targets hash. The hashes of the new targets metadata file
// MUST match the hashes, if any, listed in the trusted snapshot metadata. [...]
let target_hashes = crypto::retain_supported_hashes(targets_description.hashes());
let raw_signed_targets = remote
.fetch_metadata(&targets_path, &version, targets_length, target_hashes)
.await?;
if tuf.update_targets(&raw_signed_targets)? {
/////////////////////////////////////////
// TUF-1.0.9 §5.4.4:
//
// Persist targets metadata. The client MUST write the file to non-volatile storage
// as FILENAME.EXT (e.g. targets.json).
if let Some(local) = local {
local
.store_metadata(&targets_path, &MetadataVersion::None, &raw_signed_targets)
.await?;
}
Ok(true)
} else {
Ok(false)
}
}
/// Fetch a target from the remote repo.
///
/// It is **critical** that none of the bytes written to the `write` are used until this future
/// returns `Ok`, as the hash of the target is not verified until all bytes are read from the
/// repository.
pub async fn fetch_target(
&mut self,
target: &TargetPath,
) -> Result<impl AsyncRead + Send + Unpin + '_> {
let target_description = self.fetch_target_description(target).await?;
// TODO: Check the local repository to see if it already has the target.
self.remote
.fetch_target(
self.tuf.trusted_root().consistent_snapshot(),
target,
target_description,
)
.await
}
/// Fetch a target from the remote repo and write it to the local repo.
///
/// It is **critical** that none of the bytes written to the `write` are used until this future
/// returns `Ok`, as the hash of the target is not verified until all bytes are read from the
/// repository.
pub async fn fetch_target_to_local(&mut self, target: &TargetPath) -> Result<()> {
let target_description = self.fetch_target_description(target).await?;
// Since the async read we fetch from the remote repository has internal
// lifetimes, we need to break up client into sub-objects so that rust
// won't complain about trying to borrow `&self` for the fetch, and
// `&mut self` for the store.
let Client {
tuf, local, remote, ..
} = self;
// TODO: Check the local repository to see if it already has the target.
let mut read = remote
.fetch_target(
tuf.trusted_root().consistent_snapshot(),
target,
target_description,
)
.await?;
local.store_target(target, &mut read).await
}
/// Fetch a target description from the remote repo and return it.
pub async fn fetch_target_description(
&mut self,
target: &TargetPath,
) -> Result<TargetDescription> {
let snapshot = self
.tuf
.trusted_snapshot()
.ok_or(Error::MissingMetadata(Role::Snapshot))?
.clone();
let (_, target_description) = self
.lookup_target_description(false, 0, target, &snapshot, None)
.await;
target_description
}
async fn lookup_target_description(
&mut self,
default_terminate: bool,
current_depth: u32,
target: &TargetPath,
snapshot: &SnapshotMetadata,
targets: Option<(&Verified<TargetsMetadata>, MetadataPath)>,
) -> (bool, Result<TargetDescription>) {
if current_depth > self.config.max_delegation_depth {
warn!(
"Walking the delegation graph would have exceeded the configured max depth: {}",
self.config.max_delegation_depth
);
return (default_terminate, Err(Error::NotFound));
}
// these clones are dumb, but we need immutable values and not references for update
// tuf in the loop below
let (targets, targets_role) = match targets {
Some((t, role)) => (t.clone(), role),
None => match self.tuf.trusted_targets() {
Some(t) => (t.clone(), MetadataPath::from_role(&Role::Targets)),
None => {
return (
default_terminate,
Err(Error::MissingMetadata(Role::Targets)),
);
}
},
};
if let Some(t) = targets.targets().get(target) {
return (default_terminate, Ok(t.clone()));
}
let delegations = match targets.delegations() {
Some(d) => d,
None => return (default_terminate, Err(Error::NotFound)),
};
for delegation in delegations.roles().iter() {
if !delegation.paths().iter().any(|p| target.is_child(p)) {
if delegation.terminating() {
return (true, Err(Error::NotFound));
} else {
continue;
}
}
let role_meta = match snapshot.meta().get(delegation.role()) {
Some(m) => m,
None if delegation.terminating() => {
return (true, Err(Error::NotFound));
}
None => {
continue;
}
};
/////////////////////////////////////////
// TUF-1.0.9 §5.4:
//
// Download the top-level targets metadata file, up to either the number of bytes
// specified in the snapshot metadata file, or some Z number of bytes. The value
// for Z is set by the authors of the application using TUF. For example, Z may be
// tens of kilobytes. If consistent snapshots are not used (see Section 7), then
// the filename used to download the targets metadata file is of the fixed form
// FILENAME.EXT (e.g., targets.json). Otherwise, the filename is of the form
// VERSION_NUMBER.FILENAME.EXT (e.g., 42.targets.json), where VERSION_NUMBER is the
// version number of the targets metadata file listed in the snapshot metadata
// file.
let version = if self.tuf.trusted_root().consistent_snapshot() {
MetadataVersion::Number(role_meta.version())
} else {
MetadataVersion::None
};
let role_length = role_meta.length().or(self.config.max_targets_length);
// https://theupdateframework.github.io/specification/v1.0.26/#update-targets
//
// [...] The hashes of the new targets metadata file MUST match the hashes, if
// any, listed in the trusted snapshot metadata.
let role_hashes = crypto::retain_supported_hashes(role_meta.hashes());
let raw_signed_meta = match self
.remote
.fetch_metadata(delegation.role(), &version, role_length, role_hashes)
.await
{
Ok(m) => m,
Err(e) => {
warn!("Failed to fetch metadata {:?}: {:?}", delegation.role(), e);
if delegation.terminating() {
return (true, Err(e));
} else {
continue;
}
}
};
match self
.tuf
.update_delegation(&targets_role, delegation.role(), &raw_signed_meta)
{
Ok(_) => {
/////////////////////////////////////////
// TUF-1.0.9 §5.4.4:
//
// Persist targets metadata. The client MUST write the file to non-volatile
// storage as FILENAME.EXT (e.g. targets.json).
match self
.local
.store_metadata(delegation.role(), &MetadataVersion::None, &raw_signed_meta)
.await
{
Ok(_) => (),
Err(e) => {
warn!(
"Error storing metadata {:?} locally: {:?}",
delegation.role(),
e
)
}
}
let meta = self
.tuf
.trusted_delegations()
.get(delegation.role())
.unwrap()
.clone();
let f: Pin<Box<dyn Future<Output = _>>> =
Box::pin(self.lookup_target_description(
delegation.terminating(),
current_depth + 1,
target,
snapshot,
Some((&meta, delegation.role().clone())),
));
let (term, res) = f.await;
if term && res.is_err() {
return (true, res);
}
// TODO end recursion early
}
Err(_) if !delegation.terminating() => continue,
Err(e) => return (true, Err(e)),
};
}
(default_terminate, Err(Error::NotFound))
}
}
/// Deconstructed parts of a [Client].
///
/// This allows taking apart a [Client] in order to reclaim the [Database],
/// local, and remote repositories.
#[non_exhaustive]
#[derive(Debug)]
pub struct Parts<D, L, R>
where
D: DataInterchange + Sync,
L: RepositoryProvider<D> + RepositoryStorage<D>,
R: RepositoryProvider<D>,
{
/// The client configuration.
pub config: Config,
/// The Tuf database, which is updated by the [Client].
pub database: Database<D>,
/// The local repository, which is used to initialize the database, and
/// is updated by the [Client].
pub local: L,
/// The remote repository, which is used by the client to update the database.
pub remote: R,
}
/// Helper function that first tries to fetch the metadata from the local store, and if it doesn't
/// exist or does and fails to parse, try fetching it from the remote store.
async fn fetch_metadata_from_local_or_else_remote<'a, D, L, R, M>(
path: &'a MetadataPath,
version: &'a MetadataVersion,
max_length: Option<usize>,
hashes: Vec<(&'static HashAlgorithm, HashValue)>,
local: &'a Repository<L, D>,
remote: &'a Repository<R, D>,
) -> Result<(bool, RawSignedMetadata<D, M>)>
where
D: DataInterchange + Sync,
L: RepositoryProvider<D> + RepositoryStorage<D>,
R: RepositoryProvider<D>,
M: Metadata + 'static,
{
match local
.fetch_metadata(path, version, max_length, hashes.clone())
.await
{
Ok(raw_meta) => Ok((false, raw_meta)),
Err(Error::NotFound) => {
let raw_meta = remote
.fetch_metadata(path, version, max_length, hashes)
.await?;
Ok((true, raw_meta))
}
Err(err) => Err(err),
}
}
/// Configuration for a TUF `Client`.
///
/// # Defaults
///
/// The following values are considered reasonably safe defaults, however these values may change
/// as this crate moves out of beta. If you are concered about them changing, you should use the
/// `ConfigBuilder` and set your own values.
///
/// ```
/// # use tuf::client::{Config};
/// let config = Config::default();
/// assert_eq!(config.max_root_length(), &Some(500 * 1024));
/// assert_eq!(config.max_timestamp_length(), &Some(16 * 1024));
/// assert_eq!(config.max_snapshot_length(), &Some(2000000));
/// assert_eq!(config.max_targets_length(), &Some(5000000));
/// assert_eq!(config.max_delegation_depth(), 8);
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Config {
max_root_length: Option<usize>,
max_timestamp_length: Option<usize>,
max_snapshot_length: Option<usize>,
max_targets_length: Option<usize>,
max_delegation_depth: u32,
}
impl Config {
/// Initialize a `ConfigBuilder` with the default values.
pub fn build() -> ConfigBuilder {
ConfigBuilder::default()
}
/// Return the optional maximum root metadata length.
pub fn max_root_length(&self) -> &Option<usize> {
&self.max_root_length
}
/// Return the optional maximum timestamp metadata size.
pub fn max_timestamp_length(&self) -> &Option<usize> {
&self.max_timestamp_length
}
/// Return the optional maximum snapshot metadata size.
pub fn max_snapshot_length(&self) -> &Option<usize> {
&self.max_snapshot_length
}
/// Return the optional maximum targets metadata size.
pub fn max_targets_length(&self) -> &Option<usize> {
&self.max_targets_length
}
/// The maximum number of steps used when walking the delegation graph.
pub fn max_delegation_depth(&self) -> u32 {
self.max_delegation_depth
}
}
impl Default for Config {
fn default() -> Self {
Config {
max_root_length: Some(500 * 1024),
max_timestamp_length: Some(16 * 1024),
max_snapshot_length: Some(2000000),
max_targets_length: Some(5000000),
max_delegation_depth: 8,
}
}
}
/// Helper for building and validating a TUF client `Config`.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ConfigBuilder {
cfg: Config,
}
impl ConfigBuilder {
/// Validate this builder return a `Config` if validation succeeds.
pub fn finish(self) -> Result<Config> {
Ok(self.cfg)
}
/// Set the optional maximum download length for root metadata.
pub fn max_root_length(mut self, max: Option<usize>) -> Self {
self.cfg.max_root_length = max;
self
}
/// Set the optional maximum download length for timestamp metadata.
pub fn max_timestamp_length(mut self, max: Option<usize>) -> Self {
self.cfg.max_timestamp_length = max;
self
}
/// Set the optional maximum download length for snapshot metadata.
pub fn max_snapshot_length(mut self, max: Option<usize>) -> Self {
self.cfg.max_snapshot_length = max;
self
}
/// Set the optional maximum download length for targets metadata.
pub fn max_targets_length(mut self, max: Option<usize>) -> Self {
self.cfg.max_targets_length = max;
self
}
/// Set the maximum number of steps used when walking the delegation graph.
pub fn max_delegation_depth(mut self, max: u32) -> Self {
self.cfg.max_delegation_depth = max;
self
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::crypto::{Ed25519PrivateKey, HashAlgorithm, PrivateKey};
use crate::interchange::Json;
use crate::metadata::{
MetadataDescription, MetadataPath, MetadataVersion, RootMetadataBuilder,
SnapshotMetadataBuilder, TargetsMetadataBuilder, TimestampMetadataBuilder,
};
use crate::repo_builder::RepoBuilder;
use crate::repository::{EphemeralRepository, ErrorRepository, Track, TrackRepository};
use chrono::prelude::*;
use futures_executor::block_on;
use lazy_static::lazy_static;
use maplit::hashmap;
use matches::assert_matches;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::iter::once;
lazy_static! {
static ref KEYS: Vec<Ed25519PrivateKey> = {
let keys: &[&[u8]] = &[
include_bytes!("../tests/ed25519/ed25519-1.pk8.der"),
include_bytes!("../tests/ed25519/ed25519-2.pk8.der"),
include_bytes!("../tests/ed25519/ed25519-3.pk8.der"),
include_bytes!("../tests/ed25519/ed25519-4.pk8.der"),
include_bytes!("../tests/ed25519/ed25519-5.pk8.der"),
include_bytes!("../tests/ed25519/ed25519-6.pk8.der"),
];
keys.iter()
.map(|b| Ed25519PrivateKey::from_pkcs8(b).unwrap())
.collect()
};
}
#[allow(clippy::enum_variant_names)]
enum ConstructorMode {
WithTrustedLocal,
WithTrustedRoot,
WithTrustedRootKeys,
FromDatabase,
}
#[test]
fn client_constructors_err_with_not_found() {
block_on(async {
let mut local = EphemeralRepository::<Json>::new();
let remote = EphemeralRepository::<Json>::new();
let private_key =
Ed25519PrivateKey::from_pkcs8(&Ed25519PrivateKey::pkcs8().unwrap()).unwrap();
let public_key = private_key.public().clone();
assert_matches!(
Client::with_trusted_local(Config::default(), &mut local, &remote).await,
Err(Error::NotFound)
);
assert_matches!(
Client::with_trusted_root_keys(
Config::default(),
&MetadataVersion::Number(1),
1,
once(&public_key),
local,
&remote,
)
.await,
Err(Error::NotFound)
);
})
}
#[test]
fn client_constructors_err_with_invalid_keys() {
block_on(async {
let mut remote = EphemeralRepository::<Json>::new();
let good_private_key = &KEYS[0];
let bad_private_key = &KEYS[1];
let _ = RepoBuilder::create(&mut remote)
.trusted_root_keys(&[good_private_key])
.trusted_targets_keys(&[good_private_key])
.trusted_snapshot_keys(&[good_private_key])
.trusted_timestamp_keys(&[good_private_key])
.commit()
.await
.unwrap();
assert_matches!(
Client::with_trusted_root_keys(
Config::default(),
&MetadataVersion::Number(1),
1,
once(bad_private_key.public()),
EphemeralRepository::new(),
&remote,
)
.await,
Err(Error::VerificationFailure(_))
);
})
}
#[test]
fn with_trusted_local_loads_metadata_from_local_repo() {
block_on(constructors_load_metadata_from_local_repo(
ConstructorMode::WithTrustedLocal,
))
}
#[test]
fn with_trusted_root_loads_metadata_from_local_repo() {
block_on(constructors_load_metadata_from_local_repo(
ConstructorMode::WithTrustedRoot,
))
}
#[test]
fn with_trusted_root_keys_loads_metadata_from_local_repo() {
block_on(constructors_load_metadata_from_local_repo(
ConstructorMode::WithTrustedRootKeys,
))
}
#[test]
fn from_database_loads_metadata_from_local_repo() {
block_on(constructors_load_metadata_from_local_repo(
ConstructorMode::FromDatabase,
))
}
async fn constructors_load_metadata_from_local_repo(constructor_mode: ConstructorMode) {
// Store an expired root in the local store.
let mut local = EphemeralRepository::<Json>::new();
let metadata1 = RepoBuilder::create(&mut local)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| {
bld.consistent_snapshot(true)
.expires(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0))
})
.unwrap()
.commit_skip_validation()
.await
.unwrap();
// Remote repo has unexpired metadata.
let mut remote = EphemeralRepository::<Json>::new();
let metadata2 = RepoBuilder::create(&mut remote)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| bld.version(2).consistent_snapshot(true))
.unwrap()
.stage_targets_with_builder(|bld| bld.version(2))
.unwrap()
.stage_snapshot_with_builder(|bld| bld.version(2))
.unwrap()
.with_timestamp_builder(|bld| bld.version(2))
.unwrap()
.commit()
.await
.unwrap();
// Now, make sure that the local metadata got version 1.
let track_local = TrackRepository::new(local);
let track_remote = TrackRepository::new(remote);
// Make sure the client initialized metadata in the right order. Each has a slightly
// different usage of the local repository.
let mut client = match constructor_mode {
ConstructorMode::WithTrustedLocal => {
Client::with_trusted_local(Config::default(), track_local, track_remote)
.await
.unwrap()
}
ConstructorMode::WithTrustedRoot => Client::with_trusted_root(
Config::default(),
metadata1.root().unwrap(),
track_local,
track_remote,
)
.await
.unwrap(),
ConstructorMode::WithTrustedRootKeys => Client::with_trusted_root_keys(
Config::default(),
&MetadataVersion::Number(1),
1,
once(&KEYS[0].public().clone()),
track_local,
track_remote,
)
.await
.unwrap(),
ConstructorMode::FromDatabase => Client::from_database(
Config::default(),
Database::from_trusted_root(metadata1.root().unwrap()).unwrap(),
track_local,
track_remote,
)
.await
.unwrap(),
};
assert_eq!(client.tuf.trusted_root().version(), 1);
assert_eq!(client.remote.as_inner().take_tracks(), vec![]);
// According to [1], "Check for freeze attack", only the root should be
// fetched since it has expired.
//
// [1]: https://theupdateframework.github.io/specification/latest/#update-root
match constructor_mode {
ConstructorMode::WithTrustedLocal => {
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::fetch_meta_found(
&MetadataVersion::Number(1),
metadata1.root().unwrap()
),
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(2)
),
],
);
}
ConstructorMode::WithTrustedRoot => {
assert_eq!(
client.local.as_inner().take_tracks(),
vec![Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(2)
)],
);
}
ConstructorMode::WithTrustedRootKeys => {
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::fetch_meta_found(
&MetadataVersion::Number(1),
metadata1.root().unwrap()
),
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(2)
),
],
);
}
ConstructorMode::FromDatabase => {
assert_eq!(
client.local.as_inner().take_tracks(),
vec![Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(2)
)],
);
}
};
assert_matches!(client.update().await, Ok(true));
assert_eq!(client.tuf.trusted_root().version(), 2);
// We should only fetch metadata from the remote repository and write it to the local
// repository.
assert_eq!(
client.remote.as_inner().take_tracks(),
vec![
Track::fetch_meta_found(&MetadataVersion::Number(2), metadata2.root().unwrap()),
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(3)
),
Track::fetch_meta_found(&MetadataVersion::None, metadata2.timestamp().unwrap()),
Track::fetch_meta_found(&MetadataVersion::Number(2), metadata2.snapshot().unwrap()),
Track::fetch_meta_found(&MetadataVersion::Number(2), metadata2.targets().unwrap()),
],
);
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::store_meta(&MetadataVersion::None, metadata2.root().unwrap()),
Track::store_meta(&MetadataVersion::Number(2), metadata2.root().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata2.timestamp().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata2.snapshot().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata2.targets().unwrap()),
],
);
// Another update should not fetch anything.
assert_matches!(client.update().await, Ok(false));
assert_eq!(client.tuf.trusted_root().version(), 2);
// Make sure we only fetched the next root and timestamp, and didn't store anything.
assert_eq!(
client.remote.as_inner().take_tracks(),
vec![
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(3)
),
Track::fetch_meta_found(&MetadataVersion::None, metadata2.timestamp().unwrap()),
]
);
assert_eq!(client.local.as_inner().take_tracks(), vec![]);
}
#[test]
fn constructor_succeeds_with_missing_metadata() {
block_on(async {
let mut local = EphemeralRepository::<Json>::new();
let remote = EphemeralRepository::<Json>::new();
// Store only a root in the local store.
let metadata1 = RepoBuilder::create(&mut local)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| bld.consistent_snapshot(true))
.unwrap()
.skip_targets()
.skip_snapshot()
.skip_timestamp()
.commit()
.await
.unwrap();
let track_local = TrackRepository::new(local);
let track_remote = TrackRepository::new(remote);
// Create a client, which should try to fetch metadata from the local store.
let client = Client::with_trusted_root(
Config::default(),
metadata1.root().unwrap(),
track_local,
track_remote,
)
.await
.unwrap();
assert_eq!(client.tuf.trusted_root().version(), 1);
// We shouldn't fetch metadata.
assert_eq!(client.remote.as_inner().take_tracks(), vec![]);
// We should have tried fetching a new timestamp, but it shouldn't exist in the
// repository.
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(2)
),
Track::FetchErr(
MetadataPath::from_role(&Role::Timestamp),
MetadataVersion::None
)
],
);
// An update should succeed.
let mut parts = client.into_parts();
let metadata2 = RepoBuilder::create(parts.remote.as_inner_mut())
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| bld.version(2).consistent_snapshot(true))
.unwrap()
.stage_targets_with_builder(|bld| bld.version(2))
.unwrap()
.stage_snapshot_with_builder(|bld| bld.version(2))
.unwrap()
.with_timestamp_builder(|bld| bld.version(2))
.unwrap()
.commit()
.await
.unwrap();
let mut client = Client::from_parts(parts);
assert_matches!(client.update().await, Ok(true));
assert_eq!(client.tuf.trusted_root().version(), 2);
// We should have fetched the metadata, and written it to the local database.
assert_eq!(
client.remote.as_inner().take_tracks(),
vec![
Track::fetch_meta_found(&MetadataVersion::Number(2), metadata2.root().unwrap()),
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(3)
),
Track::fetch_meta_found(&MetadataVersion::None, metadata2.timestamp().unwrap()),
Track::fetch_meta_found(
&MetadataVersion::Number(2),
metadata2.snapshot().unwrap()
),
Track::fetch_meta_found(
&MetadataVersion::Number(2),
metadata2.targets().unwrap()
),
],
);
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::store_meta(&MetadataVersion::None, metadata2.root().unwrap()),
Track::store_meta(&MetadataVersion::Number(2), metadata2.root().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata2.timestamp().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata2.snapshot().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata2.targets().unwrap()),
],
);
})
}
#[test]
fn constructor_succeeds_with_expired_metadata() {
block_on(async {
let mut local = EphemeralRepository::<Json>::new();
let remote = EphemeralRepository::<Json>::new();
// Store an expired root in the local store.
let metadata1 = RepoBuilder::create(&mut local)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| {
bld.version(1)
.consistent_snapshot(true)
.expires(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0))
})
.unwrap()
.commit_skip_validation()
.await
.unwrap();
let metadata2 = RepoBuilder::create(&mut local)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| {
bld.version(2)
.consistent_snapshot(true)
.expires(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0))
})
.unwrap()
.stage_targets_with_builder(|bld| bld.version(2))
.unwrap()
.stage_snapshot_with_builder(|bld| bld.version(2))
.unwrap()
.with_timestamp_builder(|bld| bld.version(2))
.unwrap()
.commit_skip_validation()
.await
.unwrap();
// Now, make sure that the local metadata got version 1.
let track_local = TrackRepository::new(local);
let track_remote = TrackRepository::new(remote);
let client = Client::with_trusted_root(
Config::default(),
metadata1.root().unwrap(),
track_local,
track_remote,
)
.await
.unwrap();
assert_eq!(client.tuf.trusted_root().version(), 2);
// We shouldn't fetch metadata.
assert_eq!(client.remote.as_inner().take_tracks(), vec![]);
// We should only load the root metadata, but because it's expired we don't try
// fetching the other local metadata.
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::fetch_meta_found(&MetadataVersion::Number(2), metadata2.root().unwrap()),
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(3)
)
],
);
// An update should succeed.
let mut parts = client.into_parts();
let _metadata3 = RepoBuilder::create(&mut parts.remote)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| {
bld.version(3)
.consistent_snapshot(true)
.expires(Utc.ymd(2038, 1, 1).and_hms(0, 0, 0))
})
.unwrap()
.stage_targets_with_builder(|bld| bld.version(2))
.unwrap()
.stage_snapshot_with_builder(|bld| bld.version(2))
.unwrap()
.with_timestamp_builder(|bld| bld.version(2))
.unwrap()
.commit()
.await
.unwrap();
let mut client = Client::from_parts(parts);
assert_matches!(client.update().await, Ok(true));
assert_eq!(client.tuf.trusted_root().version(), 3);
})
}
#[test]
fn constructor_succeeds_with_malformed_metadata() {
block_on(async {
// Store a malformed timestamp in the local repository.
let mut local = EphemeralRepository::<Json>::new();
let junk_timestamp = "junk timestamp";
local
.store_metadata(
&MetadataPath::from_role(&Role::Timestamp),
&MetadataVersion::None,
&mut junk_timestamp.as_bytes(),
)
.await
.unwrap();
// Create a normal repository on the remote server.
let mut remote = EphemeralRepository::<Json>::new();
let metadata1 = RepoBuilder::create(&mut remote)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.commit()
.await
.unwrap();
// Create the client. It should ignore the malformed timestamp.
let track_local = TrackRepository::new(local);
let track_remote = TrackRepository::new(remote);
let mut client = Client::with_trusted_root(
Config::default(),
metadata1.root().unwrap(),
track_local,
track_remote,
)
.await
.unwrap();
assert_eq!(client.tuf.trusted_root().version(), 1);
// We shouldn't fetch metadata.
assert_eq!(client.remote.as_inner().take_tracks(), vec![]);
// We should only load the root metadata, but because it's expired we don't try
// fetching the other local metadata.
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::FetchErr(
MetadataPath::from_role(&Role::Root),
MetadataVersion::Number(2)
),
Track::FetchFound {
path: MetadataPath::from_role(&Role::Timestamp),
version: MetadataVersion::None,
metadata: junk_timestamp.into(),
},
],
);
// An update should work.
assert_matches!(client.update().await, Ok(true));
})
}
#[test]
fn root_chain_update_consistent_snapshot_false() {
block_on(root_chain_update(false))
}
#[test]
fn root_chain_update_consistent_snapshot_true() {
block_on(root_chain_update(true))
}
async fn root_chain_update(consistent_snapshot: bool) {
let mut repo = EphemeralRepository::<Json>::new();
// First, create the initial metadata. We want to use the same non-root
// metadata, so sign it with all the keys.
let metadata1 = RepoBuilder::create(&mut repo)
.trusted_root_keys(&[&KEYS[0]])
.signing_targets_keys(&[&KEYS[1], &KEYS[2]])
.trusted_targets_keys(&[&KEYS[0]])
.signing_snapshot_keys(&[&KEYS[1], &KEYS[2]])
.trusted_snapshot_keys(&[&KEYS[0]])
.signing_timestamp_keys(&[&KEYS[1], &KEYS[2]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| bld.consistent_snapshot(consistent_snapshot))
.unwrap()
.commit()
.await
.unwrap();
let root_path = MetadataPath::from_role(&Role::Root);
let timestamp_path = MetadataPath::from_role(&Role::Timestamp);
let targets_version;
let snapshot_version;
if consistent_snapshot {
targets_version = MetadataVersion::Number(1);
snapshot_version = MetadataVersion::Number(1);
} else {
targets_version = MetadataVersion::None;
snapshot_version = MetadataVersion::None;
};
// Now, make sure that the local metadata got version 1.
let track_local = TrackRepository::new(EphemeralRepository::new());
let track_remote = TrackRepository::new(repo);
let mut client = Client::with_trusted_root_keys(
Config::default(),
&MetadataVersion::Number(1),
1,
once(&KEYS[0].public().clone()),
track_local,
track_remote,
)
.await
.unwrap();
// Check that we tried to load metadata from the local repository.
assert_eq!(
client.remote.as_inner().take_tracks(),
vec![Track::fetch_found(
&root_path,
&MetadataVersion::Number(1),
metadata1.root().unwrap().as_bytes()
),]
);
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::FetchErr(root_path.clone(), MetadataVersion::Number(1)),
Track::store_meta(&MetadataVersion::Number(1), metadata1.root().unwrap()),
Track::FetchErr(root_path.clone(), MetadataVersion::Number(2)),
Track::FetchErr(timestamp_path.clone(), MetadataVersion::None),
]
);
assert_matches!(client.update().await, Ok(true));
assert_eq!(client.tuf.trusted_root().version(), 1);
// Make sure we fetched the metadata in the right order.
assert_eq!(
client.remote.as_inner().take_tracks(),
vec![
Track::FetchErr(root_path.clone(), MetadataVersion::Number(2)),
Track::fetch_meta_found(&MetadataVersion::None, metadata1.timestamp().unwrap()),
Track::fetch_meta_found(&snapshot_version, metadata1.snapshot().unwrap()),
Track::fetch_meta_found(&targets_version, metadata1.targets().unwrap()),
]
);
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::store_meta(&MetadataVersion::None, metadata1.timestamp().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata1.snapshot().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata1.targets().unwrap()),
],
);
// Another update should not fetch anything.
assert_matches!(client.update().await, Ok(false));
assert_eq!(client.tuf.trusted_root().version(), 1);
// Make sure we only fetched the next root and timestamp, and didn't store anything.
assert_eq!(
client.remote.as_inner().take_tracks(),
vec![
Track::FetchErr(root_path.clone(), MetadataVersion::Number(2)),
Track::fetch_meta_found(&MetadataVersion::None, metadata1.timestamp().unwrap()),
]
);
assert_eq!(client.local.as_inner().take_tracks(), vec![]);
////
// Now bump the root to version 3
// Make sure the version 2 is also signed by version 1's keys.
//
// Note that we write to the underlying store so TrackRepo doesn't track
// this new metadata.
let mut parts = client.into_parts();
let metadata2 = RepoBuilder::create(parts.remote.as_inner_mut())
.signing_root_keys(&[&KEYS[0]])
.trusted_root_keys(&[&KEYS[1]])
.trusted_targets_keys(&[&KEYS[1]])
.trusted_snapshot_keys(&[&KEYS[1]])
.trusted_timestamp_keys(&[&KEYS[1]])
.stage_root_with_builder(|bld| bld.version(2).consistent_snapshot(consistent_snapshot))
.unwrap()
.skip_targets()
.skip_snapshot()
.skip_timestamp()
.commit()
.await
.unwrap();
// Make sure the version 3 is also signed by version 2's keys.
let metadata3 = RepoBuilder::create(parts.remote.as_inner_mut())
.signing_root_keys(&[&KEYS[1]])
.trusted_root_keys(&[&KEYS[2]])
.trusted_targets_keys(&[&KEYS[2]])
.trusted_snapshot_keys(&[&KEYS[2]])
.trusted_timestamp_keys(&[&KEYS[2]])
.stage_root_with_builder(|bld| bld.version(3).consistent_snapshot(consistent_snapshot))
.unwrap()
.skip_targets()
.skip_snapshot()
.skip_timestamp()
.commit()
.await
.unwrap();
////
// Finally, check that the update brings us to version 3.
let mut client = Client::from_parts(parts);
assert_matches!(client.update().await, Ok(true));
assert_eq!(client.tuf.trusted_root().version(), 3);
// Make sure we fetched and stored the metadata in the expected order. Note that we
// re-fetch snapshot and targets because we rotated keys, which caused `tuf::Database` to delete
// the metadata.
assert_eq!(
client.remote.as_inner().take_tracks(),
vec![
Track::fetch_meta_found(&MetadataVersion::Number(2), metadata2.root().unwrap()),
Track::fetch_meta_found(&MetadataVersion::Number(3), metadata3.root().unwrap()),
Track::FetchErr(root_path.clone(), MetadataVersion::Number(4)),
Track::fetch_meta_found(&MetadataVersion::None, metadata1.timestamp().unwrap()),
Track::fetch_meta_found(&snapshot_version, metadata1.snapshot().unwrap()),
Track::fetch_meta_found(&targets_version, metadata1.targets().unwrap()),
]
);
assert_eq!(
client.local.as_inner().take_tracks(),
vec![
Track::store_meta(&MetadataVersion::None, metadata2.root().unwrap()),
Track::store_meta(&MetadataVersion::Number(2), metadata2.root().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata3.root().unwrap()),
Track::store_meta(&MetadataVersion::Number(3), metadata3.root().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata1.timestamp().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata1.snapshot().unwrap()),
Track::store_meta(&MetadataVersion::None, metadata1.targets().unwrap()),
],
);
}
#[test]
fn test_fetch_target_description_standard() {
block_on(test_fetch_target_description(
"standard/metadata".to_string(),
TargetDescription::from_slice(
"target with no custom metadata".as_bytes(),
&[HashAlgorithm::Sha256],
)
.unwrap(),
));
}
#[test]
fn test_fetch_target_description_custom_empty() {
block_on(test_fetch_target_description(
"custom-empty".to_string(),
TargetDescription::from_slice_with_custom(
"target with empty custom metadata".as_bytes(),
&[HashAlgorithm::Sha256],
hashmap!(),
)
.unwrap(),
));
}
#[test]
fn test_fetch_target_description_custom() {
block_on(test_fetch_target_description(
"custom/metadata".to_string(),
TargetDescription::from_slice_with_custom(
"target with lots of custom metadata".as_bytes(),
&[HashAlgorithm::Sha256],
hashmap!(
"string".to_string() => json!("string"),
"bool".to_string() => json!(true),
"int".to_string() => json!(42),
"object".to_string() => json!({
"string": json!("string"),
"bool": json!(true),
"int": json!(42),
}),
"array".to_string() => json!([1, 2, 3]),
),
)
.unwrap(),
));
}
async fn test_fetch_target_description(path: String, expected_description: TargetDescription) {
// Generate an ephemeral repository with a single target.
let mut remote = EphemeralRepository::<Json>::new();
let metadata = RepoBuilder::create(&mut remote)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root()
.unwrap()
.stage_targets_with_builder(|bld| {
bld.insert_target_description(
TargetPath::new(path.clone()).unwrap(),
expected_description.clone(),
)
})
.unwrap()
.commit()
.await
.unwrap();
// Initialize and update client.
let mut client = Client::with_trusted_root(
Config::default(),
metadata.root().unwrap(),
EphemeralRepository::new(),
remote,
)
.await
.unwrap();
assert_matches!(client.update().await, Ok(true));
// Verify fetch_target_description returns expected target metadata
let description = client
.fetch_target_description(&TargetPath::new(path).unwrap())
.await
.unwrap();
assert_eq!(description, expected_description);
}
#[test]
fn update_eventually_succeeds_if_cannot_write_to_repo() {
block_on(async {
let mut remote = EphemeralRepository::<Json>::new();
// First, create the metadata.
let _ = RepoBuilder::create(&mut remote)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.commit()
.await
.unwrap();
// Now, make sure that the local metadata got version 1.
let local = ErrorRepository::new(EphemeralRepository::new());
let mut client = Client::with_trusted_root_keys(
Config::default(),
&MetadataVersion::Number(1),
1,
once(&KEYS[0].public().clone()),
local,
remote,
)
.await
.unwrap();
// The first update should succeed.
assert_matches!(client.update().await, Ok(true));
// Make sure the database is correct.
let mut parts = client.into_parts();
assert_eq!(parts.database.trusted_root().version(), 1);
assert_eq!(parts.database.trusted_timestamp().unwrap().version(), 1);
assert_eq!(parts.database.trusted_snapshot().unwrap().version(), 1);
assert_eq!(parts.database.trusted_targets().unwrap().version(), 1);
// Publish new metadata.
let _ = RepoBuilder::create(&mut parts.remote)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| bld.version(2))
.unwrap()
.stage_targets_with_builder(|bld| bld.version(2))
.unwrap()
.stage_snapshot_with_builder(|bld| bld.version(2))
.unwrap()
.with_timestamp_builder(|bld| bld.version(2))
.unwrap()
.commit()
.await
.unwrap();
// Make sure we fail to write metadata to the local store.
parts.local.fail_metadata_stores(true);
// The second update should fail.
let mut client = Client::from_parts(parts);
assert_matches!(client.update().await, Err(Error::Encoding(_)));
// FIXME(#297): rust-tuf diverges from the spec by throwing away the
// metadata if the root is updated.
assert_eq!(client.trusted_root().version(), 2);
assert_eq!(client.trusted_timestamp(), None);
assert_eq!(client.trusted_snapshot(), None);
assert_eq!(client.trusted_targets(), None);
// However, due to https://github.com/theupdateframework/specification/issues/131, if
// the update is retried a few times it will still succeed.
assert_matches!(client.update().await, Err(Error::Encoding(_)));
assert_eq!(client.trusted_root().version(), 2);
assert_eq!(client.trusted_timestamp().unwrap().version(), 2);
assert_eq!(client.trusted_snapshot(), None);
assert_eq!(client.trusted_targets(), None);
assert_matches!(client.update().await, Err(Error::Encoding(_)));
assert_eq!(client.trusted_root().version(), 2);
assert_eq!(client.trusted_timestamp().unwrap().version(), 2);
assert_eq!(client.trusted_snapshot().unwrap().version(), 2);
assert_eq!(client.trusted_targets(), None);
assert_matches!(client.update().await, Err(Error::Encoding(_)));
assert_eq!(client.trusted_root().version(), 2);
assert_eq!(client.trusted_timestamp().unwrap().version(), 2);
assert_eq!(client.trusted_snapshot().unwrap().version(), 2);
assert_eq!(client.trusted_targets().unwrap().version(), 2);
assert_matches!(client.update().await, Ok(false));
assert_eq!(client.trusted_root().version(), 2);
assert_eq!(client.trusted_timestamp().unwrap().version(), 2);
assert_eq!(client.trusted_snapshot().unwrap().version(), 2);
assert_eq!(client.trusted_targets().unwrap().version(), 2);
});
}
#[test]
fn with_trusted_methods_return_correct_metadata() {
block_on(async {
let mut local = EphemeralRepository::<Json>::new();
let remote = EphemeralRepository::<Json>::new();
// Store an expired root in the local store.
let metadata1 = RepoBuilder::create(&mut local)
.trusted_root_keys(&[&KEYS[0]])
.trusted_targets_keys(&[&KEYS[0]])
.trusted_snapshot_keys(&[&KEYS[0]])
.trusted_timestamp_keys(&[&KEYS[0]])
.stage_root_with_builder(|bld| {
bld.consistent_snapshot(true)
.expires(Utc.ymd(1970, 1, 1).and_hms(0, 0, 0))
})
.unwrap()
.commit_skip_validation()
.await
.unwrap();
let track_local = TrackRepository::new(local);
let track_remote = TrackRepository::new(remote);
let client = Client::with_trusted_root(
Config::default(),
metadata1.root().unwrap(),
track_local,
track_remote,
)
.await
.unwrap();
assert_eq!(client.trusted_targets(), client.tuf.trusted_targets());
assert_eq!(client.trusted_snapshot(), client.tuf.trusted_snapshot());
assert_eq!(client.trusted_timestamp(), client.tuf.trusted_timestamp());
assert_eq!(
client.trusted_delegations(),
client.tuf.trusted_delegations()
);
})
}
#[test]
fn client_can_update_with_unknown_len_and_hashes() {
block_on(async {
let mut repo = EphemeralRepository::<Json>::new();
let root = RootMetadataBuilder::new()
.consistent_snapshot(true)
.root_key(KEYS[0].public().clone())
.targets_key(KEYS[1].public().clone())
.snapshot_key(KEYS[2].public().clone())
.timestamp_key(KEYS[3].public().clone())
.signed::<Json>(&KEYS[0])
.unwrap()
.to_raw()
.unwrap();
repo.store_metadata(
&MetadataPath::from_role(&Role::Root),
&MetadataVersion::Number(1),
&mut root.as_bytes(),
)
.await
.unwrap();
let targets = TargetsMetadataBuilder::new()
.signed::<Json>(&KEYS[1])
.unwrap()
.to_raw()
.unwrap();
repo.store_metadata(
&MetadataPath::from_role(&Role::Targets),
&MetadataVersion::Number(1),
&mut targets.as_bytes(),
)
.await
.unwrap();
// Create a targets metadata description, and deliberately don't set the metadata length
// or hashes.
let targets_description = MetadataDescription::new(1, None, HashMap::new()).unwrap();
let snapshot = SnapshotMetadataBuilder::new()
.insert_metadata_description(
MetadataPath::from_role(&Role::Targets),
targets_description,
)
.signed::<Json>(&KEYS[2])
.unwrap()
.to_raw()
.unwrap();
repo.store_metadata(
&MetadataPath::from_role(&Role::Snapshot),
&MetadataVersion::Number(1),
&mut snapshot.as_bytes(),
)
.await
.unwrap();
// Create a snapshot metadata description, and deliberately don't set the metadata length
// or hashes.
let timestamp_description = MetadataDescription::new(1, None, HashMap::new()).unwrap();
let timestamp =
TimestampMetadataBuilder::from_metadata_description(timestamp_description)
.signed::<Json>(&KEYS[3])
.unwrap()
.to_raw()
.unwrap();
repo.store_metadata(
&MetadataPath::from_role(&Role::Timestamp),
&MetadataVersion::None,
&mut timestamp.as_bytes(),
)
.await
.unwrap();
let mut client = Client::with_trusted_root_keys(
Config::default(),
&MetadataVersion::Number(1),
1,
once(&KEYS[0].public().clone()),
EphemeralRepository::new(),
repo,
)
.await
.unwrap();
assert_matches!(client.update().await, Ok(true));
})
}
}