debkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,610 @@
1
+ """Base class containing Debian repository indices and data.
2
+
3
+ Method load() loads the repository.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ from collections.abc import Generator, Iterable
10
+ from dataclasses import dataclass
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from txstore import StorageException, is_unsafe_path
14
+
15
+ from debkit.repo.component import Component, IndexLoad
16
+ from debkit.repo.hashes import parse_size
17
+ from debkit.repo.index_selection import match_index_tail, select_index_entry
18
+ from debkit.repo.package import PackageException
19
+ from debkit.repo.packages import diff_packages
20
+ from debkit.repo.params import (
21
+ ARCH_ANY,
22
+ FLAT_COMPONENT,
23
+ RepoParams,
24
+ is_safe_name,
25
+ is_valid_arch,
26
+ )
27
+ from debkit.repo.release import ROOT_RELEASE_KEYS, Release, RootRelease
28
+ from debkit.repo.repo_diff import RepoDiff
29
+
30
+ if TYPE_CHECKING:
31
+ from txstore import Storage
32
+
33
+ from debkit.repo.gnupg import GnuPG
34
+ from debkit.repo.package import Package
35
+ from debkit.repo.release import IndexEntry
36
+
37
+ logger = logging.getLogger(__name__)
38
+ logger.addHandler(logging.NullHandler())
39
+
40
+ # each component and arch slot -> its package map, by `Filename`, as `Repo.snapshot` takes it
41
+ type RepoSnapshot = dict[tuple[str, str], dict[str, Package]]
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class IndexTarget:
46
+ """One index in the mirror set -> [VALIDATION.md](VALIDATION.md#index-selection).
47
+
48
+ `digests` are what the source root Release records for the path, or `None` for
49
+ the root Release files, which are not listed in their own digest block.
50
+ `known_published` says the Release load or a parse already fetched the object.
51
+ """
52
+
53
+ digests: dict[str, str] | None
54
+ known_published: bool
55
+
56
+
57
+ class RepoReadException(Exception):
58
+ """Exception raised for errors in reading the repository."""
59
+
60
+ def __init__(self, message: str) -> None:
61
+ """Initialize with error message."""
62
+ super().__init__(f"Repo read: {message}")
63
+
64
+
65
+ def _package_size(filename: str, package: Package) -> int:
66
+ """Read a package's `Size` as a byte count.
67
+
68
+ Raises:
69
+ PackageException: The `Size` is not a decimal byte count.
70
+ """
71
+ size = parse_size(package.fields["Size"])
72
+ if size is None:
73
+ raise PackageException(f"{filename} has a malformed Size: {package.fields['Size']!r}")
74
+ return size
75
+
76
+
77
+ class Repo:
78
+ """Object containing Debian repository indices and data.
79
+
80
+ Attributes:
81
+ storage: The storage for the repo.
82
+ params: The input parameters.
83
+ gpg: The GnuPG object.
84
+ release: The root Release file of repo.
85
+ components: The components of the repo by its names
86
+ """
87
+
88
+ def __init__(self, storage: Storage, params: RepoParams, gpg: GnuPG | None = None) -> None:
89
+ """Init repo object.
90
+
91
+ Args:
92
+ storage: The storage for the repo.
93
+ params: The input parameters.
94
+ gpg: The GnuPG object. Defaults to None.
95
+ """
96
+ self.storage = storage
97
+ self.params = params
98
+ self.gpg = gpg
99
+ self.release = RootRelease(storage, params, gpg=gpg)
100
+ self.components: dict[str, Component] = {}
101
+ # Release-token lines already logged. A sync reloads its source after each pass and
102
+ # builds the index set again, so each is logged once per repository; the selection is
103
+ # not cached at load, since a reload, `setup()`, and `save()` change the Release
104
+ self._release_lines_logged: set[str] = set()
105
+ # payloads reported as Release-owned. Building the package set again in one run, as a
106
+ # sync and its check do, reports each once
107
+ self._owned_payloads_warned: set[str] = set()
108
+
109
+ logger.debug(
110
+ "Repo: Storage=%s, Dist=%s, Components=%s",
111
+ storage,
112
+ params.dist,
113
+ params.components,
114
+ )
115
+
116
+ def snapshot(self) -> RepoSnapshot:
117
+ """Snapshot the package maps, as a diff against this repo's later state needs them.
118
+
119
+ A load or a mutation replaces packages rather than changing one in place, so copied
120
+ maps keep describing the repo as it was. A flat slot snapshots its whole index, not
121
+ its arch view: a flat sync copies the index whole, so it plans every payload in it
122
+ -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
123
+
124
+ Returns:
125
+ Each component and arch slot → a copy of its package map.
126
+ """
127
+ return {
128
+ (comp_name, arch): dict(packages.packages)
129
+ for comp_name, component in self.components.items()
130
+ for arch, packages in component.packages.items()
131
+ }
132
+
133
+ def _log_once(self, level: int, msg: str, *args: object) -> None:
134
+ """Log a line about the root Release unless this repository already logged it.
135
+
136
+ Args:
137
+ level: The logging level.
138
+ msg: The message format.
139
+ *args: The format arguments.
140
+ """
141
+ line = msg % args
142
+ if line not in self._release_lines_logged:
143
+ self._release_lines_logged.add(line)
144
+ logger.log(level, line)
145
+
146
+ def get_components(self) -> Generator[str]:
147
+ """Get the components of the repo.
148
+
149
+ Yields:
150
+ The name of a component.
151
+ """
152
+ # try get from params
153
+ if isinstance(self.params.components, list):
154
+ yield from self.params.components
155
+
156
+ # try get from Release file; its tokens name storage directories, so an unsafe one
157
+ # is dropped like a bad architecture token
158
+ # -> [VALIDATION.md](VALIDATION.md#debian-source-strings)
159
+ elif "Components" in self.release.fields:
160
+ names = []
161
+ for name in self.release.fields.get("Components", "").split():
162
+ if is_safe_name(name):
163
+ names.append(name)
164
+ else:
165
+ self._log_once(
166
+ logging.WARNING, "Release component %r is not a safe name. Skipped.", name
167
+ )
168
+ # a flat layout names one index file whatever the component, so a second slot
169
+ # over it would save last and drop what the first one changed
170
+ # -> [VALIDATION.md](VALIDATION.md#repository-index-paths)
171
+ if self.params.is_flat:
172
+ if len(names) > 1:
173
+ self._log_once(
174
+ logging.WARNING,
175
+ "Flat Release lists components %s; using %r.",
176
+ names,
177
+ names[0],
178
+ )
179
+ names = names[:1] or [FLAT_COMPONENT]
180
+ yield from names
181
+
182
+ else:
183
+ yield FLAT_COMPONENT
184
+
185
+ def get_archs(self) -> Generator[str]:
186
+ """Get the architectures of the repo.
187
+
188
+ The `--architectures` selection wins; without one the Release tokens decide. A
189
+ Release without `Architectures` yields the empty arch of a flat repo, or the
190
+ binary architectures a componented one lists indices for
191
+ -> [VALIDATION.md](VALIDATION.md#architectures).
192
+
193
+ Yields:
194
+ The name of an arch.
195
+ """
196
+ if isinstance(self.params.archs, list) and len(self.params.archs) > 0:
197
+ yield from self.params.archs
198
+ return
199
+
200
+ archs = list(self.release_archs())
201
+ if archs or "Architectures" in self.release.fields:
202
+ yield from archs
203
+ elif self.params.is_flat:
204
+ yield ""
205
+ else:
206
+ yield from self._listed_binary_archs(self.get_components())
207
+
208
+ def _listed_binary_archs(self, components: Iterable[str]) -> list[str]:
209
+ """Get the binary architectures the root Release lists a `Packages` index for.
210
+
211
+ Only the selected components count; a directory name that is not an architecture
212
+ token, or `all`, is skipped like a Release token.
213
+
214
+ Args:
215
+ components: The selected components.
216
+
217
+ Returns:
218
+ Sorted architecture names, without duplicates.
219
+ """
220
+ archs: set[str] = set()
221
+ for comp in components:
222
+ for key in self.release.digests:
223
+ match = match_index_tail(key, comp)
224
+ if match is None or match["arch"] is None:
225
+ continue
226
+ arch = match["arch"]
227
+ if arch == ARCH_ANY:
228
+ continue
229
+ if not is_valid_arch(arch):
230
+ self._log_once(
231
+ logging.WARNING, "%r in a Release index path is not an architecture.", arch
232
+ )
233
+ continue
234
+ archs.add(arch)
235
+ if archs:
236
+ self._log_once(
237
+ logging.INFO,
238
+ "Release declares no Architectures; using its indices: %s",
239
+ sorted(archs),
240
+ )
241
+ return sorted(archs)
242
+
243
+ def release_archs(self) -> Generator[str]:
244
+ """Get the architectures the root Release declares, ignoring the selection.
245
+
246
+ Reads `Architectures`, else the singular `Architecture`, and skips `all`. A
247
+ Release token that is not a well-formed architecture name is remote metadata
248
+ steering a storage path, so it is dropped and logged
249
+ -> [VALIDATION.md](VALIDATION.md#architectures).
250
+
251
+ Yields:
252
+ The name of an arch.
253
+ """
254
+ if "Architectures" in self.release.fields:
255
+ field = "Architectures"
256
+ elif "Architecture" in self.release.fields:
257
+ field = "Architecture"
258
+ else:
259
+ return
260
+
261
+ for arch in self.release.fields.get(field, "").split():
262
+ if arch == ARCH_ANY:
263
+ continue
264
+ if not is_valid_arch(arch):
265
+ self._log_once(
266
+ logging.WARNING,
267
+ "%r in Release %s is not an architecture. Skipped.",
268
+ arch,
269
+ field,
270
+ )
271
+ continue
272
+ yield arch
273
+
274
+ def load(self, mode: IndexLoad = IndexLoad.WRITABLE) -> None:
275
+ """Load Debian repository.
276
+
277
+ This method does a similar thing to `apt-get update` command.
278
+
279
+ Args:
280
+ mode: What an architecture that does not load may skip. Defaults to `WRITABLE`,
281
+ which skips a missing index but raises on an unreadable one, since a caller
282
+ that saves would replace it -> [VALIDATION.md](VALIDATION.md#index-loading).
283
+
284
+ Raises:
285
+ RepoReadException: The root Release storage fails to read, or a strict load
286
+ selects no architecture.
287
+ ReleaseReadException: The root Release is missing, too large, unsigned while
288
+ signatures are checked, or a Release holds an unreadable line.
289
+ GPGVerifyException: A signature fails, or an `InRelease` is malformed.
290
+ ChecksumException: A per-arch Release or index fails its digest, or the two signed
291
+ root forms differ.
292
+ ComponentException: An architecture cannot be loaded and may not be skipped.
293
+ PackageException: An index stanza has no `Filename`.
294
+ StorageException: An index exists but its storage fails to read.
295
+ """
296
+ try:
297
+ self.release.load()
298
+ except StorageException as exc:
299
+ raise RepoReadException(str(exc)) from exc
300
+
301
+ if not self.params.is_flat and "Components" not in self.release.fields:
302
+ self._log_once(
303
+ logging.WARNING, "Components field not found in Release of non-flat repo."
304
+ )
305
+
306
+ # the arch set reads only the selection and the root Release, so it is resolved once
307
+ archs = list(self.get_archs())
308
+ # a strict load that selects no architecture loads nothing, and a sync would plan
309
+ # every target index and payload away -> [VALIDATION.md](VALIDATION.md#architectures)
310
+ if mode is IndexLoad.STRICT and not archs:
311
+ raise RepoReadException(
312
+ "Release selects no architecture: it declares none and lists no index."
313
+ )
314
+
315
+ # a reload replaces the components: one the new Release drops must not survive
316
+ self.components = {}
317
+ pkgs_total = 0
318
+ for component_name in self.get_components():
319
+ component = Component(self.storage, self.params, self.release, component_name)
320
+
321
+ pkgs_total += component.load(archs, mode)
322
+
323
+ self.components[component_name] = component
324
+
325
+ logger.debug("Total %s packages in %s.", pkgs_total, self.storage)
326
+ if pkgs_total == 0:
327
+ logger.warning("Empty repo.")
328
+
329
+ def dump(self) -> dict[str, dict[str, Any]]:
330
+ """Dump the repository data to a dict.
331
+
332
+ Returns:
333
+ A dict representation of the repository. The dictionary includes the release, components
334
+ of the repository.
335
+ """
336
+ # add Release (mandatory)
337
+ ret: dict[str, dict[str, Any]] = {
338
+ "release": self.release.dump(),
339
+ "components": {},
340
+ }
341
+
342
+ # add components (mandatory)
343
+ ret["components"] = {
344
+ component_name: component.dump()
345
+ for component_name, component in self.components.items()
346
+ }
347
+
348
+ return ret
349
+
350
+ def stats(self) -> dict[str, dict[str, dict[str, int]]]:
351
+ """Get statistics of the repository.
352
+
353
+ Raises:
354
+ PackageException: A package `Size` is not a decimal byte count.
355
+
356
+ Returns:
357
+ A dict representation of the repository statistics.
358
+ """
359
+ stats: dict[str, dict[str, dict[str, int]]] = {}
360
+ for comp_name, component in self.components.items():
361
+ stats[comp_name] = {}
362
+ for arch in component.packages:
363
+ slot = component.slot_packages(arch)
364
+ stats[comp_name][arch] = {
365
+ "packages_total": len(slot),
366
+ "packages_bytes": sum(
367
+ _package_size(filename, package) for filename, package in slot.items()
368
+ ),
369
+ }
370
+ return stats
371
+
372
+ def get_packages(self) -> Generator[Package]:
373
+ """Get every package of the repository, each payload once.
374
+
375
+ A flat layout shares one index across its arch slots, and an `all` package sits in
376
+ every binary index of its component, so a payload is yielded for its first slot only.
377
+
378
+ Yields:
379
+ The package.
380
+ """
381
+ seen: set[str] = set()
382
+ for component in self.components.values():
383
+ for packages in component.packages.values():
384
+ for package in packages.packages.values():
385
+ if (filename := str(package)) not in seen:
386
+ seen.add(filename)
387
+ yield package
388
+
389
+ def diff(self, older: RepoSnapshot) -> RepoDiff:
390
+ """Get how this repo, the newer state, differs from `older`.
391
+
392
+ Every component and arch slot either side holds is compared, so a slot only the older
393
+ state holds reports its packages as removed.
394
+
395
+ Args:
396
+ older: The older state, as `snapshot` took it.
397
+
398
+ Returns:
399
+ Packages added, removed and updated in this repo, by component and arch.
400
+ """
401
+ diff = RepoDiff()
402
+ newer = self.snapshot()
403
+
404
+ # always compared: equal Release bytes do not prove equal loaded packages, since a
405
+ # load may skip an unreadable index -> [VALIDATION.md](VALIDATION.md#index-loading)
406
+ for slot in sorted(newer.keys() | older.keys()):
407
+ diff.record(*slot, diff_packages(newer.get(slot, {}), older.get(slot, {})))
408
+
409
+ return diff
410
+
411
+ def _release_blocks(self) -> Generator[Release]:
412
+ """Yield every Release whose digest block is authoritative for this repo.
413
+
414
+ The ownership gate and the digest check read the same blocks, so both walk
415
+ this one iterator -> [CRYPTO.md](CRYPTO.md#verification-order).
416
+
417
+ Yields:
418
+ The root Release, then every component Release.
419
+ """
420
+ yield self.release
421
+
422
+ for component in self.components.values():
423
+ for packages in component.containers():
424
+ yield packages.release
425
+
426
+ def _release_owns(self, release_key: str) -> bool:
427
+ """Report whether a signed Release digest block covers this key.
428
+
429
+ The root Release is GPG-verified and every component Release is chained to it
430
+ by digest, so a key either Release lists is authoritative for that path. A
431
+ package stanza naming the same key must not outrank it
432
+ -> [CRYPTO.md](CRYPTO.md#verification-order).
433
+
434
+ Args:
435
+ release_key: Path as the Release lists it, from `release_key()`.
436
+
437
+ Returns:
438
+ True when a Release digest block names the key.
439
+ """
440
+ return any(release_key in release.digests for release in self._release_blocks())
441
+
442
+ def _release_keys(self) -> set[str]:
443
+ """Collect every key a signed Release digest block covers.
444
+
445
+ The set form of `_release_owns` for a caller testing many keys at once: it walks
446
+ the same blocks, so both answer alike -> [CRYPTO.md](CRYPTO.md#verification-order).
447
+
448
+ Returns:
449
+ Every key a Release digest block lists.
450
+ """
451
+ return {key for release in self._release_blocks() for key in release.digests}
452
+
453
+ def verify_checksum(self, filename: str, incoming_digests: dict[str, str]) -> bool:
454
+ """Verify file checksum in all available indices files.
455
+
456
+ Args:
457
+ filename: The name of the file to verify.
458
+ incoming_digests: The digests of the file.
459
+
460
+ Returns:
461
+ Whether the file checksum was verified.
462
+ """
463
+ release_key = self.params.release_key(filename)
464
+
465
+ # no digest block lists the root Release files, so each copy is bound to the bytes
466
+ # the load fetched and verified, and no stanza may vouch for one
467
+ # -> [CRYPTO.md](CRYPTO.md#verification-order)
468
+ if release_key in ROOT_RELEASE_KEYS:
469
+ return self.release.verify_root_digests(release_key, incoming_digests)
470
+
471
+ # a package index is remote metadata, so a stanza naming a path the signed Release
472
+ # also covers would define that path's content instead of the GPG-rooted Release.
473
+ # The Release owns every key inside its digest block, keyed by the path it lists, and
474
+ # is checked against exactly the blocks that granted it that ownership
475
+ # -> [CRYPTO.md](CRYPTO.md#verification-order)
476
+ if self._release_owns(release_key):
477
+ return any(
478
+ release.verify_digests(release_key, incoming_digests)
479
+ for release in self._release_blocks()
480
+ )
481
+
482
+ # only paths outside every block fall to the containers, each keyed by the `Filename`
483
+ # field it parsed, so this is one dict lookup and a path no index names simply misses.
484
+ # A suffix gate here would have to track every compression `dpkg-source` emits
485
+ return any(
486
+ packages.verify_checksum(filename, incoming_digests)
487
+ for component in self.components.values()
488
+ for packages in component.containers()
489
+ )
490
+
491
+ def _get_indices(self) -> dict[str, IndexTarget]:
492
+ """Get every repository index file to mirror, with its expected digests.
493
+
494
+ The signed root Release is the manifest: it lists each index apt may fetch,
495
+ so every listed path is a candidate. Entries are filtered by the selected
496
+ components and architectures and by `RepoParams.indices_exclude`
497
+ → [VALIDATION.md](VALIDATION.md#index-exclude-globs).
498
+
499
+ The root `Release`, `Release.gpg`, and `InRelease` files are not listed in
500
+ the digest block, carry no digests, and are never filtered. A listed key that
501
+ would escape the storage root is dropped
502
+ -> [VALIDATION.md](VALIDATION.md#filename-safety). Nothing is probed
503
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
504
+
505
+ Returns:
506
+ Index path → the digests recorded for it and whether the source is already known to
507
+ publish it.
508
+ """
509
+ ret: dict[str, IndexTarget] = {}
510
+
511
+ components = None if self.params.is_flat else set(self.get_components())
512
+ archs = set(self.get_archs())
513
+ arch_universe = archs | set(self.release_archs())
514
+ excludes = self.params.indices_exclude or []
515
+
516
+ def selected(key: str) -> bool:
517
+ return select_index_entry(
518
+ key,
519
+ components=components,
520
+ archs=archs,
521
+ arch_universe=arch_universe,
522
+ excludes=excludes,
523
+ )
524
+
525
+ # root Release files: the manifest itself, never filtered and never listed
526
+ # in their own digest block
527
+ for path in self.release.get_indices_paths():
528
+ ret[path] = IndexTarget(None, known_published=True)
529
+
530
+ # indices already discovered while parsing, e.g. Packages files. Parsing
531
+ # proved they exist, so they are not probed again, but the selection rules
532
+ # still apply to them.
533
+ for component in self.components.values():
534
+ for path in component.get_indices_paths():
535
+ key = self.params.release_key(path)
536
+ if not selected(key):
537
+ continue
538
+ ret[path] = IndexTarget(self.release.digests.get(key), known_published=True)
539
+
540
+ for entry in self.release.listed_indices():
541
+ if entry.path in ret:
542
+ continue
543
+
544
+ if not selected(entry.key):
545
+ continue
546
+
547
+ if not self._index_path_is_safe(entry):
548
+ continue
549
+
550
+ # listed is not published; the transfer settles it
551
+ ret[entry.path] = IndexTarget(entry.digests, known_published=False)
552
+
553
+ return ret
554
+
555
+ def _index_path_is_safe(self, entry: IndexEntry) -> bool:
556
+ """Report whether a Release-listed index path stays inside the repository.
557
+
558
+ The digest block is remote metadata, so a hostile or malformed Release can
559
+ name a key outside the storage root. A rejected entry is dropped from the
560
+ index set rather than failing the transfer, so one bad record cannot stop a
561
+ mirror -> [VALIDATION.md](VALIDATION.md#filename-safety).
562
+
563
+ Args:
564
+ entry: candidate index from the root Release digest block.
565
+
566
+ Returns:
567
+ True when the path is safe to mirror.
568
+ """
569
+ if is_unsafe_path(entry.key) or is_unsafe_path(entry.path):
570
+ logger.warning("%s listed in Release is an unsafe index path. Skipped.", entry.key)
571
+ return False
572
+ return True
573
+
574
+ def _payload_files(self) -> set[str]:
575
+ """Collect the parsed payload paths, dropping any the Release owns.
576
+
577
+ Returns:
578
+ Paths of every parsed package the Release does not own.
579
+ """
580
+ return self._drop_release_owned(str(pkg) for pkg in self.get_packages())
581
+
582
+ def _drop_release_owned(self, paths: Iterable[str]) -> set[str]:
583
+ """Drop the stanza paths a Release digest block lists.
584
+
585
+ A stanza `Filename` a Release digest block also lists is an index, not a
586
+ payload: the index set alone decides whether it is copied or purged, so index
587
+ selection and the payload copy and removal cannot disagree
588
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
589
+
590
+ Args:
591
+ paths: Stanza paths, as `str(Package)` gives them.
592
+
593
+ Returns:
594
+ The paths no Release digest block lists.
595
+ """
596
+ ret: set[str] = set()
597
+ # one walk of the Release blocks, not one per package
598
+ owned_keys = self._release_keys()
599
+
600
+ for path in paths:
601
+ if self.params.release_key(path) in owned_keys:
602
+ if path not in self._owned_payloads_warned:
603
+ self._owned_payloads_warned.add(path)
604
+ logger.warning(
605
+ "%s is named by a Release digest block, not mirrored as a package", path
606
+ )
607
+ continue
608
+ ret.add(path)
609
+
610
+ return ret