/
client.rs
2437 lines (2190 loc) · 88.6 KB
/
client.rs
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
//! Clients for high level interactions with TUF repositories.
//!
//! # Example
//!
//! ```no_run
//! # use futures_executor::block_on;
//! # 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, DateTime};
use futures_io::AsyncRead;
use log::{error, warn};
use std::future::Future;
use std::pin::Pin;
use crate::crypto::{self, HashAlgorithm, HashValue, PublicKey};
use crate::database::Database;
use crate::error::{Error, Result};
use crate::interchange::DataInterchange;
use crate::metadata::{
Metadata, MetadataPath, MetadataVersion, RawSignedMetadata, RootMetadata, SnapshotMetadata,
TargetDescription, TargetPath, TargetsMetadata,
};
use crate::repository::{Repository, RepositoryProvider, RepositoryStorage};
use crate::verify::Verified;
/// 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::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::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::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::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 start_time = Utc::now();
let res = async {
let _r =
Self::update_root_with_repos(&start_time, &config, &mut tuf, None, &local).await?;
let _ts =
Self::update_timestamp_with_repos(&start_time, &config, &mut tuf, None, &local)
.await?;
let _sn = Self::update_snapshot_with_repos(
&start_time,
&config,
&mut tuf,
None,
&local,
false,
)
.await?;
let _ta = Self::update_targets_with_repos(
&start_time,
&config,
&mut tuf,
None,
&local,
false,
)
.await?;
Ok(())
}
.await;
match res {
Ok(()) | Err(Error::MetadataNotFound { .. }) => {}
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> {
self.update_with_start_time(&Utc::now()).await
}
/// Update TUF metadata from the remote repository, using the specified time to determine if
/// the metadata is expired.
///
/// Returns `true` if an update occurred and `false` otherwise.
///
/// **WARNING**: Using an older time opens up users to a freeze attack.
pub async fn update_with_start_time(&mut self, start_time: &DateTime<Utc>) -> Result<bool> {
let r = self.update_root(start_time).await?;
let ts = self.update_timestamp(start_time).await?;
let sn = self.update_snapshot(start_time).await?;
let ta = self.update_targets(start_time).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 a reference to the TUF database.
pub fn database(&self) -> &Database<D> {
&self.tuf
}
/// Returns a mutable reference to the TUF database.
pub fn database_mut(&mut self) -> &mut Database<D> {
&mut self.tuf
}
/// Returns a refrerence to the local repository.
pub fn local_repo(&self) -> &L {
self.local.as_inner()
}
/// Returns a mutable reference to the local repository.
pub fn local_repo_mut(&mut self) -> &mut L {
self.local.as_inner_mut()
}
/// Returns a refrerence to the remote repository.
pub fn remote_repo(&self) -> &R {
self.remote.as_inner()
}
/// Returns a mutable reference to the remote repository.
pub fn remote_repo_mut(&mut self) -> &mut R {
self.remote.as_inner_mut()
}
/// Update TUF root metadata from the remote repository.
///
/// Returns `true` if an update occurred and `false` otherwise.
pub async fn update_root(&mut self, start_time: &DateTime<Utc>) -> Result<bool> {
Self::update_root_with_repos(
start_time,
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
)
.await
}
async fn update_root_with_repos<Remote>(
start_time: &DateTime<Utc>,
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::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::MetadataNotFound { .. }) => {
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() <= start_time {
error!("Root metadata expired, potential freeze attack");
return Err(Error::ExpiredMetadata(MetadataPath::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, start_time: &DateTime<Utc>) -> Result<bool> {
Self::update_timestamp_with_repos(
start_time,
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
)
.await
}
async fn update_timestamp_with_repos<Remote>(
start_time: &DateTime<Utc>,
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::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(start_time, &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, start_time: &DateTime<Utc>) -> Result<bool> {
let consistent_snapshot = self.tuf.trusted_root().consistent_snapshot();
Self::update_snapshot_with_repos(
start_time,
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
consistent_snapshot,
)
.await
}
async fn update_snapshot_with_repos<Remote>(
start_time: &DateTime<Utc>,
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::MetadataNotFound {
path: MetadataPath::timestamp(),
version: MetadataVersion::None,
}),
}?
.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::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(start_time, &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, start_time: &DateTime<Utc>) -> Result<bool> {
let consistent_snapshot = self.tuf.trusted_root().consistent_snapshot();
Self::update_targets_with_repos(
start_time,
&self.config,
&mut self.tuf,
Some(&mut self.local),
&self.remote,
consistent_snapshot,
)
.await
}
async fn update_targets_with_repos<Remote>(
start_time: &DateTime<Utc>,
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::targets()) {
Some(d) => Ok(d),
None => Err(Error::MissingMetadataDescription {
parent_role: MetadataPath::snapshot(),
child_role: MetadataPath::targets(),
}),
},
None => Err(Error::MetadataNotFound {
path: MetadataPath::snapshot(),
version: MetadataVersion::None,
}),
}?
.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::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(start_time, &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 + '_> {
self.fetch_target_with_start_time(target, &Utc::now()).await
}
/// 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_with_start_time(
&mut self,
target: &TargetPath,
start_time: &DateTime<Utc>,
) -> Result<impl AsyncRead + Send + Unpin + '_> {
let target_description = self
.fetch_target_description_with_start_time(target, start_time)
.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<()> {
self.fetch_target_to_local_with_start_time(target, &Utc::now())
.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_with_start_time(
&mut self,
target: &TargetPath,
start_time: &DateTime<Utc>,
) -> Result<()> {
let target_description = self
.fetch_target_description_with_start_time(target, start_time)
.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> {
self.fetch_target_description_with_start_time(target, &Utc::now())
.await
}
/// Fetch a target description from the remote repo and return it.
pub async fn fetch_target_description_with_start_time(
&mut self,
target: &TargetPath,
start_time: &DateTime<Utc>,
) -> Result<TargetDescription> {
let snapshot = self
.tuf
.trusted_snapshot()
.ok_or_else(|| Error::MetadataNotFound {
path: MetadataPath::snapshot(),
version: MetadataVersion::None,
})?
.clone();
/////////////////////////////////////////
// https://theupdateframework.github.io/specification/v1.0.30/#update-targets:
//
// 7. **Perform a pre-order depth-first search for metadata about the
// desired target, beginning with the top-level targets role.** Note: If
// any metadata requested in steps 5.6.7.1 - 5.6.7.2 cannot be downloaded nor
// validated, end the search and report that the target cannot be found.
let (_, target_description) = self
.lookup_target_description(start_time, false, 0, target, &snapshot, None)
.await;
target_description
}
async fn lookup_target_description(
&mut self,
start_time: &DateTime<Utc>,
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::TargetNotFound(target.clone())),
);
}
// 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::targets()),
None => {
return (
default_terminate,
Err(Error::MetadataNotFound {
path: MetadataPath::targets(),
version: MetadataVersion::None,
}),
);
}
},
};
if let Some(t) = targets.targets().get(target) {
return (default_terminate, Ok(t.clone()));
}
for delegation in targets.delegations().roles() {
if !delegation.paths().iter().any(|p| target.is_child(p)) {
if delegation.terminating() {