-
Notifications
You must be signed in to change notification settings - Fork 272
/
test_updater_delegation_graphs.py
396 lines (347 loc) · 14.6 KB
/
test_updater_delegation_graphs.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
#!/usr/bin/env python
# Copyright 2021, New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""Test updating delegated targets roles and searching for
target files with various delegation graphs"""
import os
import sys
import tempfile
import unittest
from dataclasses import astuple, dataclass, field
from typing import Iterable, List, Optional, Tuple
from tests import utils
from tests.repository_simulator import RepositorySimulator
from tuf.api.metadata import (
SPECIFICATION_VERSION,
TOP_LEVEL_ROLE_NAMES,
DelegatedRole,
Targets,
)
from tuf.exceptions import UnsignedMetadataError
from tuf.ngclient import Updater
@dataclass
class TestDelegation:
delegator: str
rolename: str
keyids: List[str] = field(default_factory=list)
threshold: int = 1
terminating: bool = False
paths: List[str] = field(default_factory=lambda: ["*"])
path_hash_prefixes: Optional[List[str]] = None
@dataclass
class TestTarget:
rolename: str
content: bytes
targetpath: str
@dataclass
class DelegationsTestCase:
"""A delegations graph as lists of delegations and target files
and the expected order of traversal as a list of role names."""
delegations: List[TestDelegation]
target_files: List[TestTarget] = field(default_factory=list)
visited_order: List[str] = field(default_factory=list)
class TestDelegations(unittest.TestCase):
"""Base class for delegation tests"""
# set dump_dir to trigger repository state dumps
dump_dir: Optional[str] = None
def setUp(self) -> None:
# pylint: disable=consider-using-with
self.subtest_count = 0
self.temp_dir = tempfile.TemporaryDirectory()
self.metadata_dir = os.path.join(self.temp_dir.name, "metadata")
self.targets_dir = os.path.join(self.temp_dir.name, "targets")
os.mkdir(self.metadata_dir)
os.mkdir(self.targets_dir)
self.sim: RepositorySimulator
def tearDown(self) -> None:
self.temp_dir.cleanup()
def setup_subtest(self) -> None:
self.subtest_count += 1
if self.dump_dir is not None:
# create subtest dumpdir
name = f"{self.id().split('.')[-1]}-{self.subtest_count}"
self.sim.dump_dir = os.path.join(self.dump_dir, name)
os.mkdir(self.sim.dump_dir)
# dump the repo simulator metadata
self.sim.write()
def teardown_subtest(self) -> None:
utils.cleanup_dir(self.metadata_dir)
def _init_repo(self, test_case: DelegationsTestCase) -> None:
"""Create a new RepositorySimulator instance and
populate it with delegations and target files"""
self.sim = RepositorySimulator()
spec_version = ".".join(SPECIFICATION_VERSION)
for d in test_case.delegations:
if d.rolename in self.sim.md_delegates:
targets = self.sim.md_delegates[d.rolename].signed
else:
targets = Targets(
1, spec_version, self.sim.safe_expiry, {}, None
)
# unpack 'd' but skip "delegator"
role = DelegatedRole(*astuple(d)[1:])
self.sim.add_delegation(d.delegator, role, targets)
for target in test_case.target_files:
self.sim.add_target(*astuple(target))
if test_case.target_files:
self.sim.targets.version += 1
self.sim.update_snapshot()
def _init_updater(self) -> Updater:
"""Create a new Updater instance"""
# Init trusted root for Updater
with open(os.path.join(self.metadata_dir, "root.json"), "bw") as f:
f.write(self.sim.signed_roots[0])
return Updater(
self.metadata_dir,
"https://example.com/metadata/",
self.targets_dir,
"https://example.com/targets/",
self.sim,
)
def _assert_files_exist(self, roles: Iterable[str]) -> None:
"""Assert that local metadata files exist for 'roles'"""
expected_files = sorted([f"{role}.json" for role in roles])
local_metadata_files = sorted(os.listdir(self.metadata_dir))
self.assertListEqual(local_metadata_files, expected_files)
class TestDelegationsGraphs(TestDelegations):
"""Test creating delegations graphs with different complexity
and successfully updating the delegated roles metadata"""
graphs: utils.DataSet = {
"basic delegation": DelegationsTestCase(
delegations=[TestDelegation("targets", "A")],
visited_order=["A"],
),
"single level delegations": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
],
visited_order=["A", "B"],
),
"two-level delegations": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("B", "C"),
],
visited_order=["A", "B", "C"],
),
"two-level test DFS order of traversal": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("A", "C"),
TestDelegation("A", "D"),
],
visited_order=["A", "C", "D", "B"],
),
"three-level delegation test DFS order of traversal": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("A", "C"),
TestDelegation("C", "D"),
],
visited_order=["A", "C", "D", "B"],
),
"two-level terminating ignores all but role's descendants": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("A", "C", terminating=True),
TestDelegation("A", "D"),
],
visited_order=["A", "C"],
),
"three-level terminating ignores all but role's descendants": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("A", "C", terminating=True),
TestDelegation("C", "D"),
],
visited_order=["A", "C", "D"],
),
"two-level ignores all branches not matching 'paths'": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A", paths=["*.py"]),
TestDelegation("targets", "B"),
TestDelegation("A", "C"),
],
visited_order=["B"],
),
"three-level ignores all branches not matching 'paths'": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("A", "C", paths=["*.py"]),
TestDelegation("C", "D"),
],
visited_order=["A", "B"],
),
"cyclic graph": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("B", "C"),
TestDelegation("C", "D"),
TestDelegation("D", "B"),
],
visited_order=["A", "B", "C", "D"],
),
"two roles delegating to a third": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("B", "C"),
TestDelegation("A", "C"),
],
# Under all same conditions, 'C' is reached through 'A' first"
visited_order=["A", "C", "B"],
),
"two roles delegating to a third different 'paths'": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("B", "C"),
TestDelegation("A", "C", paths=["*.py"]),
],
# 'C' is reached through 'B' since 'A' does not delegate a matching pattern"
visited_order=["A", "B", "C"],
),
"max number of delegations": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("targets", "C"),
TestDelegation("C", "D"),
TestDelegation("C", "E"),
],
# "E" is skipped, max_delegations is 4
visited_order=["A", "B", "C", "D"],
),
}
@utils.run_sub_tests_with_dataset(graphs)
def test_graph_traversal(self, test_data: DelegationsTestCase) -> None:
"""Test that delegated roles are traversed in the order of appearance
in the delegator's metadata, using pre-order depth-first search"""
try:
exp_files = [*TOP_LEVEL_ROLE_NAMES, *test_data.visited_order]
exp_calls = [(role, 1) for role in test_data.visited_order]
self._init_repo(test_data)
self.setup_subtest()
updater = self._init_updater()
# restrict the max number of delegations to simplify the test
updater.config.max_delegations = 4
# Call explicitly refresh to simplify the expected_calls list
updater.refresh()
self.sim.fetch_tracker.metadata.clear()
# Check that metadata dir contains only top-level roles
self._assert_files_exist(TOP_LEVEL_ROLE_NAMES)
# Looking for a non-existing targetpath forces updater
# to visit all possible delegated roles
targetfile = updater.get_targetinfo("missingpath")
self.assertIsNone(targetfile)
# Check that the delegated roles were visited in the expected
# order and the corresponding metadata files were persisted
self.assertListEqual(self.sim.fetch_tracker.metadata, exp_calls)
self._assert_files_exist(exp_files)
finally:
self.teardown_subtest()
invalid_metadata: utils.DataSet = {
"unsigned delegated role": DelegationsTestCase(
delegations=[
TestDelegation("targets", "A"),
TestDelegation("targets", "B"),
TestDelegation("A", "C"),
],
# The traversal stops after visiting an invalid role
visited_order=["A"],
)
}
@utils.run_sub_tests_with_dataset(invalid_metadata)
def test_invalid_metadata(self, test_data: DelegationsTestCase) -> None:
try:
self._init_repo(test_data)
# The invalid role is the last visited
invalid_role = test_data.visited_order[-1]
self.sim.signers[invalid_role].clear()
self.setup_subtest()
# The invalid role metadata must not be persisted
exp_files = [*TOP_LEVEL_ROLE_NAMES, *test_data.visited_order[:-1]]
exp_calls = [(role, 1) for role in test_data.visited_order]
updater = self._init_updater()
# Call explicitly refresh to simplify the expected_calls list
updater.refresh()
self.sim.fetch_tracker.metadata.clear()
with self.assertRaises(UnsignedMetadataError):
updater.get_targetinfo("missingpath")
# Check that there were no visited roles after the invalid one
# and only the valid metadata files were persisted
self.assertListEqual(self.sim.fetch_tracker.metadata, exp_calls)
self._assert_files_exist(exp_files)
finally:
self.teardown_subtest()
class TestTargetFileSearch(TestDelegations):
r"""
Create a single repository with the following delegations:
targets
*.doc / \ r/*/*
A B
r/x/* / \ r/y/*.zip
C D
Test that Updater successfully finds the target files metadata,
traversing the delegations as expected.
"""
delegations_tree = DelegationsTestCase(
delegations=[
TestDelegation("targets", "A", paths=["*.doc", "*.md"]),
TestDelegation("targets", "B", paths=["releases/*/*"]),
TestDelegation("B", "C", paths=["releases/x/*"]),
TestDelegation("B", "D", paths=["releases/y/*.zip"]),
],
target_files=[
TestTarget("targets", b"content", "targetfile"),
TestTarget("A", b"content", "README.md"),
TestTarget("C", b"content", "releases/x/x_v1"),
TestTarget("D", b"content", "releases/y/y_v1.zip"),
],
)
def setUp(self) -> None:
super().setUp()
self._init_repo(self.delegations_tree)
targets: utils.DataSet = {
"targetfile": ("targetfile", []),
"README.md": ("README.md", ["A"]),
"releases/x/*": ("releases/x/x_v1", ["B", "C"]),
"releases/y/*.zip": ("releases/y/y_v1.zip", ["B", "D"]),
}
@utils.run_sub_tests_with_dataset(targets)
def test_targetfile_search(self, test_data: Tuple[str, List[str]]) -> None:
try:
self.setup_subtest()
targetpath, visited_order = test_data
exp_files = [*TOP_LEVEL_ROLE_NAMES, *visited_order]
exp_calls = [(role, 1) for role in visited_order]
updater = self._init_updater()
# Call explicitly refresh to simplify the expected_calls list
updater.refresh()
self.sim.fetch_tracker.metadata.clear()
target = updater.get_targetinfo(targetpath)
# Confirm that the expected TargetFile is found
assert target is not None
exp_target = self.sim.target_files[targetpath].target_file
self.assertDictEqual(target.to_dict(), exp_target.to_dict())
# Check that the delegated roles were visited in the expected
# order and the corresponding metadata files were persisted
self.assertListEqual(self.sim.fetch_tracker.metadata, exp_calls)
self._assert_files_exist(exp_files)
finally:
self.teardown_subtest()
if __name__ == "__main__":
if "--dump" in sys.argv:
TestDelegations.dump_dir = tempfile.mkdtemp()
print(f"Repository Simulator dumps in {TestDelegations.dump_dir}")
sys.argv.remove("--dump")
utils.configure_test_logging(sys.argv)
unittest.main()