Skip to content

Commit 240fb54

Browse files
author
Lukas Puehringer
committed
Use custom errors in serializer.json sub-package
Re-raise all errors that happen during de/serialization as custom De/SerializationError. Whilelist 'e', which is idiomatic for error, in api/pylintrc, and inline exempt broad-except, which are okay if re-raised. Signed-off-by: Lukas Puehringer <lukas.puehringer@nyu.edu>
1 parent 499f1c8 commit 240fb54

File tree

5 files changed

+50
-15
lines changed

5 files changed

+50
-15
lines changed

tests/test_api.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@
2828
Targets
2929
)
3030

31+
from tuf.api.serialization import (
32+
DeserializationError
33+
)
34+
3135
from tuf.api.serialization.json import (
3236
JSONSerializer,
3337
JSONDeserializer,
@@ -118,7 +122,7 @@ def test_generic_read(self):
118122
with open(bad_metadata_path, 'wb') as f:
119123
f.write(json.dumps(bad_metadata).encode('utf-8'))
120124

121-
with self.assertRaises(ValueError):
125+
with self.assertRaises(DeserializationError):
122126
Metadata.from_file(bad_metadata_path)
123127

124128
os.remove(bad_metadata_path)

tuf/api/metadata.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,8 @@ def from_file(
117117
118118
Raises:
119119
securesystemslib.exceptions.StorageError: The file cannot be read.
120-
securesystemslib.exceptions.Error, ValueError, KeyError: The
121-
metadata cannot be parsed.
120+
tuf.api.serialization.DeserializationError:
121+
The file cannot be deserialized.
122122
123123
Returns:
124124
A TUF Metadata object.
@@ -161,6 +161,8 @@ def to_file(self, filename: str, serializer: MetadataSerializer = None,
161161
a (local) FilesystemBackend is used.
162162
163163
Raises:
164+
tuf.api.serialization.SerializationError:
165+
The metadata object cannot be serialized.
164166
securesystemslib.exceptions.StorageError:
165167
The file cannot be written.
166168
@@ -191,7 +193,8 @@ def sign(self, key: JsonDict, append: bool = False,
191193
CanonicalJSONSerializer is used.
192194
193195
Raises:
194-
securesystemslib.exceptions.FormatError: Key argument is malformed.
196+
tuf.api.serialization.SerializationError:
197+
'signed' cannot be serialized.
195198
securesystemslib.exceptions.CryptoError, \
196199
securesystemslib.exceptions.UnsupportedAlgorithmError:
197200
Signing errors.
@@ -230,6 +233,8 @@ def verify(self, key: JsonDict,
230233
# TODO: Revise exception taxonomy
231234
tuf.exceptions.Error: None or multiple signatures found for key.
232235
securesystemslib.exceptions.FormatError: Key argument is malformed.
236+
tuf.api.serialization.SerializationError:
237+
'signed' cannot be serialized.
233238
securesystemslib.exceptions.CryptoError, \
234239
securesystemslib.exceptions.UnsupportedAlgorithmError:
235240
Signing errors.

tuf/api/pylintrc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
[MESSAGE_CONTROL]
22
disable=fixme
33

4+
[BASIC]
5+
good-names=e
6+
47
[FORMAT]
58
indent-string=" "
69
max-line-length=79

tuf/api/serialization/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@
1313
"""
1414
import abc
1515

16+
# TODO: Should these be in tuf.exceptions or inherit from tuf.exceptions.Error?
17+
class SerializationError(Exception):
18+
"""Error during serialization. """
19+
20+
class DeserializationError(Exception):
21+
"""Error during deserialization. """
22+
23+
1624
class MetadataDeserializer():
1725
"""Abstract base class for deserialization of Metadata objects. """
1826
__metaclass__ = abc.ABCMeta

tuf/api/serialization/json.py

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
88
"""
99
import json
10+
import six
1011

1112
from securesystemslib.formats import encode_canonical
1213

@@ -16,16 +17,22 @@
1617
from tuf.api.metadata import Metadata, Signed
1718
from tuf.api.serialization import (MetadataSerializer,
1819
MetadataDeserializer,
19-
SignedSerializer)
20+
SignedSerializer,
21+
SerializationError,
22+
DeserializationError)
2023

2124

2225
class JSONDeserializer(MetadataDeserializer):
2326
"""Provides JSON-to-Metadata deserialize method. """
2427

2528
def deserialize(self, raw_data: bytes) -> Metadata:
2629
"""Deserialize utf-8 encoded JSON bytes into Metadata object. """
27-
_dict = json.loads(raw_data.decode("utf-8"))
28-
return Metadata.from_dict(_dict)
30+
try:
31+
_dict = json.loads(raw_data.decode("utf-8"))
32+
return Metadata.from_dict(_dict)
33+
34+
except Exception as e: # pylint: disable=broad-except
35+
six.raise_from(DeserializationError, e)
2936

3037

3138
class JSONSerializer(MetadataSerializer):
@@ -41,18 +48,26 @@ def __init__(self, compact: bool = False) -> None:
4148

4249
def serialize(self, metadata_obj: Metadata) -> bytes:
4350
"""Serialize Metadata object into utf-8 encoded JSON bytes. """
44-
indent = (None if self.compact else 1)
45-
separators=((',', ':') if self.compact else (',', ': '))
46-
return json.dumps(metadata_obj.to_dict(),
47-
indent=indent,
48-
separators=separators,
49-
sort_keys=True).encode("utf-8")
51+
try:
52+
indent = (None if self.compact else 1)
53+
separators=((',', ':') if self.compact else (',', ': '))
54+
return json.dumps(metadata_obj.to_dict(),
55+
indent=indent,
56+
separators=separators,
57+
sort_keys=True).encode("utf-8")
58+
59+
except Exception as e: # pylint: disable=broad-except
60+
six.raise_from(SerializationError, e)
5061

5162

5263
class CanonicalJSONSerializer(SignedSerializer):
5364
"""A Signed-to-Canonical JSON 'serialize' method. """
5465

5566
def serialize(self, signed_obj: Signed) -> bytes:
5667
"""Serialize Signed object into utf-8 encoded Canonical JSON bytes. """
57-
signed_dict = signed_obj.to_dict()
58-
return encode_canonical(signed_dict).encode("utf-8")
68+
try:
69+
signed_dict = signed_obj.to_dict()
70+
return encode_canonical(signed_dict).encode("utf-8")
71+
72+
except Exception as e: # pylint: disable=broad-except
73+
six.raise_from(SerializationError, e)

0 commit comments

Comments
 (0)