Skip to content

Commit f8d3437

Browse files
A decent implementation of Comparable.
I don't think we need anything more complicated like the solutions here: python/typing#59 There are some questions about the correctness of other operators like <= and >= that you now get for free with functools.total_ordering, due to the unexpected interactions with the __eq__ you get for free from dataclasses.dataclass, but we can punt them to the future. Signed-off-by: Trishank Karthik Kuppusamy <[email protected]>
1 parent 081e581 commit f8d3437

4 files changed

Lines changed: 59 additions & 43 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,4 @@ source = ["tuf_on_a_plane"]
4444

4545
[tool.coverage.report]
4646
show_missing = true
47-
fail_under = 80
47+
fail_under = 78

‎src/tuf_on_a_plane/models/common.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,15 @@ def strptime(cls, date_string: str, format: str) -> "DateTime":
2727

2828

2929
@total_ordering
30-
class Natural:
30+
class Comparable:
31+
def __eq__(self, other: Any) -> bool:
32+
raise NotImplementedError
33+
34+
def __lt__(self, other: Any) -> bool:
35+
raise NotImplementedError
36+
37+
38+
class Natural(Comparable):
3139
def __init__(self, value: Any):
3240
self.value = value
3341

‎src/tuf_on_a_plane/models/metadata.py‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from securesystemslib.rsa_keys import verify_rsa_signature
88

99
from .common import (
10+
Comparable,
1011
DateTime,
1112
Filepath,
1213
Hashes,
@@ -26,19 +27,23 @@
2627

2728

2829
@dataclass
29-
class Signed:
30+
class Signed(Comparable):
31+
# __eq__ and __str__ autogenerated by dataclass.
3032
expires: DateTime
3133
spec_version: SpecVersion
3234
version: Version
3335

36+
def __lt__(self, other: Any) -> bool:
37+
if not isinstance(other, Signed):
38+
raise NotImplementedError
39+
return self.version < other.version
40+
41+
# NOTE: Overrides __eq__ and __lt__.
3442
def __gt__(self, other: Any) -> bool:
3543
if not isinstance(other, Signed):
3644
raise NotImplementedError
3745
return self.version > other.version
3846

39-
def __str__(self):
40-
return f"{self.__class__.__name__}({self.version})"
41-
4247

4348
@dataclass
4449
class Metadata:
@@ -149,19 +154,23 @@ class Root(Signed):
149154

150155

151156
@dataclass
152-
class TimeSnap:
157+
class TimeSnap(Comparable):
158+
# __eq__ and __str__ autogenerated by dataclass.
153159
version: Version
154160
hashes: Optional[Hashes] = None
155161
length: Optional[Length] = None
156162

163+
def __lt__(self, other: Any) -> bool:
164+
if not isinstance(other, TimeSnap):
165+
raise NotImplementedError
166+
return self.version < other.version
167+
168+
# NOTE: Overrides __eq__ and __lt__.
157169
def __gt__(self, other: Any) -> bool:
158170
if not isinstance(other, TimeSnap):
159171
raise NotImplementedError
160172
return self.version > other.version
161173

162-
def __str__(self):
163-
return f"{self.__class__.__name__}({self.version})"
164-
165174

166175
TimeSnaps = Dict[Filepath, TimeSnap]
167176

‎src/tuf_on_a_plane/repository.py‎

Lines changed: 32 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
RollbackAttack,
1212
)
1313
from .models.common import (
14+
Comparable,
1415
Filepath,
1516
Rolename,
1617
Url,
@@ -49,9 +50,7 @@ def __check_expiry(self, signed: Signed) -> None:
4950
if signed.expires <= self.config.NOW:
5051
raise FreezeAttack(f"{signed}: {signed.expires} <= {self.config.NOW}")
5152

52-
# FIXME: maybe we can write a Comparable interface, but I'm too tired right
53-
# now: https://github.com/python/typing/issues/59
54-
def __check_rollback(self, prev: Signed, curr: Signed) -> None:
53+
def __check_rollback(self, prev: Comparable, curr: Comparable) -> None:
5554
if prev > curr:
5655
raise RollbackAttack(f"{prev} > {curr}")
5756

@@ -113,7 +112,8 @@ def __update_root(self) -> None:
113112
"""5.1. Update the root metadata file."""
114113
# 5.1.1. Let N denote the version number of the trusted root metadata
115114
# file.
116-
curr_root = self.__root
115+
prev_root = self.__root
116+
curr_root = prev_root
117117
n = curr_root.version
118118

119119
# 5.1.8. Repeat steps 5.1.1 to 5.1.8.
@@ -144,32 +144,35 @@ def __update_root(self) -> None:
144144
# file.
145145
curr_root = metadata.signed
146146

147-
# 5.1.11. Set whether consistent snapshots are used as per the trusted
148-
# root metadata file (see Section 4.3).
149-
# NOTE: We violate the spec in checking this *before* deleting local
150-
# timestamp and/or snapshot metadata, which I think is reasonable.
151-
if not curr_root.consistent_snapshot:
152-
raise NoConsistentSnapshotsError
153-
154147
# 5.1.9. Check for a freeze attack.
155148
self.__check_expiry(curr_root)
156149

157-
# 5.1.10. If the timestamp and / or snapshot keys have been rotated,
158-
# then delete the trusted timestamp and snapshot metadata files.
159-
if (
160-
self.__root.timestamp != curr_root.timestamp
161-
or self.__root.snapshot != curr_root.snapshot
162-
):
163-
self.rm_file(self.__local_metadata_filename("snapshot"), ignore_errors=True)
164-
self.rm_file(
165-
self.__local_metadata_filename("timestamp"), ignore_errors=True
166-
)
150+
if prev_root < curr_root:
151+
# 5.1.11. Set whether consistent snapshots are used as per the
152+
# trusted root metadata file.
153+
# NOTE: We violate the spec in checking this *before* deleting local
154+
# timestamp and/or snapshot metadata, which I think is reasonable.
155+
if not curr_root.consistent_snapshot:
156+
raise NoConsistentSnapshotsError
157+
158+
# 5.1.10. If the timestamp and / or snapshot keys have been rotated,
159+
# then delete the trusted timestamp and snapshot metadata files.
160+
if (
161+
self.__root.timestamp != curr_root.timestamp
162+
or self.__root.snapshot != curr_root.snapshot
163+
):
164+
self.rm_file(
165+
self.__local_metadata_filename("snapshot"), ignore_errors=True
166+
)
167+
self.rm_file(
168+
self.__local_metadata_filename("timestamp"), ignore_errors=True
169+
)
167170

168-
# 5.1.7. Persist root metadata.
169-
# NOTE: We violate the spec in persisting only *after* checking
170-
# everything, which I think is reasonable.
171-
self.mv_file(tmp_file, self.__local_metadata_filename("root"))
172-
self.__root = curr_root
171+
# 5.1.7. Persist root metadata.
172+
# NOTE: We violate the spec in persisting only *after* checking
173+
# everything, which I think is reasonable.
174+
self.mv_file(tmp_file, self.__local_metadata_filename("root"))
175+
self.__root = curr_root
173176

174177
def __update_timestamp(self) -> None:
175178
"""5.2. Download the timestamp metadata file."""
@@ -192,13 +195,9 @@ def __update_timestamp(self) -> None:
192195
TimeSnap, prev_metadata.signed.snapshot
193196
)
194197
self.__check_rollback(prev_metadata.signed, curr_metadata.signed)
195-
196-
# FIXME: ideally, self.__check_rollback() takes Comparable so that
197-
# we can reuse it.
198-
if prev_metadata.signed.snapshot > curr_metadata.signed.snapshot:
199-
raise RollbackAttack(
200-
f"{prev_metadata.signed.snapshot} > {curr_metadata.signed.snapshot}"
201-
)
198+
self.__check_rollback(
199+
prev_metadata.signed.snapshot, curr_metadata.signed.snapshot
200+
)
202201

203202
# 5.2.3. Check for a freeze attack.
204203
self.__check_expiry(curr_metadata.signed)

0 commit comments

Comments
 (0)