Debian Codegraph @

tests/repository_simulator.py

raw
1 # Copyright 2021, New York University and the TUF contributors
2 # SPDX-License-Identifier: MIT OR Apache-2.0
3
4 """Test utility to simulate a repository
5
6 RepositorySimulator provides methods to modify repository metadata so that it's
7 easy to "publish" new repository versions with modified metadata, while serving
8 the versions to client test code.
9
10 RepositorySimulator implements FetcherInterface so Updaters in tests can use it
11 as a way to "download" new metadata from remote: in practice no downloading,
12 network connections or even file access happens as RepositorySimulator serves
13 everything from memory.
14
15 Metadata and targets "hosted" by the simulator are made available in URL paths
16 "/metadata/..." and "/targets/..." respectively.
17
18 Example::
19
20 # constructor creates repository with top-level metadata
21 sim = RepositorySimulator()
22
23 # metadata can be modified directly: it is immediately available to clients
24 sim.snapshot.version += 1
25
26 # As an exception, new root versions require explicit publishing
27 sim.root.version += 1
28 sim.publish_root()
29
30 # there are helper functions
31 sim.add_target("targets", b"content", "targetpath")
32 sim.targets.version += 1
33 sim.update_snapshot()
34
35 # Use the simulated repository from an Updater:
36 updater = Updater(
37 dir,
38 "https://example.com/metadata/",
39 dir,
40 "https://example.com/targets/",
41 sim,
42 bootstrap=sim.signed_roots[0],
43 )
44 updater.refresh()
45 """
46
47 from __future__ import annotations
48
49 import datetime
50 import hashlib
51 import logging
52 import os
53 import tempfile
54 from dataclasses import dataclass, field
55 from typing import TYPE_CHECKING
56 from urllib import parse
57
58 from securesystemslib.signer import CryptoSigner, Signer
59
60 from tuf.api.exceptions import DownloadHTTPError
61 from tuf.api.metadata import (
62 SPECIFICATION_VERSION,
63 TOP_LEVEL_ROLE_NAMES,
64 DelegatedRole,
65 Delegations,
66 Metadata,
67 MetaFile,
68 Root,
69 Snapshot,
70 SuccinctRoles,
71 TargetFile,
72 Targets,
73 Timestamp,
74 )
75 from tuf.api.serialization.json import JSONSerializer
76 from tuf.ngclient.fetcher import FetcherInterface
77
78 if TYPE_CHECKING:
79 from collections.abc import Iterator
80
81 logger = logging.getLogger(__name__)
82
83 SPEC_VER = ".".join(SPECIFICATION_VERSION)
84
85 _HASH_ALGORITHM = "sha256"
86
87
88 @dataclass
89 class FetchTracker:
90 """Fetcher counter for metadata and targets."""
91
92 metadata: list[tuple[str, int | None]] = field(default_factory=list)
93 targets: list[tuple[str, str | None]] = field(default_factory=list)
94
95
96 @dataclass
97 class RepositoryTarget:
98 """Contains actual target data and the related target metadata."""
99
100 data: bytes
101 target_file: TargetFile
102
103
104 class RepositorySimulator(FetcherInterface):
105 """Simulates a repository that can be used for testing."""
106
107 def __init__(self) -> None:
108 self.md_delegates: dict[str, Metadata[Targets]] = {}
109
110 # other metadata is signed on-demand (when fetched) but roots must be
111 # explicitly published with publish_root() which maintains this list
112 self.signed_roots: list[bytes] = []
113
114 # signers are used on-demand at fetch time to sign metadata
115 # keys are roles, values are dicts of {keyid: signer}
116 self.signers: dict[str, dict[str, Signer]] = {}
117
118 # target downloads are served from this dict
119 self.target_files: dict[str, RepositoryTarget] = {}
120
121 # Whether to compute hashes and length for meta in snapshot/timestamp
122 self.compute_metafile_hashes_length = False
123
124 # Enable hash-prefixed target file names
125 self.prefix_targets_with_hash = True
126
127 self.dump_dir: str | None = None
128 self.dump_version = 0
129
130 self.fetch_tracker = FetchTracker()
131
132 now = datetime.datetime.now(datetime.timezone.utc)
133 self.safe_expiry = now.replace(microsecond=0) + datetime.timedelta(
134 days=30
135 )
136
137 self._initialize()
138
139 @property
140 def root(self) -> Root:
141 return self.md_root.signed
142
143 @property
144 def timestamp(self) -> Timestamp:
145 return self.md_timestamp.signed
146
147 @property
148 def snapshot(self) -> Snapshot:
149 return self.md_snapshot.signed
150
151 @property
152 def targets(self) -> Targets:
153 return self.md_targets.signed
154
155 def all_targets(self) -> Iterator[tuple[str, Targets]]:
156 """Yield role name and signed portion of targets one by one."""
157 yield Targets.type, self.md_targets.signed
158 for role, md in self.md_delegates.items():
159 yield role, md.signed
160
161 def add_signer(self, role: str, signer: Signer) -> None:
162 if role not in self.signers:
163 self.signers[role] = {}
164 self.signers[role][signer.public_key.keyid] = signer
165
166 def rotate_keys(self, role: str) -> None:
167 """remove all keys for role, then add threshold of new keys"""
168 self.root.roles[role].keyids.clear()
169 self.signers[role].clear()
170 for _ in range(self.root.roles[role].threshold):
171 signer = CryptoSigner.generate_ed25519()
172 self.root.add_key(signer.public_key, role)
173 self.add_signer(role, signer)
174
175 def _initialize(self) -> None:
176 """Setup a minimal valid repository."""
177
178 self.md_targets = Metadata(Targets(expires=self.safe_expiry))
179 self.md_snapshot = Metadata(Snapshot(expires=self.safe_expiry))
180 self.md_timestamp = Metadata(Timestamp(expires=self.safe_expiry))
181 self.md_root = Metadata(Root(expires=self.safe_expiry))
182
183 for role in TOP_LEVEL_ROLE_NAMES:
184 signer = CryptoSigner.generate_ed25519()
185 self.md_root.signed.add_key(signer.public_key, role)
186 self.add_signer(role, signer)
187
188 self.publish_root()
189
190 def publish_root(self) -> None:
191 """Sign and store a new serialized version of root."""
192 self.md_root.signatures.clear()
193 for signer in self.signers[Root.type].values():
194 self.md_root.sign(signer, append=True)
195
196 self.signed_roots.append(self.md_root.to_bytes(JSONSerializer()))
197 logger.debug("Published root v%d", self.root.version)
198
199 def _fetch(self, url: str) -> Iterator[bytes]:
200 """Fetches data from the given url and returns an Iterator (or yields
201 bytes).
202 """
203 path = parse.urlparse(url).path
204 if path.startswith("/metadata/") and path.endswith(".json"):
205 # figure out rolename and version
206 ver_and_name = path[len("/metadata/") :][: -len(".json")]
207 version_str, _, role = ver_and_name.partition(".")
208 # root is always version-prefixed while timestamp is always NOT
209 if role == Root.type or (
210 self.root.consistent_snapshot and ver_and_name != Timestamp.type
211 ):
212 version: int | None = int(version_str)
213 else:
214 # the file is not version-prefixed
215 role = ver_and_name
216 version = None
217
218 yield self.fetch_metadata(role, version)
219 elif path.startswith("/targets/"):
220 # figure out target path and hash prefix
221 target_path = path[len("/targets/") :]
222 dir_parts, sep, prefixed_filename = target_path.rpartition("/")
223 # extract the hash prefix, if any
224 prefix: str | None = None
225 filename = prefixed_filename
226 if self.root.consistent_snapshot and self.prefix_targets_with_hash:
227 prefix, _, filename = prefixed_filename.partition(".")
228 target_path = f"{dir_parts}{sep}{filename}"
229
230 yield self.fetch_target(target_path, prefix)
231 else:
232 raise DownloadHTTPError(f"Unknown path '{path}'", 404)
233
234 def fetch_target(self, target_path: str, target_hash: str | None) -> bytes:
235 """Return data for 'target_path', checking 'target_hash' if it is given.
236
237 If hash is None, then consistent_snapshot is not used.
238 """
239 self.fetch_tracker.targets.append((target_path, target_hash))
240
241 repo_target = self.target_files.get(target_path)
242 if repo_target is None:
243 raise DownloadHTTPError(f"No target {target_path}", 404)
244 if (
245 target_hash
246 and target_hash not in repo_target.target_file.hashes.values()
247 ):
248 raise DownloadHTTPError(f"hash mismatch for {target_path}", 404)
249
250 logger.debug("fetched target %s", target_path)
251 return repo_target.data
252
253 def fetch_metadata(self, role: str, version: int | None = None) -> bytes:
254 """Return signed metadata for 'role', using 'version' if it is given.
255
256 If version is None, non-versioned metadata is being requested.
257 """
258 self.fetch_tracker.metadata.append((role, version))
259 # decode role for the metadata
260 role = parse.unquote(role, encoding="utf-8")
261
262 if role == Root.type:
263 # return a version previously serialized in publish_root()
264 if version is None or version > len(self.signed_roots):
265 raise DownloadHTTPError(f"Unknown root version {version}", 404)
266 logger.debug("fetched root version %d", version)
267 return self.signed_roots[version - 1]
268
269 # sign and serialize the requested metadata
270 md: Metadata | None
271 if role == Timestamp.type:
272 md = self.md_timestamp
273 elif role == Snapshot.type:
274 md = self.md_snapshot
275 elif role == Targets.type:
276 md = self.md_targets
277 else:
278 md = self.md_delegates.get(role)
279
280 if md is None:
281 raise DownloadHTTPError(f"Unknown role {role}", 404)
282
283 md.signatures.clear()
284 for signer in self.signers[role].values():
285 md.sign(signer, append=True)
286
287 logger.debug(
288 "fetched %s v%d with %d sigs",
289 role,
290 md.signed.version,
291 len(self.signers[role]),
292 )
293 return md.to_bytes(JSONSerializer())
294
295 def _compute_hashes_and_length(
296 self, role: str
297 ) -> tuple[dict[str, str], int]:
298 data = self.fetch_metadata(role)
299 digest_object = hashlib.new(_HASH_ALGORITHM)
300 digest_object.update(data)
301 hashes = {_HASH_ALGORITHM: digest_object.hexdigest()}
302 return hashes, len(data)
303
304 def update_timestamp(self) -> None:
305 """Update timestamp and assign snapshot version to snapshot_meta
306 version.
307 """
308
309 hashes = None
310 length = None
311 if self.compute_metafile_hashes_length:
312 hashes, length = self._compute_hashes_and_length(Snapshot.type)
313
314 self.timestamp.snapshot_meta = MetaFile(
315 self.snapshot.version, length, hashes
316 )
317
318 self.timestamp.version += 1
319
320 def update_snapshot(self) -> None:
321 """Update snapshot, assign targets versions and update timestamp."""
322 for role, delegate in self.all_targets():
323 hashes = None
324 length = None
325 if self.compute_metafile_hashes_length:
326 hashes, length = self._compute_hashes_and_length(role)
327
328 self.snapshot.meta[f"{role}.json"] = MetaFile(
329 delegate.version, length, hashes
330 )
331
332 self.snapshot.version += 1
333 self.update_timestamp()
334
335 def _get_delegator(self, delegator_name: str) -> Targets:
336 """Given a delegator name return, its corresponding Targets object."""
337 if delegator_name == Targets.type:
338 return self.targets
339
340 return self.md_delegates[delegator_name].signed
341
342 def add_target(self, role: str, data: bytes, path: str) -> None:
343 """Create a target from data and add it to the target_files."""
344 targets = self._get_delegator(role)
345
346 target = TargetFile.from_data(path, data, ["sha256"])
347 targets.targets[path] = target
348 self.target_files[path] = RepositoryTarget(data, target)
349
350 def add_delegation(
351 self, delegator_name: str, role: DelegatedRole, targets: Targets
352 ) -> None:
353 """Add delegated target role to the repository."""
354 delegator = self._get_delegator(delegator_name)
355
356 if (
357 delegator.delegations is not None
358 and delegator.delegations.succinct_roles is not None
359 ):
360 raise ValueError("Can't add a role when succinct_roles is used")
361
362 # Create delegation
363 if delegator.delegations is None:
364 delegator.delegations = Delegations({}, roles={})
365
366 assert delegator.delegations.roles is not None
367 # put delegation last by default
368 delegator.delegations.roles[role.name] = role
369
370 # By default add one new key for the role
371 signer = CryptoSigner.generate_ed25519()
372 delegator.add_key(signer.public_key, role.name)
373 self.add_signer(role.name, signer)
374
375 # Add metadata for the role
376 if role.name not in self.md_delegates:
377 self.md_delegates[role.name] = Metadata(targets, {})
378
379 def add_succinct_roles(
380 self, delegator_name: str, bit_length: int, name_prefix: str
381 ) -> None:
382 """Add succinct roles info to a delegator with name "delegator_name".
383
384 Note that for each delegated role represented by succinct roles an empty
385 Targets instance is created.
386 """
387 delegator = self._get_delegator(delegator_name)
388
389 if (
390 delegator.delegations is not None
391 and delegator.delegations.roles is not None
392 ):
393 raise ValueError(
394 "Can't add a succinct_roles when delegated roles are used"
395 )
396
397 signer = CryptoSigner.generate_ed25519()
398 succinct_roles = SuccinctRoles([], 1, bit_length, name_prefix)
399 delegator.delegations = Delegations({}, None, succinct_roles)
400
401 # Add targets metadata for all bins.
402 for delegated_name in succinct_roles.get_roles():
403 self.md_delegates[delegated_name] = Metadata(
404 Targets(expires=self.safe_expiry)
405 )
406
407 self.add_signer(delegated_name, signer)
408
409 delegator.add_key(signer.public_key)
410
411 def write(self) -> None:
412 """Dump current repository metadata to self.dump_dir
413
414 This is a debugging tool: dumping repository state before running
415 Updater refresh may be useful while debugging a test.
416 """
417 if self.dump_dir is None:
418 self.dump_dir = tempfile.mkdtemp()
419 print(f"Repository Simulator dumps in {self.dump_dir}")
420
421 self.dump_version += 1
422 dest_dir = os.path.join(self.dump_dir, str(self.dump_version))
423 os.makedirs(dest_dir)
424
425 for ver in range(1, len(self.signed_roots) + 1):
426 with open(os.path.join(dest_dir, f"{ver}.root.json"), "wb") as f:
427 f.write(self.fetch_metadata(Root.type, ver))
428
429 for role in [Timestamp.type, Snapshot.type, Targets.type]:
430 with open(os.path.join(dest_dir, f"{role}.json"), "wb") as f:
431 f.write(self.fetch_metadata(role))
432
433 for role in self.md_delegates:
434 quoted_role = parse.quote(role, "")
435 with open(os.path.join(dest_dir, f"{quoted_role}.json"), "wb") as f:
436 f.write(self.fetch_metadata(role))