Skip to content

Commit bc69a70

Browse files
authored
Merge pull request #843 from L77H/type-formats-improve-docstr
type annotations for formats.py & tried to improve docstring
2 parents 5cc4b30 + 2163e8d commit bc69a70

File tree

2 files changed

+29
-13
lines changed

2 files changed

+29
-13
lines changed

securesystemslib/formats.py

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,18 @@
2020
2121
"""
2222

23+
from typing import Callable, Optional, Union
24+
2325
from securesystemslib import exceptions
2426

2527

26-
def _canonical_string_encoder(string):
28+
def _canonical_string_encoder(string: str) -> str:
2729
"""
2830
<Purpose>
29-
Encode 'string' to canonical string format.
31+
Encode 'string' to canonical string format. By using the escape sequence ('\')
32+
which is mandatory to use for quote and backslash.
33+
backslash: \\ translates to \\\\
34+
quote: \" translates to \\".
3035
3136
<Arguments>
3237
string:
@@ -41,13 +46,14 @@ def _canonical_string_encoder(string):
4146
<Returns>
4247
A string with the canonical-encoded 'string' embedded.
4348
"""
44-
4549
string = '"{}"'.format(string.replace("\\", "\\\\").replace('"', '\\"'))
4650

4751
return string
4852

4953

50-
def _encode_canonical(object, output_function):
54+
def _encode_canonical(
55+
object: Union[bool, None, str, int, tuple, list, dict], output_function: Callable
56+
) -> None:
5157
# Helper for encode_canonical. Older versions of json.encoder don't
5258
# even let us replace the separators.
5359

@@ -88,11 +94,15 @@ def _encode_canonical(object, output_function):
8894

8995

9096
def encode_canonical(
91-
object,
92-
output_function=None,
93-
):
97+
object: Union[bool, None, str, int, tuple, list, dict],
98+
output_function: Optional[Callable] = None,
99+
) -> Union[str, None]:
94100
"""
95101
<Purpose>
102+
Encoding an object so that it is always has the same string format
103+
independent of the original format. This allows to compute always the same hash
104+
or signature for that object.
105+
96106
Encode 'object' in canonical JSON form, as specified at
97107
http://wiki.laptop.org/go/Canonical_JSON . It's a restricted
98108
dialect of JSON in which keys are always lexically sorted,
@@ -140,7 +150,7 @@ def encode_canonical(
140150
A string representing the 'object' encoded in canonical JSON form.
141151
"""
142152

143-
result = None
153+
result: Union[None, list] = None
144154
# If 'output_function' is unset, treat it as
145155
# appending to a list.
146156
if output_function is None:
@@ -151,11 +161,12 @@ def encode_canonical(
151161
_encode_canonical(object, output_function)
152162

153163
except (TypeError, exceptions.FormatError) as e:
154-
message = "Could not encode " + repr(object) + ": " + str(e)
164+
message: str = "Could not encode " + repr(object) + ": " + str(e)
155165
raise exceptions.FormatError(message)
156166

157167
# Return the encoded 'object' as a string.
158168
# Note: Implies 'output_function' is None,
159169
# otherwise results are sent to 'output_function'.
160170
if result is not None:
161171
return "".join(result)
172+
return None

securesystemslib/signer/_utils.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
11
"""Signer utils for internal use."""
22

3-
from typing import Any, Dict
3+
from typing import Any, Dict, Union
44

5+
from securesystemslib.exceptions import FormatError
56
from securesystemslib.formats import encode_canonical
67
from securesystemslib.hash import digest
78

89

910
def compute_default_keyid(keytype: str, scheme, keyval: Dict[str, Any]) -> str:
1011
"""Return sha256 hexdigest of the canonical json of the key."""
11-
data = encode_canonical(
12+
data: Union[str, None] = encode_canonical(
1213
{
1314
"keytype": keytype,
1415
"scheme": scheme,
1516
"keyval": keyval,
1617
}
17-
).encode("utf-8")
18+
)
19+
if isinstance(data, str):
20+
byte_data: bytes = data.encode("utf-8")
21+
else:
22+
raise FormatError("Failed to encode data into canonical json")
1823
hasher = digest("sha256")
19-
hasher.update(data)
24+
hasher.update(byte_data)
2025
return hasher.hexdigest()

0 commit comments

Comments
 (0)