Debian Codegraph @

tests/test_updater_fetch_target.py

raw
1 # Copyright 2021, New York University and the TUF contributors
2 # SPDX-License-Identifier: MIT OR Apache-2.0
3
4 """Test 'Fetch target' from 'Detailed client workflow' as well as
5 target files storing/loading from cache.
6 """
7
8 from __future__ import annotations
9
10 import os
11 import sys
12 import tempfile
13 import unittest
14 from dataclasses import dataclass
15
16 from tests import utils
17 from tests.repository_simulator import RepositorySimulator
18 from tuf.api.exceptions import RepositoryError
19 from tuf.api.metadata import DelegatedRole, Delegations
20 from tuf.ngclient import Updater
21
22
23 @dataclass
24 class TestTarget:
25 path: str
26 content: bytes
27 encoded_path: str
28
29
30 class TestFetchTarget(unittest.TestCase):
31 """Test ngclient downloading and caching target files."""
32
33 # set dump_dir to trigger repository state dumps
34 dump_dir: str | None = None
35
36 def setUp(self) -> None:
37 self.temp_dir = tempfile.TemporaryDirectory()
38 self.metadata_dir = os.path.join(self.temp_dir.name, "metadata")
39 self.targets_dir = os.path.join(self.temp_dir.name, "targets")
40 os.mkdir(self.metadata_dir)
41 os.mkdir(self.targets_dir)
42
43 # Setup the repository
44 self.sim = RepositorySimulator()
45
46 if self.dump_dir is not None:
47 # create test specific dump directory
48 name = self.id().split(".")[-1]
49 self.sim.dump_dir = os.path.join(self.dump_dir, name)
50 os.mkdir(self.sim.dump_dir)
51
52 def tearDown(self) -> None:
53 self.temp_dir.cleanup()
54
55 def _init_updater(self) -> Updater:
56 """Creates a new updater instance."""
57 if self.sim.dump_dir is not None:
58 self.sim.write()
59
60 return Updater(
61 self.metadata_dir,
62 "https://example.com/metadata/",
63 self.targets_dir,
64 "https://example.com/targets/",
65 self.sim,
66 bootstrap=self.sim.signed_roots[0],
67 )
68
69 targets = {
70 "standard case": TestTarget(
71 path="targetpath",
72 content=b"target content",
73 encoded_path="targetpath",
74 ),
75 "non-asci case": TestTarget(
76 path="åäö",
77 content=b"more content",
78 encoded_path="%C3%A5%C3%A4%C3%B6",
79 ),
80 "subdirectory case": TestTarget(
81 path="a/b/c/targetpath",
82 content=b"dir target content",
83 encoded_path="a%2Fb%2Fc%2Ftargetpath",
84 ),
85 }
86
87 @utils.run_sub_tests_with_dataset(targets)
88 def test_fetch_target(self, target: TestTarget) -> None:
89 path = os.path.join(self.targets_dir, target.encoded_path)
90
91 updater = self._init_updater()
92 # target does not exist yet
93 self.assertIsNone(updater.get_targetinfo(target.path))
94
95 # Add targets to repository
96 self.sim.targets.version += 1
97 self.sim.add_target("targets", target.content, target.path)
98 self.sim.update_snapshot()
99
100 updater = self._init_updater()
101 # target now exists, is not in cache yet
102 info = updater.get_targetinfo(target.path)
103 assert info is not None
104 # Test without and with explicit local filepath
105 self.assertIsNone(updater.find_cached_target(info))
106 self.assertIsNone(updater.find_cached_target(info, path))
107
108 # download target, assert it is in cache and content is correct
109 self.assertEqual(path, updater.download_target(info))
110 self.assertEqual(path, updater.find_cached_target(info))
111 self.assertEqual(path, updater.find_cached_target(info, path))
112
113 with open(path, "rb") as f:
114 self.assertEqual(f.read(), target.content)
115
116 # download using explicit filepath as well
117 os.remove(path)
118 self.assertEqual(path, updater.download_target(info, path))
119 self.assertEqual(path, updater.find_cached_target(info))
120 self.assertEqual(path, updater.find_cached_target(info, path))
121
122 def test_download_targets_with_succinct_roles(self) -> None:
123 self.sim.add_succinct_roles("targets", 8, "bin")
124 self.sim.update_snapshot()
125
126 assert self.sim.targets.delegations is not None
127 assert self.sim.targets.delegations.succinct_roles is not None
128 succinct_roles = self.sim.targets.delegations.succinct_roles
129
130 # Add lots of targets with unique data to imitate a real repository.
131 for i in range(20):
132 target_name = f"target-{i}"
133 target_bin = succinct_roles.get_role_for_target(target_name)
134 self.sim.add_target(
135 target_bin, bytes(target_name, "utf-8"), target_name
136 )
137
138 # download each target
139 updater = self._init_updater()
140 for i in range(20):
141 target_name = f"target-{i}"
142
143 # Verify that the target info was successfully found.
144 target_info = updater.get_targetinfo(target_name)
145 assert target_info is not None
146 target_full_path = updater.download_target(target_info)
147
148 # Verify that the target content is the same as the target name.
149 with open(target_full_path, encoding="utf-8") as target:
150 self.assertEqual(target.read(), target_name)
151
152 def test_invalid_target_download(self) -> None:
153 target = TestTarget("targetpath", b"content", "targetpath")
154
155 # Add target to repository
156 self.sim.targets.version += 1
157 self.sim.add_target("targets", target.content, target.path)
158 self.sim.update_snapshot()
159
160 updater = self._init_updater()
161 info = updater.get_targetinfo(target.path)
162 assert info is not None
163
164 # Corrupt the file content to not match the hash
165 self.sim.target_files[target.path].data = b"conten@"
166 with self.assertRaises(RepositoryError):
167 updater.download_target(info)
168
169 # Corrupt the file content to not match the length
170 self.sim.target_files[target.path].data = b"cont"
171 with self.assertRaises(RepositoryError):
172 updater.download_target(info)
173
174 # Verify the file is not persisted in cache
175 self.assertIsNone(updater.find_cached_target(info))
176
177 def test_invalid_target_cache(self) -> None:
178 target = TestTarget("targetpath", b"content", "targetpath")
179
180 # Add target to repository
181 self.sim.targets.version += 1
182 self.sim.add_target("targets", target.content, target.path)
183 self.sim.update_snapshot()
184
185 # Download the target
186 updater = self._init_updater()
187 info = updater.get_targetinfo(target.path)
188 assert info is not None
189 path = updater.download_target(info)
190 self.assertEqual(path, updater.find_cached_target(info))
191
192 # Add newer content to the same targetpath
193 target.content = b"contentv2"
194 self.sim.targets.version += 1
195 self.sim.add_target("targets", target.content, target.path)
196 self.sim.update_snapshot()
197
198 # Newer content is detected, old cached version is not used
199 updater = self._init_updater()
200 info = updater.get_targetinfo(target.path)
201 assert info is not None
202 self.assertIsNone(updater.find_cached_target(info))
203
204 # Download target, assert it is in cache and content is the newer
205 path = updater.download_target(info)
206 self.assertEqual(path, updater.find_cached_target(info))
207 with open(path, "rb") as f:
208 self.assertEqual(f.read(), target.content)
209
210 def test_meta_missing_delegated_role(self) -> None:
211 """Test a delegation where the role is not part of the snapshot"""
212
213 # Add new delegation, update snapshot. Do not add the actual role
214 role = DelegatedRole("role1", [], 1, True, ["*"])
215 self.sim.targets.delegations = Delegations({}, roles={role.name: role})
216 self.sim.update_snapshot()
217
218 # assert that RepositoryError is raised when role1 is needed
219 updater = self._init_updater()
220 with self.assertRaises(RepositoryError):
221 updater.get_targetinfo("")
222
223
224 if __name__ == "__main__":
225 if "--dump" in sys.argv:
226 TestFetchTarget.dump_dir = tempfile.mkdtemp()
227 print(f"Repository Simulator dumps in {TestFetchTarget.dump_dir}")
228 sys.argv.remove("--dump")
229
230 utils.configure_test_logging(sys.argv)
231 unittest.main()