-
Notifications
You must be signed in to change notification settings - Fork 33
/
client.rs
1809 lines (1611 loc) · 58.9 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, Tuf};
//! # use tuf::crypto::KeyId;
//! # use tuf::client::{Client, Config};
//! # use tuf::metadata::{RootMetadata, SignedMetadata, Role, MetadataPath,
//! # MetadataVersion};
//! # use tuf::interchange::Json;
//! # use tuf::repository::{FileSystemRepository, HttpRepositoryBuilder, Repository};
//!
//! static TRUSTED_ROOT_KEY_IDS: &'static [&str] = &[
//! "4750eaf6878740780d6f97b12dbad079fb012bec88c78de2c380add56d3f51db",
//! "01892c662c8cd79fab20edec21de1dcb8b75d9353103face7fe086ff5c0098e4",
//! "0823260c29956d0b64baa19a64c49c87922ba2bc532d09a6965aef044da490bd",
//! ];
//!
//! # fn main() -> Result<()> {
//! # block_on(async {
//! let key_ids: Vec<KeyId> = TRUSTED_ROOT_KEY_IDS.iter()
//! .map(|k| KeyId::from_str(k).unwrap())
//! .collect();
//!
//! 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_keyids(
//! Config::default(),
//! &MetadataVersion::Number(1),
//! 1,
//! &key_ids,
//! local,
//! Repository::<_, Json>::new(remote),
//! ).await?;
//!
//! let _ = client.update().await?;
//! # Ok(())
//! # })
//! # }
//! ```
use chrono::offset::Utc;
use futures_io::{AsyncRead, AsyncWrite};
use futures_util::io::copy;
use log::{error, warn};
use std::future::Future;
use std::pin::Pin;
use crate::crypto::{self, HashAlgorithm, HashValue, KeyId, PublicKey};
use crate::error::Error;
use crate::interchange::DataInterchange;
use crate::metadata::{
Metadata, MetadataPath, MetadataVersion, RawSignedMetadata, Role, RootMetadata, SignedMetadata,
SnapshotMetadata, TargetDescription, TargetPath, TargetsMetadata, VirtualTargetPath,
};
use crate::repository::{Repository, RepositoryProvider, RepositoryStorage};
use crate::tuf::Tuf;
use crate::Result;
/// Translates real paths (where a file is stored) into virtual paths (how it is addressed in TUF)
/// and back.
///
/// Implementations must obey the following identities for all possible inputs.
///
/// ```
/// # use tuf::client::{PathTranslator, DefaultTranslator};
/// # use tuf::metadata::{VirtualTargetPath, TargetPath};
/// let path = TargetPath::new("foo".into()).unwrap();
/// let virt = VirtualTargetPath::new("foo".into()).unwrap();
/// let translator = DefaultTranslator::new();
/// assert_eq!(path,
/// translator.virtual_to_real(&translator.real_to_virtual(&path).unwrap()).unwrap());
/// assert_eq!(virt,
/// translator.real_to_virtual(&translator.virtual_to_real(&virt).unwrap()).unwrap());
/// ```
pub trait PathTranslator {
/// Convert a real path into a virtual path.
fn real_to_virtual(&self, path: &TargetPath) -> Result<VirtualTargetPath>;
/// Convert a virtual path into a real path.
fn virtual_to_real(&self, path: &VirtualTargetPath) -> Result<TargetPath>;
}
/// A `PathTranslator` that does nothing.
#[derive(Clone, Debug, Default)]
pub struct DefaultTranslator;
impl DefaultTranslator {
/// Create a new `DefaultTranslator`.
pub fn new() -> Self {
DefaultTranslator
}
}
impl PathTranslator for DefaultTranslator {
fn real_to_virtual(&self, path: &TargetPath) -> Result<VirtualTargetPath> {
VirtualTargetPath::new(path.value().into())
}
fn virtual_to_real(&self, path: &VirtualTargetPath) -> Result<TargetPath> {
TargetPath::new(path.value().into())
}
}
/// A client that interacts with TUF repositories.
#[derive(Debug)]
pub struct Client<D, L, R, T>
where
D: DataInterchange + Sync,
L: RepositoryProvider<D> + RepositoryStorage<D>,
R: RepositoryProvider<D>,
T: PathTranslator,
{
tuf: Tuf<D>,
config: Config<T>,
local: Repository<L, D>,
remote: Repository<R, D>,
}
impl<D, L, R, T> Client<D, L, R, T>
where
D: DataInterchange + Sync,
L: RepositoryProvider<D> + RepositoryStorage<D>,
R: RepositoryProvider<D>,
T: PathTranslator,
{
/// 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`] and
/// [`Client::with_trusted_root_keyids`].
///
/// # Examples
///
/// ```
/// # use chrono::offset::{Utc, TimeZone};
/// # use futures_executor::block_on;
/// # use tuf::{
/// # Error,
/// # interchange::Json,
/// # client::{Client, Config},
/// # crypto::{KeyType, PrivateKey, SignatureScheme},
/// # metadata::{MetadataPath, MetadataVersion, Role, RootMetadataBuilder},
/// # repository::{EphemeralRepository, Repository, RepositoryStorage},
/// # };
/// # fn main() -> Result<(), Error> {
/// # block_on(async {
/// # let private_key = PrivateKey::from_pkcs8(
/// # &PrivateKey::new(KeyType::Ed25519)?,
/// # SignatureScheme::Ed25519,
/// # )?;
/// # let public_key = private_key.public().clone();
/// let 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,
/// 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<T>,
local: impl Into<Repository<L, D>>,
remote: impl Into<Repository<R, D>>,
) -> Result<Self> {
let root_path = MetadataPath::from_role(&Role::Root);
let (local, remote) = (local.into(), remote.into());
// FIXME should this be MetadataVersion::None so we bootstrap with the latest version?
let root_version = MetadataVersion::Number(1);
let (_, root) = local
.fetch_metadata(&root_path, &root_version, config.max_root_length, None)
.await?;
let tuf = Tuf::from_trusted_root(root)?;
Ok(Client {
tuf,
config,
local,
remote,
})
}
/// 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::{KeyType, PrivateKey, SignatureScheme},
/// # metadata::{MetadataPath, MetadataVersion, Role, RootMetadataBuilder},
/// # repository::{EphemeralRepository, Repository},
/// # };
/// # fn main() -> Result<(), Error> {
/// # block_on(async {
/// # let private_key = PrivateKey::from_pkcs8(
/// # &PrivateKey::new(KeyType::Ed25519)?,
/// # SignatureScheme::Ed25519,
/// # )?;
/// # 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 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();
///
/// let client = Client::with_trusted_root(
/// Config::default(),
/// root,
/// local,
/// remote,
/// ).await?;
/// # Ok(())
/// # })
/// # }
/// ```
pub async fn with_trusted_root(
config: Config<T>,
trusted_root: SignedMetadata<D, RootMetadata>,
local: impl Into<Repository<L, D>>,
remote: impl Into<Repository<R, D>>,
) -> Result<Self> {
let tuf = Tuf::from_trusted_root(trusted_root.clone())?;
let (local, remote) = (local.into(), remote.into());
Ok(Client {
tuf,
config,
local,
remote,
})
}
/// Create a new TUF client. It will attempt to load initial root metadata the local and remote
/// repositories, then extract out the public keys from this metadata that correspond to the
/// provided key ids, and finally establish trust by verifying the root metadata was signed
/// with these keys.
///
/// # Examples
///
/// ```
/// # use chrono::offset::{Utc, TimeZone};
/// # use futures_executor::block_on;
/// # use std::iter::once;
/// # use tuf::{
/// # Error,
/// # interchange::Json,
/// # client::{Client, Config},
/// # crypto::{KeyType, PrivateKey, SignatureScheme},
/// # metadata::{MetadataPath, MetadataVersion, Role, RootMetadataBuilder},
/// # repository::{EphemeralRepository, Repository, RepositoryStorage},
/// # };
/// # fn main() -> Result<(), Error> {
/// # block_on(async {
/// # let private_key = PrivateKey::from_pkcs8(
/// # &PrivateKey::new(KeyType::Ed25519)?,
/// # SignatureScheme::Ed25519,
/// # )?;
/// # 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 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,
/// root.to_raw().unwrap().as_bytes()
/// ).await?;
///
/// let client = Client::with_trusted_root_keyids(
/// Config::default(),
/// &root_version,
/// root_threshold,
/// once(public_key.key_id()),
/// local,
/// remote,
/// ).await?;
/// # Ok(())
/// # })
/// # }
/// ```
pub async fn with_trusted_root_keyids<'a, I>(
config: Config<T>,
root_version: &MetadataVersion,
root_threshold: u32,
trusted_root_key_ids: I,
local: impl Into<Repository<L, D>>,
remote: impl Into<Repository<R, D>>,
) -> Result<Self>
where
I: IntoIterator<Item = &'a KeyId>,
{
let root_path = MetadataPath::from_role(&Role::Root);
let (local, remote) = (local.into(), remote.into());
let (fetched, raw_trusted_root, trusted_root) = fetch_metadata_from_local_or_else_remote(
&root_path,
&root_version,
config.max_root_length,
None,
&local,
&remote,
)
.await?;
// FIXME why does with_trusted_root_keyids store using the metadata version but
// with_trusted_root_keys use the version from the caller?
let root_version = MetadataVersion::Number(trusted_root.version());
// FIXME(#253) verify the trusted root version matches the provided version.
let tuf = {
let root: &RootMetadata = trusted_root.as_ref();
// Extract out the keys that correspond by the provided key ids.
let trusted_root_keys = trusted_root_key_ids
.into_iter()
.filter_map(|key_id| root.keys().get(key_id));
Tuf::from_root_with_trusted_keys(
trusted_root.clone(),
root_threshold,
trusted_root_keys,
)?
};
let mut client = Client {
tuf,
config,
local,
remote,
};
// Only store the metadata after we have validated it.
if fetched {
client
.store_metadata(&root_path, &root_version, &raw_trusted_root)
.await;
// FIXME: should we also store the root as `MetadataVersion::None`?
}
Ok(client)
}
/// 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::{KeyType, PrivateKey, SignatureScheme},
/// # metadata::{MetadataPath, MetadataVersion, Role, RootMetadataBuilder},
/// # repository::{EphemeralRepository, Repository, RepositoryStorage},
/// # };
/// # fn main() -> Result<(), Error> {
/// # block_on(async {
/// # let private_key = PrivateKey::from_pkcs8(
/// # &PrivateKey::new(KeyType::Ed25519)?,
/// # SignatureScheme::Ed25519,
/// # )?;
/// # 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 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,
/// 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<T>,
root_version: &MetadataVersion,
root_threshold: u32,
trusted_root_keys: I,
local: impl Into<Repository<L, D>>,
remote: impl Into<Repository<R, D>>,
) -> Result<Self>
where
I: IntoIterator<Item = &'a PublicKey>,
{
let root_path = MetadataPath::from_role(&Role::Root);
let (local, remote) = (local.into(), remote.into());
let (fetched, raw_root, root) = fetch_metadata_from_local_or_else_remote(
&root_path,
root_version,
config.max_root_length,
None,
&local,
&remote,
)
.await?;
// FIXME(#253) verify the trusted root version matches the provided version.
let tuf = Tuf::from_root_with_trusted_keys(root, root_threshold, trusted_root_keys)?;
let mut client = Client {
tuf,
config,
local,
remote,
};
// Only store the metadata after we have validated it.
if fetched {
client
.store_metadata(&root_path, &root_version, &raw_root)
.await;
// FIXME: should we also store the root as `MetadataVersion::None`?
}
Ok(client)
}
/// 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)
}
/// Store the metadata in the local repository. This is just a local cache, so we ignore if it
/// experiences any errors.
async fn store_metadata<'a, M>(
&'a mut self,
path: &'a MetadataPath,
version: &'a MetadataVersion,
metadata: &'a RawSignedMetadata<D, M>,
) where
M: Metadata + Sync,
{
match self.local.store_metadata(path, version, metadata).await {
Ok(()) => {}
Err(err) => {
warn!(
"failed to store metadata version {:?} to {}: {}",
version,
path.to_string(),
err,
);
}
}
}
/// Returns `true` if an update occurred and `false` otherwise.
async fn update_root(&mut self) -> Result<bool> {
let root_path = MetadataPath::from_role(&Role::Root);
let (raw_latest_root, latest_root) = self
.remote
.fetch_metadata(
&root_path,
&MetadataVersion::None,
self.config.max_root_length,
None,
)
.await?;
let latest_version = latest_root.version();
if latest_version < self.tuf.root().version() {
return Err(Error::VerificationFailure(format!(
"Latest root version is lower than current root version: {} < {}",
latest_version,
self.tuf.root().version()
)));
} else if latest_version == self.tuf.root().version() {
return Ok(false);
}
let err_msg = "TUF claimed no update occurred when one should have. \
This is a programming error. Please report this as a bug.";
for i in (self.tuf.root().version() + 1)..latest_version {
let version = MetadataVersion::Number(i);
let (raw_signed_root, signed_root) = self
.remote
.fetch_metadata(&root_path, &version, self.config.max_root_length, None)
.await?;
if !self.tuf.update_root(signed_root)? {
error!("{}", err_msg);
return Err(Error::Programming(err_msg.into()));
}
self.store_metadata(&root_path, &version, &raw_signed_root)
.await;
}
if !self.tuf.update_root(latest_root)? {
error!("{}", err_msg);
return Err(Error::Programming(err_msg.into()));
}
let latest_version = MetadataVersion::Number(latest_version);
self.store_metadata(&root_path, &latest_version, &raw_latest_root)
.await;
self.store_metadata(&root_path, &MetadataVersion::None, &raw_latest_root)
.await;
if self.tuf.root().expires() <= &Utc::now() {
error!("Root metadata expired, potential freeze attack");
return Err(Error::ExpiredMetadata(Role::Root));
}
Ok(true)
}
/// Returns `true` if an update occurred and `false` otherwise.
async fn update_timestamp(&mut self) -> Result<bool> {
let timestamp_path = MetadataPath::from_role(&Role::Timestamp);
let (raw_signed_timestamp, signed_timestamp) = self
.remote
.fetch_metadata(
×tamp_path,
&MetadataVersion::None,
self.config.max_timestamp_length,
None,
)
.await?;
let latest_version = signed_timestamp.version();
let latest_version = MetadataVersion::Number(latest_version);
if self.tuf.update_timestamp(signed_timestamp)? {
self.store_metadata(×tamp_path, &latest_version, &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> {
// 5.3.1 Check against timestamp metadata. The hashes and version number listed in the
// timestamp metadata. If hashes and version do not match, discard the new snapshot
// metadata, abort the update cycle, and report the failure.
let snapshot_description = match self.tuf.timestamp() {
Some(ts) => Ok(ts.snapshot()),
None => Err(Error::MissingMetadata(Role::Timestamp)),
}?
.clone();
if snapshot_description.version() <= self.tuf.snapshot().map(|s| s.version()).unwrap_or(0) {
return Ok(false);
}
let (alg, value) = crypto::hash_preference(snapshot_description.hashes())?;
let version = if self.tuf.root().consistent_snapshot() {
MetadataVersion::Number(snapshot_description.version())
} else {
MetadataVersion::None
};
let snapshot_path = MetadataPath::from_role(&Role::Snapshot);
let snapshot_length = Some(snapshot_description.length());
let (raw_signed_snapshot, signed_snapshot) = self
.remote
.fetch_metadata(
&snapshot_path,
&version,
snapshot_length,
Some((alg, value.clone())),
)
.await?;
if self.tuf.update_snapshot(signed_snapshot)? {
self.store_metadata(&snapshot_path, &version, &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 targets_description = match self.tuf.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() <= self.tuf.targets().map(|t| t.version()).unwrap_or(0) {
return Ok(false);
}
let (alg, value) = crypto::hash_preference(targets_description.hashes())?;
let version = if self.tuf.root().consistent_snapshot() {
MetadataVersion::Number(targets_description.version())
} else {
MetadataVersion::None
};
let targets_path = MetadataPath::from_role(&Role::Targets);
let targets_length = Some(targets_description.length());
let (raw_signed_targets, signed_targets) = self
.remote
.fetch_metadata(
&targets_path,
&version,
targets_length,
Some((alg, value.clone())),
)
.await?;
if self.tuf.update_targets(signed_targets)? {
self.store_metadata(&targets_path, &version, &raw_signed_targets)
.await;
Ok(true)
} else {
Ok(false)
}
}
/// Fetch a target from the remote repo and write it to the local repo.
pub async fn fetch_target<'a>(&'a mut self, target: &'a TargetPath) -> Result<()> {
let read = self._fetch_target(target).await?;
self.local.store_target(read, target).await
}
/// Fetch a target from the remote repo and write it to the provided writer.
///
/// 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_writer<'a, W>(
&'a mut self,
target: &'a TargetPath,
mut write: W,
) -> Result<()>
where
W: AsyncWrite + Send + Unpin,
{
let read = self._fetch_target(&target).await?;
copy(read, &mut write).await?;
Ok(())
}
/// Fetch a target description from the remote repo and return it.
pub async fn fetch_target_description<'a>(
&'a mut self,
target: &'a TargetPath,
) -> Result<TargetDescription> {
let virt = self.config.path_translator.real_to_virtual(target)?;
let snapshot = self
.tuf
.snapshot()
.ok_or_else(|| Error::MissingMetadata(Role::Snapshot))?
.clone();
let (_, target_description) = self
.lookup_target_description(false, 0, &virt, &snapshot, None)
.await;
target_description
}
// TODO this should check the local repo first
async fn _fetch_target<'a>(
&'a mut self,
target: &'a TargetPath,
) -> Result<impl AsyncRead + Send + Unpin> {
let target_description = self.fetch_target_description(target).await?;
// According to TUF section 5.5.2, when consistent snapshot is enabled, target files should
// be found at `$HASH.FILENAME.EXT`. Otherwise it is stored at `FILENAME.EXT`.
if self.tuf.root().consistent_snapshot() {
let (_, value) = crypto::hash_preference(target_description.hashes())?;
let target = target.with_hash_prefix(value)?;
self.remote.fetch_target(&target, &target_description).await
} else {
self.remote.fetch_target(target, &target_description).await
}
}
async fn lookup_target_description<'a>(
&'a mut self,
default_terminate: bool,
current_depth: u32,
target: &'a VirtualTargetPath,
snapshot: &'a SnapshotMetadata,
targets: Option<&'a TargetsMetadata>,
) -> (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 = match targets {
Some(t) => t.clone(),
None => match self.tuf.targets() {
Some(t) => t.clone(),
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() => continue,
None => return (true, Err(Error::NotFound)),
};
let (alg, value) = match crypto::hash_preference(role_meta.hashes()) {
Ok(h) => h,
Err(e) => return (delegation.terminating(), Err(e)),
};
let version = if self.tuf.root().consistent_snapshot() {
MetadataVersion::Hash(value.clone())
} else {
MetadataVersion::None
};
let role_length = Some(role_meta.length());
let raw_signed_meta = self
.local
.fetch_metadata(
delegation.role(),
&MetadataVersion::None,
role_length,
Some((alg, value.clone())),
)
.await;
let (raw_signed_meta, signed_meta) = match raw_signed_meta {
Ok(m) => m,
Err(_) => {
match self
.remote
.fetch_metadata(
delegation.role(),
&version,
role_length,
Some((alg, value.clone())),
)
.await
{
Ok(m) => m,
Err(ref e) if !delegation.terminating() => {
warn!("Failed to fetch metadata {:?}: {:?}", delegation.role(), e);
continue;
}
Err(e) => {
warn!("Failed to fetch metadata {:?}: {:?}", delegation.role(), e);
return (true, Err(e));
}
}
}
};
match self.tuf.update_delegation(delegation.role(), signed_meta) {
Ok(_) => {
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
.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.as_ref()),
));
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))
}
}
/// 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>,
hash_data: Option<(&'static HashAlgorithm, HashValue)>,
local: &'a Repository<L, D>,
remote: &'a Repository<R, D>,
) -> Result<(bool, RawSignedMetadata<D, M>, SignedMetadata<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, hash_data.clone())
.await
{
Ok((raw_meta, meta)) => Ok((false, raw_meta, meta)),
Err(Error::NotFound) => {
let (raw_meta, meta) = remote
.fetch_metadata(path, version, max_length, hash_data)
.await?;
Ok((true, raw_meta, 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, DefaultTranslator};
/// let config = Config::default();
/// assert_eq!(config.max_root_length(), &Some(1024 * 1024));
/// assert_eq!(config.max_timestamp_length(), &Some(32 * 1024));
/// assert_eq!(config.max_delegation_depth(), 8);
/// let _: &DefaultTranslator = config.path_translator();
/// ```
#[derive(Clone, Debug)]
pub struct Config<T>