-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathmetadata.py
1122 lines (930 loc) · 39.5 KB
/
metadata.py
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
# Copyright New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""TUF role metadata model.
This module provides container classes for TUF role metadata, including methods
to read and write from and to file, perform TUF-compliant metadata updates, and
create and verify signatures.
The metadata model supports any custom serialization format, defaulting to JSON
as wireline format and Canonical JSON for reproducible signature creation and
verification.
Custom serializers must implement the abstract serialization interface defined
in 'tuf.api.serialization', and may use the [to|from]_dict convenience methods
available in the class model.
"""
import abc
import io
import tempfile
from collections import OrderedDict
from datetime import datetime, timedelta
from typing import (
Any,
BinaryIO,
ClassVar,
Dict,
List,
Mapping,
Optional,
Tuple,
Type,
Union,
)
from securesystemslib import exceptions as sslib_exceptions
from securesystemslib import hash as sslib_hash
from securesystemslib import keys as sslib_keys
from securesystemslib.signer import Signature, Signer
from securesystemslib.storage import FilesystemBackend, StorageBackendInterface
from securesystemslib.util import persist_temp_file
from tuf import exceptions
from tuf.api.serialization import (
MetadataDeserializer,
MetadataSerializer,
SignedSerializer,
)
# pylint: disable=too-many-lines
# We aim to support SPECIFICATION_VERSION and require the input metadata
# files to have the same major version (the first number) as ours.
SPECIFICATION_VERSION = ["1", "0", "19"]
class Metadata:
"""A container for signed TUF metadata.
Provides methods to convert to and from dictionary, read and write to and
from file and to create and verify metadata signatures.
Attributes:
signed: A subclass of Signed, which has the actual metadata payload,
i.e. one of Targets, Snapshot, Timestamp or Root.
signatures: An ordered dictionary of keyids to Signature objects, each
signing the canonical serialized representation of 'signed'.
"""
def __init__(
self, signed: "Signed", signatures: "OrderedDict[str, Signature]"
):
self.signed = signed
self.signatures = signatures
@classmethod
def from_dict(cls, metadata: Dict[str, Any]) -> "Metadata":
"""Creates Metadata object from its dict representation.
Arguments:
metadata: TUF metadata in dict representation.
Raises:
KeyError: The metadata dict format is invalid.
ValueError: The metadata has an unrecognized signed._type field.
Side Effect:
Destroys the metadata dict passed by reference.
Returns:
A TUF Metadata object.
"""
# Dispatch to contained metadata class on metadata _type field.
_type = metadata["signed"]["_type"]
if _type == "targets":
inner_cls: Type[Signed] = Targets
elif _type == "snapshot":
inner_cls = Snapshot
elif _type == "timestamp":
inner_cls = Timestamp
elif _type == "root":
inner_cls = Root
else:
raise ValueError(f'unrecognized metadata type "{_type}"')
# Make sure signatures are unique
signatures: "OrderedDict[str, Signature]" = OrderedDict()
for sig_dict in metadata.pop("signatures"):
sig = Signature.from_dict(sig_dict)
if sig.keyid in signatures:
raise ValueError(
f"Multiple signatures found for keyid {sig.keyid}"
)
signatures[sig.keyid] = sig
return cls(
signed=inner_cls.from_dict(metadata.pop("signed")),
signatures=signatures,
)
@classmethod
def from_file(
cls,
filename: str,
deserializer: Optional[MetadataDeserializer] = None,
storage_backend: Optional[StorageBackendInterface] = None,
) -> "Metadata":
"""Loads TUF metadata from file storage.
Arguments:
filename: The path to read the file from.
deserializer: A MetadataDeserializer subclass instance that
implements the desired wireline format deserialization. Per
default a JSONDeserializer is used.
storage_backend: An object that implements
securesystemslib.storage.StorageBackendInterface. Per default
a (local) FilesystemBackend is used.
Raises:
securesystemslib.exceptions.StorageError: The file cannot be read.
tuf.api.serialization.DeserializationError:
The file cannot be deserialized.
Returns:
A TUF Metadata object.
"""
if storage_backend is None:
storage_backend = FilesystemBackend()
with storage_backend.get(filename) as file_obj:
return cls.from_bytes(file_obj.read(), deserializer)
@staticmethod
def from_bytes(
data: bytes,
deserializer: Optional[MetadataDeserializer] = None,
) -> "Metadata":
"""Loads TUF metadata from raw data.
Arguments:
data: metadata content as bytes.
deserializer: Optional; A MetadataDeserializer instance that
implements deserialization. Default is JSONDeserializer.
Raises:
tuf.api.serialization.DeserializationError:
The file cannot be deserialized.
Returns:
A TUF Metadata object.
"""
if deserializer is None:
# Use local scope import to avoid circular import errors
# pylint: disable=import-outside-toplevel
from tuf.api.serialization.json import JSONDeserializer
deserializer = JSONDeserializer()
return deserializer.deserialize(data)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dict representation of self."""
signatures = [sig.to_dict() for sig in self.signatures.values()]
return {"signatures": signatures, "signed": self.signed.to_dict()}
def to_file(
self,
filename: str,
serializer: Optional[MetadataSerializer] = None,
storage_backend: Optional[StorageBackendInterface] = None,
) -> None:
"""Writes TUF metadata to file storage.
Arguments:
filename: The path to write the file to.
serializer: A MetadataSerializer instance that implements the
desired serialization format. Default is JSONSerializer.
storage_backend: A StorageBackendInterface implementation. Default
is FilesystemBackend (i.e. a local file).
Raises:
tuf.api.serialization.SerializationError:
The metadata object cannot be serialized.
securesystemslib.exceptions.StorageError:
The file cannot be written.
"""
if serializer is None:
# Use local scope import to avoid circular import errors
# pylint: disable=import-outside-toplevel
from tuf.api.serialization.json import JSONSerializer
serializer = JSONSerializer(compact=True)
with tempfile.TemporaryFile() as temp_file:
temp_file.write(serializer.serialize(self))
persist_temp_file(temp_file, filename, storage_backend)
# Signatures.
def sign(
self,
signer: Signer,
append: bool = False,
signed_serializer: Optional[SignedSerializer] = None,
) -> Signature:
"""Creates signature over 'signed' and assigns it to 'signatures'.
Arguments:
signer: A securesystemslib.signer.Signer implementation.
append: A boolean indicating if the signature should be appended to
the list of signatures or replace any existing signatures. The
default behavior is to replace signatures.
signed_serializer: A SignedSerializer that implements the desired
serialization format. Default is CanonicalJSONSerializer.
Raises:
tuf.api.serialization.SerializationError:
'signed' cannot be serialized.
securesystemslib.exceptions.CryptoError, \
securesystemslib.exceptions.UnsupportedAlgorithmError:
Signing errors.
Returns:
Securesystemslib Signature object that was added into signatures.
"""
if signed_serializer is None:
# Use local scope import to avoid circular import errors
# pylint: disable=import-outside-toplevel
from tuf.api.serialization.json import CanonicalJSONSerializer
signed_serializer = CanonicalJSONSerializer()
signature = signer.sign(signed_serializer.serialize(self.signed))
if not append:
self.signatures.clear()
self.signatures[signature.keyid] = signature
return signature
class Signed(metaclass=abc.ABCMeta):
"""A base class for the signed part of TUF metadata.
Objects with base class Signed are usually included in a Metadata object
on the signed attribute. This class provides attributes and methods that
are common for all TUF metadata types (roles).
Attributes:
_type: The metadata type string. Also available without underscore.
version: The metadata version number.
spec_version: The TUF specification version number (semver) the
metadata format adheres to.
expires: The metadata expiration datetime object.
unrecognized_fields: Dictionary of all unrecognized fields.
"""
# Signed implementations are expected to override this
_signed_type: ClassVar[str] = "signed"
# _type and type are identical: 1st replicates file format, 2nd passes lint
@property
def _type(self) -> str:
return self._signed_type
@property
def type(self) -> str:
return self._signed_type
# NOTE: Signed is a stupid name, because this might not be signed yet, but
# we keep it to match spec terminology (I often refer to this as "payload",
# or "inner metadata")
def __init__(
self,
version: int,
spec_version: str,
expires: datetime,
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
spec_list = spec_version.split(".")
if (
len(spec_list) != 3
or not all(el.isdigit() for el in spec_list)
or spec_list[0] != SPECIFICATION_VERSION[0]
):
raise ValueError(
f"Unsupported spec_version, got {spec_list}, "
f"supported {'.'.join(SPECIFICATION_VERSION)}"
)
self.spec_version = spec_version
self.expires = expires
if version <= 0:
raise ValueError(f"version must be > 0, got {version}")
self.version = version
self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {}
@abc.abstractmethod
def to_dict(self) -> Dict[str, Any]:
"""Serialization helper that returns dict representation of self"""
raise NotImplementedError
@classmethod
@abc.abstractmethod
def from_dict(cls, signed_dict: Dict[str, Any]) -> "Signed":
"""Deserialization helper, creates object from dict representation"""
raise NotImplementedError
@classmethod
def _common_fields_from_dict(
cls, signed_dict: Dict[str, Any]
) -> Tuple[int, str, datetime]:
"""Returns common fields of 'Signed' instances from the passed dict
representation, and returns an ordered list to be passed as leading
positional arguments to a subclass constructor.
See '{Root, Timestamp, Snapshot, Targets}.from_dict' methods for usage.
"""
_type = signed_dict.pop("_type")
if _type != cls._signed_type:
raise ValueError(f"Expected type {cls._signed_type}, got {_type}")
version = signed_dict.pop("version")
spec_version = signed_dict.pop("spec_version")
expires_str = signed_dict.pop("expires")
# Convert 'expires' TUF metadata string to a datetime object, which is
# what the constructor expects and what we store. The inverse operation
# is implemented in '_common_fields_to_dict'.
expires = datetime.strptime(expires_str, "%Y-%m-%dT%H:%M:%SZ")
return version, spec_version, expires
def _common_fields_to_dict(self) -> Dict[str, Any]:
"""Returns dict representation of common fields of 'Signed' instances.
See '{Root, Timestamp, Snapshot, Targets}.to_dict' methods for usage.
"""
return {
"_type": self._type,
"version": self.version,
"spec_version": self.spec_version,
"expires": self.expires.isoformat() + "Z",
**self.unrecognized_fields,
}
def is_expired(self, reference_time: Optional[datetime] = None) -> bool:
"""Checks metadata expiration against a reference time.
Args:
reference_time: Optional; The time to check expiration date against.
A naive datetime in UTC expected.
If not provided, checks against the current UTC date and time.
Returns:
True if expiration time is less than the reference time.
"""
if reference_time is None:
reference_time = datetime.utcnow()
return reference_time >= self.expires
# Modification.
def bump_expiration(self, delta: timedelta = timedelta(days=1)) -> None:
"""Increments the expires attribute by the passed timedelta."""
self.expires += delta
def bump_version(self) -> None:
"""Increments the metadata version number by 1."""
self.version += 1
class Key:
"""A container class representing the public portion of a Key.
Please note that "Key" instances are not semanticly validated during
initialization: this only happens at signature verification time.
Attributes:
keyid: An identifier string that must uniquely identify a key within
the metadata it is used in. This implementation does not verify
that keyid is the hash of a specific representation of the key.
keytype: A string denoting a public key signature system,
such as "rsa", "ed25519", "ecdsa" and "ecdsa-sha2-nistp256".
scheme: A string denoting a corresponding signature scheme. For example:
"rsassa-pss-sha256", "ed25519", and "ecdsa-sha2-nistp256".
keyval: A dictionary containing the public portion of the key.
unrecognized_fields: Dictionary of all unrecognized fields.
"""
def __init__(
self,
keyid: str,
keytype: str,
scheme: str,
keyval: Dict[str, str],
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
if not all(
isinstance(at, str) for at in [keyid, keytype, scheme]
) or not isinstance(keyval, Dict):
raise TypeError("Unexpected Key attributes types!")
self.keyid = keyid
self.keytype = keytype
self.scheme = scheme
self.keyval = keyval
self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {}
@classmethod
def from_dict(cls, keyid: str, key_dict: Dict[str, Any]) -> "Key":
"""Creates Key object from its dict representation."""
keytype = key_dict.pop("keytype")
scheme = key_dict.pop("scheme")
keyval = key_dict.pop("keyval")
# All fields left in the key_dict are unrecognized.
return cls(keyid, keytype, scheme, keyval, key_dict)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dictionary representation of self."""
return {
"keytype": self.keytype,
"scheme": self.scheme,
"keyval": self.keyval,
**self.unrecognized_fields,
}
def to_securesystemslib_key(self) -> Dict[str, Any]:
"""Returns a Securesystemslib compatible representation of self."""
return {
"keyid": self.keyid,
"keytype": self.keytype,
"scheme": self.scheme,
"keyval": self.keyval,
}
def verify_signature(
self,
metadata: Metadata,
signed_serializer: Optional[SignedSerializer] = None,
) -> None:
"""Verifies that the 'metadata.signatures' contains a signature made
with this key, correctly signing 'metadata.signed'.
Arguments:
metadata: Metadata to verify
signed_serializer: Optional; SignedSerializer to serialize
'metadata.signed' with. Default is CanonicalJSONSerializer.
Raises:
UnsignedMetadataError: The signature could not be verified for a
variety of possible reasons: see error message.
"""
try:
signature = metadata.signatures[self.keyid]
except KeyError:
raise exceptions.UnsignedMetadataError(
f"no signature for key {self.keyid} found in metadata",
metadata.signed,
) from None
if signed_serializer is None:
# pylint: disable=import-outside-toplevel
from tuf.api.serialization.json import CanonicalJSONSerializer
signed_serializer = CanonicalJSONSerializer()
try:
if not sslib_keys.verify_signature(
self.to_securesystemslib_key(),
signature.to_dict(),
signed_serializer.serialize(metadata.signed),
):
raise exceptions.UnsignedMetadataError(
f"Failed to verify {self.keyid} signature",
metadata.signed,
)
except (
sslib_exceptions.CryptoError,
sslib_exceptions.FormatError,
sslib_exceptions.UnsupportedAlgorithmError,
) as e:
raise exceptions.UnsignedMetadataError(
f"Failed to verify {self.keyid} signature",
metadata.signed,
) from e
class Role:
"""Container that defines which keys are required to sign roles metadata.
Role defines how many keys are required to successfully sign the roles
metadata, and which keys are accepted.
Attributes:
keyids: A set of strings representing signing keys for this role.
threshold: Number of keys required to sign this role's metadata.
unrecognized_fields: Dictionary of all unrecognized fields.
"""
def __init__(
self,
keyids: List[str],
threshold: int,
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
keyids_set = set(keyids)
if len(keyids_set) != len(keyids):
raise ValueError(
f"keyids should be a list of unique strings,"
f" instead got {keyids}"
)
if threshold < 1:
raise ValueError("threshold should be at least 1!")
self.keyids = keyids_set
self.threshold = threshold
self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {}
@classmethod
def from_dict(cls, role_dict: Dict[str, Any]) -> "Role":
"""Creates Role object from its dict representation."""
keyids = role_dict.pop("keyids")
threshold = role_dict.pop("threshold")
# All fields left in the role_dict are unrecognized.
return cls(keyids, threshold, role_dict)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dictionary representation of self."""
return {
"keyids": list(self.keyids),
"threshold": self.threshold,
**self.unrecognized_fields,
}
class Root(Signed):
"""A container for the signed part of root metadata.
Attributes:
consistent_snapshot: An optional boolean indicating whether the
repository supports consistent snapshots.
keys: Dictionary of keyids to Keys. Defines the keys used in 'roles'.
roles: Dictionary of role names to Roles. Defines which keys are
required to sign the metadata for a specific role.
"""
_signed_type = "root"
# TODO: determine an appropriate value for max-args
# pylint: disable=too-many-arguments
def __init__(
self,
version: int,
spec_version: str,
expires: datetime,
keys: Dict[str, Key],
roles: Dict[str, Role],
consistent_snapshot: Optional[bool] = None,
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
super().__init__(version, spec_version, expires, unrecognized_fields)
self.consistent_snapshot = consistent_snapshot
self.keys = keys
self.roles = roles
@classmethod
def from_dict(cls, signed_dict: Dict[str, Any]) -> "Root":
"""Creates Root object from its dict representation."""
common_args = cls._common_fields_from_dict(signed_dict)
consistent_snapshot = signed_dict.pop("consistent_snapshot", None)
keys = signed_dict.pop("keys")
roles = signed_dict.pop("roles")
for keyid, key_dict in keys.items():
keys[keyid] = Key.from_dict(keyid, key_dict)
for role_name, role_dict in roles.items():
roles[role_name] = Role.from_dict(role_dict)
# All fields left in the signed_dict are unrecognized.
return cls(*common_args, keys, roles, consistent_snapshot, signed_dict)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dict representation of self."""
root_dict = self._common_fields_to_dict()
keys = {keyid: key.to_dict() for (keyid, key) in self.keys.items()}
roles = {}
for role_name, role in self.roles.items():
roles[role_name] = role.to_dict()
if self.consistent_snapshot is not None:
root_dict["consistent_snapshot"] = self.consistent_snapshot
root_dict.update(
{
"keys": keys,
"roles": roles,
}
)
return root_dict
# Update key for a role.
def add_key(self, role: str, key: Key) -> None:
"""Adds new signing key for delegated role 'role'."""
self.roles[role].keyids.add(key.keyid)
self.keys[key.keyid] = key
def remove_key(self, role: str, keyid: str) -> None:
"""Removes key from 'role' and updates the key store.
Raises:
KeyError: If 'role' does not include the key
"""
self.roles[role].keyids.remove(keyid)
for keyinfo in self.roles.values():
if keyid in keyinfo.keyids:
return
del self.keys[keyid]
class BaseFile:
"""A base class of MetaFile and TargetFile.
Encapsulates common static methods for length and hash verification.
"""
@staticmethod
def _verify_hashes(
data: Union[bytes, BinaryIO], expected_hashes: Dict[str, str]
) -> None:
"""Verifies that the hash of 'data' matches 'expected_hashes'"""
is_bytes = isinstance(data, bytes)
for algo, exp_hash in expected_hashes.items():
try:
if is_bytes:
digest_object = sslib_hash.digest(algo)
digest_object.update(data)
else:
# if data is not bytes, assume it is a file object
digest_object = sslib_hash.digest_fileobject(data, algo)
except (
sslib_exceptions.UnsupportedAlgorithmError,
sslib_exceptions.FormatError,
) as e:
raise exceptions.LengthOrHashMismatchError(
f"Unsupported algorithm '{algo}'"
) from e
observed_hash = digest_object.hexdigest()
if observed_hash != exp_hash:
raise exceptions.LengthOrHashMismatchError(
f"Observed hash {observed_hash} does not match"
f"expected hash {exp_hash}"
)
@staticmethod
def _verify_length(
data: Union[bytes, BinaryIO], expected_length: int
) -> None:
"""Verifies that the length of 'data' matches 'expected_length'"""
if isinstance(data, bytes):
observed_length = len(data)
else:
# if data is not bytes, assume it is a file object
data.seek(0, io.SEEK_END)
observed_length = data.tell()
if observed_length != expected_length:
raise exceptions.LengthOrHashMismatchError(
f"Observed length {observed_length} does not match"
f"expected length {expected_length}"
)
@staticmethod
def _validate_hashes(hashes: Dict[str, str]) -> None:
if not hashes:
raise ValueError("Hashes must be a non empty dictionary")
for key, value in hashes.items():
if not (isinstance(key, str) and isinstance(value, str)):
raise TypeError("Hashes items must be strings")
@staticmethod
def _validate_length(length: int) -> None:
if length <= 0:
raise ValueError(f"Length must be > 0, got {length}")
class MetaFile(BaseFile):
"""A container with information about a particular metadata file.
Attributes:
version: An integer indicating the version of the metadata file.
length: An optional integer indicating the length of the metadata file.
hashes: An optional dictionary of hash algorithm names to hash values.
unrecognized_fields: Dictionary of all unrecognized fields.
"""
def __init__(
self,
version: int,
length: Optional[int] = None,
hashes: Optional[Dict[str, str]] = None,
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
if version <= 0:
raise ValueError(f"Metafile version must be > 0, got {version}")
if length is not None:
self._validate_length(length)
if hashes is not None:
self._validate_hashes(hashes)
self.version = version
self.length = length
self.hashes = hashes
self.unrecognized_fields: Mapping[str, Any] = unrecognized_fields or {}
@classmethod
def from_dict(cls, meta_dict: Dict[str, Any]) -> "MetaFile":
"""Creates MetaFile object from its dict representation."""
version = meta_dict.pop("version")
length = meta_dict.pop("length", None)
hashes = meta_dict.pop("hashes", None)
# All fields left in the meta_dict are unrecognized.
return cls(version, length, hashes, meta_dict)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dictionary representation of self."""
res_dict: Dict[str, Any] = {
"version": self.version,
**self.unrecognized_fields,
}
if self.length is not None:
res_dict["length"] = self.length
if self.hashes is not None:
res_dict["hashes"] = self.hashes
return res_dict
def verify_length_and_hashes(self, data: Union[bytes, BinaryIO]) -> None:
"""Verifies that the length and hashes of "data" match expected values.
Args:
data: File object or its content in bytes.
Raises:
LengthOrHashMismatchError: Calculated length or hashes do not
match expected values or hash algorithm is not supported.
"""
if self.length is not None:
self._verify_length(data, self.length)
if self.hashes is not None:
self._verify_hashes(data, self.hashes)
class Timestamp(Signed):
"""A container for the signed part of timestamp metadata.
Timestamp contains information about the snapshot Metadata file.
Attributes:
meta: A dictionary of filenames to MetaFiles. The only valid key value
is the snapshot filename, as defined by the specification.
"""
_signed_type = "timestamp"
def __init__(
self,
version: int,
spec_version: str,
expires: datetime,
meta: Dict[str, MetaFile],
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
super().__init__(version, spec_version, expires, unrecognized_fields)
self.meta = meta
@classmethod
def from_dict(cls, signed_dict: Dict[str, Any]) -> "Timestamp":
"""Creates Timestamp object from its dict representation."""
common_args = cls._common_fields_from_dict(signed_dict)
meta_dict = signed_dict.pop("meta")
meta = {"snapshot.json": MetaFile.from_dict(meta_dict["snapshot.json"])}
# All fields left in the timestamp_dict are unrecognized.
return cls(*common_args, meta, signed_dict)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dict representation of self."""
res_dict = self._common_fields_to_dict()
res_dict["meta"] = {
"snapshot.json": self.meta["snapshot.json"].to_dict()
}
return res_dict
# Modification.
def update(self, snapshot_meta: MetaFile) -> None:
"""Assigns passed info about snapshot metadata to meta dict."""
self.meta["snapshot.json"] = snapshot_meta
class Snapshot(Signed):
"""A container for the signed part of snapshot metadata.
Snapshot contains information about all target Metadata files.
Attributes:
meta: A dictionary of target metadata filenames to MetaFile objects.
"""
_signed_type = "snapshot"
def __init__(
self,
version: int,
spec_version: str,
expires: datetime,
meta: Dict[str, MetaFile],
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
super().__init__(version, spec_version, expires, unrecognized_fields)
self.meta = meta
@classmethod
def from_dict(cls, signed_dict: Dict[str, Any]) -> "Snapshot":
"""Creates Snapshot object from its dict representation."""
common_args = cls._common_fields_from_dict(signed_dict)
meta_dicts = signed_dict.pop("meta")
meta = {}
for meta_path, meta_dict in meta_dicts.items():
meta[meta_path] = MetaFile.from_dict(meta_dict)
# All fields left in the snapshot_dict are unrecognized.
return cls(*common_args, meta, signed_dict)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dict representation of self."""
snapshot_dict = self._common_fields_to_dict()
meta_dict = {}
for meta_path, meta_info in self.meta.items():
meta_dict[meta_path] = meta_info.to_dict()
snapshot_dict["meta"] = meta_dict
return snapshot_dict
# Modification.
def update(self, rolename: str, role_info: MetaFile) -> None:
"""Assigns passed (delegated) targets role info to meta dict."""
metadata_fn = f"{rolename}.json"
self.meta[metadata_fn] = role_info
class DelegatedRole(Role):
"""A container with information about a delegated role.
A delegation can happen in three ways:
- paths is None and path_hash_prefixes is None: delegates all targets
- paths is set: delegates targets matching any path pattern in paths
- path_hash_prefixes is set: delegates targets whose target path hash
starts with any of the prefixes in path_hash_prefixes
paths and path_hash_prefixes are mutually exclusive: both cannot be set.
Attributes:
name: A string giving the name of the delegated role.
terminating: A boolean indicating whether subsequent delegations
should be considered during a target lookup.
paths: An optional list of path pattern strings. See note above.
path_hash_prefixes: An optional list of hash prefixes. See note above.
unrecognized_fields: Dictionary of all unrecognized fields.
"""
def __init__(
self,
name: str,
keyids: List[str],
threshold: int,
terminating: bool,
paths: Optional[List[str]] = None,
path_hash_prefixes: Optional[List[str]] = None,
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
super().__init__(keyids, threshold, unrecognized_fields)
self.name = name
self.terminating = terminating
if paths is not None and path_hash_prefixes is not None:
raise ValueError(
"Only one of the attributes 'paths' and"
"'path_hash_prefixes' can be set!"
)
self.paths = paths
self.path_hash_prefixes = path_hash_prefixes
@classmethod
def from_dict(cls, role_dict: Dict[str, Any]) -> "DelegatedRole":
"""Creates DelegatedRole object from its dict representation."""
name = role_dict.pop("name")
keyids = role_dict.pop("keyids")
threshold = role_dict.pop("threshold")
terminating = role_dict.pop("terminating")
paths = role_dict.pop("paths", None)
path_hash_prefixes = role_dict.pop("path_hash_prefixes", None)
# All fields left in the role_dict are unrecognized.
return cls(
name,
keyids,
threshold,
terminating,
paths,
path_hash_prefixes,
role_dict,
)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dict representation of self."""
base_role_dict = super().to_dict()
res_dict = {
"name": self.name,
"terminating": self.terminating,
**base_role_dict,
}
if self.paths is not None:
res_dict["paths"] = self.paths
elif self.path_hash_prefixes is not None:
res_dict["path_hash_prefixes"] = self.path_hash_prefixes
return res_dict
class Delegations:
"""A container object storing information about all delegations.
Attributes:
keys: Dictionary of keyids to Keys. Defines the keys used in 'roles'.
roles: List of DelegatedRoles that define which keys are required to
sign the metadata for a specific role. The roles order also
defines the order that role delegations are considered in.
unrecognized_fields: Dictionary of all unrecognized fields.
"""
def __init__(
self,
keys: Mapping[str, Key],
roles: List[DelegatedRole],
unrecognized_fields: Optional[Mapping[str, Any]] = None,
) -> None:
self.keys = keys
self.roles = roles
self.unrecognized_fields = unrecognized_fields or {}
@classmethod
def from_dict(cls, delegations_dict: Dict[str, Any]) -> "Delegations":
"""Creates Delegations object from its dict representation."""
keys = delegations_dict.pop("keys")
keys_res = {}
for keyid, key_dict in keys.items():
keys_res[keyid] = Key.from_dict(keyid, key_dict)
roles = delegations_dict.pop("roles")
roles_res = []
for role_dict in roles:
new_role = DelegatedRole.from_dict(role_dict)
roles_res.append(new_role)
# All fields left in the delegations_dict are unrecognized.
return cls(keys_res, roles_res, delegations_dict)
def to_dict(self) -> Dict[str, Any]:
"""Returns the dict representation of self."""
keys = {keyid: key.to_dict() for keyid, key in self.keys.items()}
roles = [role_obj.to_dict() for role_obj in self.roles]
return {
"keys": keys,
"roles": roles,
**self.unrecognized_fields,