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.
debkit/repo/release.py ADDED
@@ -0,0 +1,881 @@
1
+ """Class containing Debian Release file data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import logging
7
+ import re
8
+ from datetime import UTC, datetime
9
+ from email.utils import parsedate_to_datetime
10
+ from enum import Enum
11
+ from typing import TYPE_CHECKING, Any, NamedTuple
12
+
13
+ from debian.deb822 import Deb822
14
+ from txstore import SUPPORT_HASH_LIST, StorageNotFoundException, calc_digests, compare_digests
15
+
16
+ from debkit.repo.compress import SizeLimitError, read_capped
17
+ from debkit.repo.gnupg import canonical_text, cleartext_body
18
+ from debkit.repo.hashes import (
19
+ ChecksumException,
20
+ HexDigests,
21
+ parse_hash_block,
22
+ )
23
+ from debkit.repo.stanza import parse_stanza
24
+
25
+ if TYPE_CHECKING:
26
+ from txstore import Storage
27
+
28
+ from debkit.repo.gnupg import GnuPG
29
+ from debkit.repo.params import RepoParams
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+ logger.addHandler(logging.NullHandler())
34
+
35
+ # Fields whose bare unindented continuation tokens are folded onto the previous line; why hash
36
+ # blocks are excluded -> `Release._fix_unindented_continuations`
37
+ _CONTINUATION_FIELDS = frozenset({"Architectures", "Components"})
38
+
39
+ # Largest Release file read when no signed Release records its size; it is read before its
40
+ # signature is checked -> [VALIDATION.md](VALIDATION.md#object-sizes)
41
+ MAX_RELEASE_BYTES = 16 * 1024 * 1024
42
+
43
+ # Every root Release file a load fetches and records digests for; no index stanza may vouch
44
+ # for one -> [CRYPTO.md](CRYPTO.md#verification-order)
45
+ ROOT_RELEASE_KEYS = frozenset({"Release", "InRelease", "Release.gpg"})
46
+ _HASH_BLOCK_FIELDS = frozenset(SUPPORT_HASH_LIST)
47
+
48
+
49
+ class SignatureMode(Enum):
50
+ """How a root Release treats its signatures -> [CRYPTO.md](CRYPTO.md#gpg).
51
+
52
+ Attributes:
53
+ VERIFY_AND_SIGN: GPG verification on with a `GnuPG`: a load verifies every
54
+ signature present and a save signs.
55
+ READ_SIGNED_UNVERIFIED: GPG verification on without a `GnuPG`, as the `sync`
56
+ target: a load reads the signed form unverified and a save is refused.
57
+ OFF: GPG verification off: a load reads either form unverified and a save writes
58
+ unsigned, removing the stale signatures.
59
+ """
60
+
61
+ VERIFY_AND_SIGN = "verify-and-sign"
62
+ READ_SIGNED_UNVERIFIED = "read-signed-unverified"
63
+ OFF = "off"
64
+
65
+
66
+ class IndexEntry(NamedTuple):
67
+ """One index file listed in the digest block of a Release file.
68
+
69
+ Attributes:
70
+ key: Path as the Release lists it, relative to the layout prefix.
71
+ path: Full storage path of the same object.
72
+ digests: Digests and `Size` the Release records for it.
73
+ """
74
+
75
+ key: str
76
+ path: str
77
+ digests: dict[str, str]
78
+
79
+
80
+ class ReleaseReadException(Exception):
81
+ """Exception raised when a Release cannot be read, parsed, or verified."""
82
+
83
+ def __init__(self, message: str) -> None:
84
+ """Initialize with error message."""
85
+ super().__init__(f"Release read: {message}")
86
+
87
+
88
+ class ReleaseNotFoundException(ReleaseReadException):
89
+ """Exception raised when a repository has neither a root `Release` nor an `InRelease`.
90
+
91
+ The only read failure that means "no repository here": every other one is a
92
+ repository that exists but cannot be trusted or parsed.
93
+ """
94
+
95
+
96
+ class ReleaseWriteException(Exception):
97
+ """Exception raised when a Release cannot be signed."""
98
+
99
+ def __init__(self, message: str) -> None:
100
+ """Initialize with error message."""
101
+ super().__init__(f"Release write: {message}")
102
+
103
+
104
+ class ReleaseFreshnessException(Exception):
105
+ """Exception raised when a source Release is stale, expired, or badly dated."""
106
+
107
+ def __init__(self, message: str) -> None:
108
+ """Initialize with error message."""
109
+ super().__init__(f"Release freshness: {message}")
110
+
111
+
112
+ # Zone tokens apt accepts in a Release date; any other name would silently read as UTC
113
+ _RELEASE_DATE_ZONES = frozenset({"UTC", "GMT", "UT", "Z"})
114
+ _NUMERIC_ZONE = re.compile(r"[+-]\d{4}")
115
+
116
+ # a continuation line of only blanks: apt continues the value over it, but a deb822 reader
117
+ # ends the stanza there, so it is written as the ` .` that stands for an empty line
118
+ _BLANK_CONTINUATION = re.compile(r"^[ \t]+$", re.MULTILINE)
119
+
120
+
121
+ def parse_release_date(value: str) -> datetime:
122
+ """Parse a Release date field such as `Date` or `Valid-Until`.
123
+
124
+ The zone must be `UTC`, `GMT`, `UT`, `Z`, or a numeric offset; `-0000` is read as
125
+ UTC -> [VALIDATION.md](VALIDATION.md#release-dates).
126
+
127
+ Args:
128
+ value: Raw field value.
129
+
130
+ Raises:
131
+ ValueError: If *value* is not an RFC 2822 date with an accepted zone.
132
+
133
+ Returns:
134
+ The zone-aware date.
135
+ """
136
+ tokens = value.split()
137
+ zone = tokens[-1] if tokens else ""
138
+ if zone.upper() not in _RELEASE_DATE_ZONES and not _NUMERIC_ZONE.fullmatch(zone):
139
+ raise ValueError(f"not an RFC 2822 date with a UTC or numeric zone: {value!r}")
140
+ try:
141
+ parsed = parsedate_to_datetime(value)
142
+ except (TypeError, ValueError):
143
+ raise ValueError(f"not an RFC 2822 date: {value!r}") from None
144
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
145
+
146
+
147
+ class Release(HexDigests):
148
+ """Object to store Debian Release file data.
149
+
150
+ Attributes:
151
+ storage: The storage class of the repo.
152
+ params: The input parameters of the repo.
153
+ fields: The fields of the release.
154
+ filename: The filename of the release.
155
+ found_indices_files: List of all found Release files.
156
+ hashfuns: Available hexdigest algorithms in data.
157
+ content_sha256: SHA-256 of the loaded file content, for change detection; None
158
+ until a load reads bytes.
159
+ modified: Whether `save` has anything to write: set by a setup, or by whoever changes
160
+ a loaded Release.
161
+ """
162
+
163
+ def __init__(self, storage: Storage, params: RepoParams) -> None:
164
+ """Initialize Release object.
165
+
166
+ Args:
167
+ storage: The storage class of the repo.
168
+ params: The input parameters of the repo.
169
+ """
170
+ self.storage = storage
171
+ self.params = params
172
+ super().__init__()
173
+ self.reset()
174
+
175
+ def reset(self) -> None:
176
+ """Set everything a load or a setup fills to its empty value.
177
+
178
+ `__init__` runs it too, so an override resets only its own fields and reads no state
179
+ its subclass sets after `super().__init__()`.
180
+ """
181
+ self.modified = False
182
+ self.filename: str | None = None
183
+ self.found_indices_files: list[str] = []
184
+ self._reset_parsed()
185
+
186
+ def _reset_parsed(self) -> None:
187
+ """Set everything a parse fills to its empty value.
188
+
189
+ A load finds the file and, for the root Release, fetches its root digests before it
190
+ parses, so those survive; a reload replaces the rest.
191
+ """
192
+ self.fields: dict[str, str] = {}
193
+ self.digests = {}
194
+ self.hashfuns: list[str] = []
195
+ self.content_sha256: str | None = None
196
+
197
+ def __repr__(self) -> str:
198
+ """Return string representation of the Release object."""
199
+ return "<empty>" if self.filename is None else self.filename
200
+
201
+ @staticmethod
202
+ def _fix_unindented_continuations(text: str) -> str:
203
+ """Re-join bare continuation tokens that lack a leading space.
204
+
205
+ Works around non-RFC-2822 Release files.
206
+
207
+ RFC 2822 requires multi-value continuation lines to begin with whitespace (space or tab).
208
+ Some repositories (e.g. ProxySQL) instead emit bare tokens on their own line without any
209
+ leading whitespace:
210
+
211
+ Architectures: amd64
212
+ arm64
213
+ Components: main
214
+
215
+ Python's ``email.parser.Parser`` treats ``arm64`` as a new (invalid) field name and
216
+ consumes ``Components: main`` as its value, silently dropping ``Components`` from the
217
+ parsed result. Without ``Components``, ``get_components()`` falls through to the
218
+ flat-repo fallback (``yield "/"``), which then raises
219
+ ``ComponentException: Cannot load /: <arch>``.
220
+
221
+ This method detects such lines — non-blank, no leading whitespace, no ``:`` — and folds
222
+ them back onto the previous line as space-separated tokens before the parser runs,
223
+ **but only when the active field is in** ``_CONTINUATION_FIELDS``
224
+ (``Architectures`` and ``Components``). Hash-block fields (``MD5Sum``, ``SHA256``,
225
+ etc.) are excluded: folding a stray token into a hash block shifts the
226
+ ``(digest, size, filename)`` triple alignment and silently maps wrong digests to files
227
+ without raising any error.
228
+ It is a no-op for fully conforming Release files.
229
+ """
230
+ lines = text.splitlines(keepends=True)
231
+ fixed: list[str] = []
232
+ warned = False
233
+ current_field: str | None = None
234
+ for line in lines:
235
+ stripped = line.rstrip("\n\r")
236
+ if stripped and not stripped[0].isspace() and ":" in stripped:
237
+ # normal header line — track which field we are in
238
+ current_field = stripped.split(":", 1)[0].strip()
239
+ elif stripped and not stripped[0].isspace() and ":" not in stripped:
240
+ # bare continuation token — fold only for known safe simple-value fields
241
+ if fixed and current_field in _CONTINUATION_FIELDS:
242
+ fixed[-1] = fixed[-1].rstrip("\n\r") + " " + stripped + "\n"
243
+ if not warned:
244
+ logger.warning(
245
+ "Release: non-standard unindented continuation lines detected "
246
+ "and normalised"
247
+ )
248
+ warned = True
249
+ continue
250
+ if current_field in _HASH_BLOCK_FIELDS:
251
+ # Discard stray bare tokens inside hash blocks. If kept, the email
252
+ # parser treats the following indented hash entry as the stray token's
253
+ # continuation, silently emptying the hash field.
254
+ continue
255
+ fixed.append(line)
256
+ return "".join(fixed)
257
+
258
+ def parse(self, enc_data: bytes) -> None:
259
+ """Parse Release file fields from headers format.
260
+
261
+ Args:
262
+ enc_data: The encoded data to parse.
263
+
264
+ Raises:
265
+ ReleaseReadException: A line is neither a field, a continuation, nor empty.
266
+ """
267
+ try:
268
+ data = enc_data.decode("utf-8")
269
+
270
+ # because of possible encoding errors in some repositories
271
+ # 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
272
+ except UnicodeDecodeError:
273
+ data = enc_data.decode("latin-1")
274
+
275
+ data = self._fix_unindented_continuations(data)
276
+ parsed, more_paragraphs, unreadable = parse_stanza(data)
277
+ # the fields after an unreadable line would be missing: Suite, Components, or a
278
+ # digest block -> [VALIDATION.md](VALIDATION.md#blank-lines)
279
+ if unreadable:
280
+ raise ReleaseReadException("unreadable line: a Release field line needs a colon")
281
+ if more_paragraphs:
282
+ # apt reads the first paragraph, so freshness and the index set read it too
283
+ logger.warning("Release: more than one paragraph; reading the first, as apt does")
284
+ # `dict(parsed)` would keep the first of duplicate fields; `items()` lets the last win
285
+ self.fields = dict(parsed.items())
286
+
287
+ # a reload replaces the manifest: a key or algorithm the new file drops must
288
+ # not survive from the previous parse
289
+ self.digests = {}
290
+ self.hashfuns = []
291
+ for hashfun in SUPPORT_HASH_LIST:
292
+ if hashfun in self.fields:
293
+ self.hashfuns.append(hashfun)
294
+ for hashstr, size, filename in parse_hash_block(self.fields[hashfun]):
295
+ if filename not in self.digests:
296
+ self.update_digests(filename, {"Size": str(size)})
297
+ self.update_digests(filename, {hashfun: hashstr})
298
+ del self.fields[hashfun]
299
+
300
+ def _component_release_path(self, comp: str, arch: str) -> str:
301
+ """Compose the path of a per-component Release.
302
+
303
+ One composition for the write and the read alike, so a written Release lands
304
+ where the loader looks -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
305
+
306
+ Args:
307
+ comp: The component the Release belongs to.
308
+ arch: The architecture the Release belongs to.
309
+
310
+ Returns:
311
+ The storage path of the component Release.
312
+ """
313
+ filename = self.params.indices_path(f"{self.params.arch_dir(arch)}/Release", comp)
314
+ return filename
315
+
316
+ @staticmethod
317
+ def _require_coordinates(comp: str, arch: str) -> None:
318
+ """Refuse an empty component or architecture for a per-component Release.
319
+
320
+ Either one empty would compose a path over the root Release or under
321
+ `binary-/` -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
322
+
323
+ Raises:
324
+ ValueError: `comp` or `arch` is empty.
325
+ """
326
+ if not comp or not arch:
327
+ raise ValueError(f"component Release needs a component and an arch: {comp!r} {arch!r}")
328
+
329
+ @property
330
+ def is_loaded(self) -> bool:
331
+ """Whether a load read Release bytes that a reset has not cleared since.
332
+
333
+ Returns:
334
+ True after a successful `load`, `load_component`, or parse of loaded bytes.
335
+ """
336
+ return self.content_sha256 is not None
337
+
338
+ def _parse_loaded(self, data: bytes) -> None:
339
+ """Parse loaded Release bytes and record their hash for change detection.
340
+
341
+ A reload replaces the previous parse, so an empty file leaves the Release unloaded
342
+ rather than keeping the fields and hash it replaced.
343
+ """
344
+ self._reset_parsed()
345
+ if data:
346
+ self.parse(data)
347
+ self.content_sha256 = hashlib.sha256(data).hexdigest()
348
+ if self.hashfuns:
349
+ logger.debug("Available hexdigests: %s", self.hashfuns)
350
+
351
+ def load_component(self, comp: str, arch: str, root_release: HexDigests) -> bool:
352
+ """Load the per-component Release of one architecture.
353
+
354
+ Args:
355
+ comp: The component to load.
356
+ arch: The architecture to load.
357
+ root_release: The root Release listing its digests, checked when digest verification
358
+ is on; only its digest table is read.
359
+
360
+ Raises:
361
+ ValueError: `comp` or `arch` is empty.
362
+ ChecksumException: Checksum mismatch against the root Release, or a file larger than
363
+ the size the root Release records.
364
+ ReleaseReadException: The file is larger than `MAX_RELEASE_BYTES`, whatever size
365
+ the root Release records, or holds an unreadable line.
366
+
367
+ Returns:
368
+ True if the Release file was loaded, False when storage lacks it.
369
+ """
370
+ self._require_coordinates(comp, arch)
371
+ filename = self._component_release_path(comp, arch)
372
+ if not self.storage.exists(filename):
373
+ self.filename = None
374
+ return False
375
+ self.filename = filename
376
+ self.found_indices_files = [filename]
377
+
378
+ key = self.params.release_key(filename)
379
+ checked = self.params.verify_digests
380
+ declared = root_release.declared_size(key) if checked else None
381
+ # a recorded size tightens the cap, never lifts it
382
+ # -> [VALIDATION.md](VALIDATION.md#object-sizes)
383
+ limit = MAX_RELEASE_BYTES if declared is None else min(declared, MAX_RELEASE_BYTES)
384
+ try:
385
+ data = read_capped(self.storage, filename, limit)
386
+ except SizeLimitError as exc:
387
+ if declared is None or declared > MAX_RELEASE_BYTES:
388
+ raise ReleaseReadException(f"{exc}.") from exc
389
+ raise ChecksumException(f"{key} is larger than the root Release records.") from exc
390
+ if checked and not root_release.verify_digests(key, calc_digests(data)):
391
+ raise ChecksumException(f"{key} checksum mismatch.")
392
+
393
+ self._parse_loaded(data)
394
+ logger.info(
395
+ "Component=%s Storage=%s Release=%s", comp, self.storage.get_type(), self.fields
396
+ )
397
+ return True
398
+
399
+ def serialize(self) -> str:
400
+ """Serialize Release file data to headers format.
401
+
402
+ Values are written verbatim, as `Package.serialize` writes a stanza: multi-line values
403
+ keep their continuation lines, non-ASCII text stays UTF-8, and nothing is rewrapped;
404
+ only a blank continuation line becomes ` .`
405
+ -> [VALIDATION.md](VALIDATION.md#release-fields).
406
+
407
+ Returns:
408
+ The serialized Release file fields.
409
+ """
410
+ fields = {
411
+ field: _BLANK_CONTINUATION.sub(" .", value) for field, value in self.fields.items()
412
+ }
413
+ ret = Deb822(fields).dump().rstrip()
414
+
415
+ if self.hashfuns:
416
+ for hashfun in self.hashfuns:
417
+ # a record sits in the blocks its digests cover: a parsed upstream Release
418
+ # may list a file in one block only, and is written back the same way
419
+ hlist = [
420
+ f"{filesums[hashfun]} {filesums['Size']:>16} {filename}"
421
+ for filename, filesums in self.digests.items()
422
+ if hashfun in filesums
423
+ ]
424
+ if hlist:
425
+ ret += f"\n{hashfun}:\n " + "\n ".join(hlist)
426
+
427
+ return ret
428
+
429
+ def save(self) -> dict[str, str] | None:
430
+ """Save Release file when it changed.
431
+
432
+ A per-component Release is written where it was read and never signed; a root one
433
+ -> `RootRelease`.
434
+
435
+ Raises:
436
+ ReleaseWriteException: A root Release cannot be signed.
437
+
438
+ Returns:
439
+ The digests of the saved file, or None when nothing was written.
440
+ """
441
+ if self.filename is None:
442
+ return None
443
+
444
+ if not self.modified:
445
+ logger.debug("%s not modified.", self.filename)
446
+ return None
447
+
448
+ return calc_digests(self._put())
449
+
450
+ def _put(self) -> bytes:
451
+ """Write the serialized Release to its file.
452
+
453
+ Returns:
454
+ The bytes written.
455
+ """
456
+ assert self.filename is not None, "put without a file"
457
+ enc_data = self.serialize().encode("utf-8")
458
+ logger.info("Save %s...", self.filename)
459
+ self.storage.put(self.filename, enc_data)
460
+ return enc_data
461
+
462
+ def dump(self) -> dict[str, Any]:
463
+ """Dump Release object to a dict.
464
+
465
+ Returns:
466
+ A dict representation of the Release object: the indices filenames, the fields, and
467
+ the digests.
468
+ """
469
+ return {
470
+ "files": self.found_indices_files,
471
+ "data": self.fields,
472
+ "digests": self.digests,
473
+ }
474
+
475
+ def get_indices_paths(self) -> list[str]:
476
+ """Get list of all found indices filenames.
477
+
478
+ Returns:
479
+ A list of filenames.
480
+ """
481
+ return self.found_indices_files
482
+
483
+ def listed_indices(self) -> list[IndexEntry]:
484
+ """Get every index file the digest block of this Release lists.
485
+
486
+ The Release lists index paths relative to the layout prefix; this maps each
487
+ one to its full storage path. Entries are not checked against storage, so a
488
+ path listed but not published by the repository is still returned.
489
+
490
+ Returns:
491
+ One entry per digest block record, sorted by key.
492
+ """
493
+ return [
494
+ IndexEntry(key, self.params.indices_path(key), digests)
495
+ for key, digests in sorted(self.digests.items())
496
+ ]
497
+
498
+ def date(self, field: str) -> datetime | None:
499
+ """Get a date field of the Release.
500
+
501
+ Args:
502
+ field: Field name, `Date` or `Valid-Until`.
503
+
504
+ Raises:
505
+ ValueError: If the field is present but malformed.
506
+
507
+ Returns:
508
+ The zone-aware date, or None when the field is absent.
509
+ """
510
+ value = self.fields.get(field)
511
+ return None if value is None else parse_release_date(value)
512
+
513
+ def is_empty(self) -> bool:
514
+ """Check if Release object is empty.
515
+
516
+ Returns:
517
+ True if the Release object is empty, False otherwise.
518
+ """
519
+ return bool(len(self.fields) == 0)
520
+
521
+ def setup_component(self, comp: str, arch: str) -> None:
522
+ """Start a new per-component Release of one architecture.
523
+
524
+ Args:
525
+ comp: The component.
526
+ arch: The architecture.
527
+
528
+ Raises:
529
+ ValueError: `comp` or `arch` is empty.
530
+ """
531
+ self._require_coordinates(comp, arch)
532
+ self.fields = {"Component": comp, "Architecture": arch}
533
+ self._start_file(self._component_release_path(comp, arch))
534
+
535
+ def _start_file(self, filename: str) -> None:
536
+ """Point this Release at a new file to write with every supported digest."""
537
+ self.hashfuns = list(SUPPORT_HASH_LIST)
538
+ self.filename = filename
539
+ self.found_indices_files = [filename]
540
+ self.modified = True
541
+
542
+
543
+ class RootRelease(Release):
544
+ """The root Release of a repository: loaded and signed at the layout's root paths.
545
+
546
+ A root save writes the layout's `Release` whichever form the load read, then signs
547
+ it or removes its stale signatures -> [CRYPTO.md](CRYPTO.md#gpg).
548
+
549
+ Attributes:
550
+ gpg: The GnuPG object, None where none verifies or signs.
551
+ root_digests: Release key → digests of each root Release file as the last load fetched it.
552
+ """
553
+
554
+ root_digests: dict[str, dict[str, str]]
555
+
556
+ def __init__(self, storage: Storage, params: RepoParams, gpg: GnuPG | None = None) -> None:
557
+ """Initialize RootRelease object.
558
+
559
+ Args:
560
+ storage: The storage class of the repo.
561
+ params: The input parameters of the repo.
562
+ gpg: Optional GnuPG object. Defaults to None.
563
+ """
564
+ self.gpg: GnuPG | None = gpg
565
+ super().__init__(storage, params)
566
+
567
+ def reset(self) -> None:
568
+ """Reset RootRelease object to defaults, dropping the fetched root digests too."""
569
+ super().reset()
570
+ self.root_digests = {}
571
+
572
+ def _put(self) -> bytes:
573
+ """Write the layout's root `Release`, then sign it or drop its stale signatures.
574
+
575
+ Raises:
576
+ ReleaseWriteException: In `READ_SIGNED_UNVERIFIED` no `GnuPG` signs it, and
577
+ saving unsigned would drop the signatures it was read with.
578
+
579
+ Returns:
580
+ The bytes written.
581
+ """
582
+ mode = self.signature_mode
583
+ if mode is SignatureMode.READ_SIGNED_UNVERIFIED:
584
+ raise ReleaseWriteException(
585
+ "GPG verification is on but no GnuPG signs the root Release; "
586
+ "refusing to save it unsigned"
587
+ )
588
+ self.filename = self.params.indices_path("Release")
589
+ enc_data = super()._put()
590
+ if mode is SignatureMode.VERIFY_AND_SIGN:
591
+ self._sign_gpg(enc_data)
592
+ else:
593
+ self._remove_root_signatures()
594
+ return enc_data
595
+
596
+ @property
597
+ def signature_mode(self) -> SignatureMode:
598
+ """How a root load and save treat signatures, from the GPG switch and the `GnuPG`.
599
+
600
+ GPG verification also turns signing on -> [CRYPTO.md](CRYPTO.md#verification-switches).
601
+
602
+ Returns:
603
+ The mode; the one place `params.verify_gpg` and `gpg` are combined.
604
+ """
605
+ if not self.params.verify_gpg:
606
+ return SignatureMode.OFF
607
+ if self.gpg is None:
608
+ return SignatureMode.READ_SIGNED_UNVERIFIED
609
+ return SignatureMode.VERIFY_AND_SIGN
610
+
611
+ def _find_root_files(self) -> tuple[bool, str]:
612
+ """Find the root Release files in storage and pick the one to parse.
613
+
614
+ Raises:
615
+ ReleaseNotFoundException: Neither `Release` nor `InRelease` exists.
616
+ ReleaseReadException: Signatures are checked and neither `Release.gpg` nor
617
+ `InRelease` exists.
618
+
619
+ Returns:
620
+ Whether to parse `InRelease`, and the file to parse.
621
+ """
622
+ # the layout decides the prefix -> [VALIDATION.md](VALIDATION.md#repository-index-paths)
623
+ release_path = self.params.indices_path("Release")
624
+ release_gpg_path = self.params.indices_path("Release.gpg")
625
+ inrelease_path = self.params.indices_path("InRelease")
626
+
627
+ release_path_exists = self.storage.exists(release_path)
628
+ release_gpg_path_exists = self.storage.exists(release_gpg_path)
629
+ inrelease_path_exists = self.storage.exists(inrelease_path)
630
+
631
+ # Release or InRelease not found
632
+ if not (release_path_exists or inrelease_path_exists):
633
+ raise ReleaseNotFoundException(f"File not found: {release_path} or {inrelease_path}")
634
+
635
+ # a detached signature signs `Release` alone, so without one it is never verified and
636
+ # never mirrored -> [CRYPTO.md](CRYPTO.md#gpg)
637
+ if release_gpg_path_exists and not release_path_exists:
638
+ logger.warning("%s signs no %s. Skipped.", release_gpg_path, release_path)
639
+ release_gpg_path_exists = False
640
+
641
+ # an unsigned Release reads as-is when no signature is checked
642
+ # -> [CRYPTO.md](CRYPTO.md#verification-switches)
643
+ mode = self.signature_mode
644
+ if mode is SignatureMode.VERIFY_AND_SIGN and not (
645
+ release_gpg_path_exists or inrelease_path_exists
646
+ ):
647
+ raise ReleaseReadException(
648
+ f"GPG signature file missing: {release_gpg_path} or {inrelease_path}"
649
+ )
650
+
651
+ self.found_indices_files = [
652
+ path
653
+ for path, exists in (
654
+ (release_path, release_path_exists),
655
+ (release_gpg_path, release_gpg_path_exists),
656
+ (inrelease_path, inrelease_path_exists),
657
+ )
658
+ if exists
659
+ ]
660
+
661
+ # with verification on, a Release without its detached signature is read from InRelease
662
+ # even when no GnuPG checks it here, as the sync target: the verified source reads the
663
+ # same form, so both hash the same body -> [CRYPTO.md](CRYPTO.md#gpg)
664
+ prefers_signed_form = mode is not SignatureMode.OFF and not release_gpg_path_exists
665
+ use_inrelease = inrelease_path_exists and (not release_path_exists or prefers_signed_form)
666
+ return use_inrelease, inrelease_path if use_inrelease else release_path
667
+
668
+ def _verify_gpg(self, data: bytes, detach_sign: bytes | None = None) -> bytes:
669
+ """Verify GPG signature.
670
+
671
+ Args:
672
+ data: The data to verify.
673
+ detach_sign: The detached signature. Defaults to None.
674
+
675
+ Returns:
676
+ The verified data.
677
+ """
678
+ # only reached in `VERIFY_AND_SIGN`, so a missing GnuPG is a caller bug,
679
+ # never an unverified load
680
+ assert self.gpg is not None, "signature check without GnuPG"
681
+
682
+ if detach_sign is None:
683
+ logger.debug("Verify signed InRelease...")
684
+ return self.gpg.verify(data)
685
+ logger.debug("Verify detached GPG signature...")
686
+ return self.gpg.verify(data, detach_sign=detach_sign)
687
+
688
+ def _load_root_files(self, use_inrelease: bool) -> bytes:
689
+ """Fetch every root Release file once and verify each signature present.
690
+
691
+ No digest block lists these files, so their digests are recorded here: a sync
692
+ copy must match the bytes this load verified, not a second fetch of them
693
+ -> [CRYPTO.md](CRYPTO.md#verification-order).
694
+
695
+ Args:
696
+ use_inrelease: Whether `InRelease` is the file to parse.
697
+
698
+ Raises:
699
+ ChecksumException: Both `InRelease` and `Release` are present and their
700
+ verified contents differ.
701
+ ReleaseReadException: A root Release file is larger than `MAX_RELEASE_BYTES`.
702
+
703
+ Returns:
704
+ The verified content of the file to parse.
705
+ """
706
+ raw: dict[str, bytes] = {}
707
+ for path in self.found_indices_files:
708
+ try:
709
+ raw[self.params.release_key(path)] = read_capped(
710
+ self.storage, path, MAX_RELEASE_BYTES
711
+ )
712
+ except SizeLimitError as exc:
713
+ raise ReleaseReadException(f"{exc}.") from exc
714
+ self.root_digests = {key: calc_digests(data) for key, data in raw.items()}
715
+
716
+ if self.signature_mode is SignatureMode.VERIFY_AND_SIGN:
717
+ if "InRelease" in raw:
718
+ raw["InRelease"] = self._verify_gpg(raw["InRelease"])
719
+ if "Release" in raw and "Release.gpg" in raw:
720
+ self._verify_gpg(raw["Release"], detach_sign=raw["Release.gpg"])
721
+ # only the parsed form is checked for freshness, and apt prefers `InRelease`,
722
+ # so a mirrored pair must say the same -> [CRYPTO.md](CRYPTO.md#gpg)
723
+ if (
724
+ "InRelease" in raw
725
+ and "Release" in raw
726
+ and raw["InRelease"] != canonical_text(raw["Release"])
727
+ ):
728
+ raise ChecksumException("Release and InRelease carry different content.")
729
+ elif use_inrelease:
730
+ # unverified, as under `--skip-verify-gpg` or for a sync target, yet the signed
731
+ # body still holds the fields and the Date a source must not undercut
732
+ # -> [CRYPTO.md](CRYPTO.md#release-freshness)
733
+ raw["InRelease"] = cleartext_body(raw["InRelease"])
734
+
735
+ return raw["InRelease" if use_inrelease else "Release"]
736
+
737
+ def verify_root_digests(self, key: str, incoming_digests: dict[str, str]) -> bool:
738
+ """Verify a root Release file against the bytes the last load fetched.
739
+
740
+ Args:
741
+ key: `Release`, `InRelease`, or `Release.gpg`.
742
+ incoming_digests: The digests to verify.
743
+
744
+ Returns:
745
+ True when the last load fetched the file with these digests.
746
+ """
747
+ return compare_digests(self.root_digests.get(key, {}), incoming_digests)
748
+
749
+ def load(self) -> None:
750
+ """Load the root Release file, verifying its signatures when they are checked.
751
+
752
+ Raises:
753
+ ReleaseNotFoundException: Neither a root `Release` nor an `InRelease` exists.
754
+ ReleaseReadException: Signatures are checked and the root Release has none, or
755
+ it holds an unreadable line.
756
+ GPGVerifyException: A root Release signature fails, or an `InRelease` is malformed.
757
+ ChecksumException: `Release` and `InRelease` carry different content.
758
+ StorageException: A root Release file exists but its storage fails to read.
759
+ """
760
+ use_inrelease, self.filename = self._find_root_files()
761
+ self._parse_loaded(self._load_root_files(use_inrelease))
762
+ logger.info("Repo: Storage=%s Release=%s", self.storage.get_type(), self.fields)
763
+
764
+ def setup(self, fields: dict[str, str] | None = None) -> None:
765
+ """Start a new root Release.
766
+
767
+ Args:
768
+ fields: Initial fields, copied; the generated identity fields are added to them.
769
+ Defaults to None (keep the current ones).
770
+ """
771
+ # a new root Release is named after its dist, which every repo that saves one has
772
+ dist = self.params.dist
773
+ assert dist is not None
774
+ if fields is not None:
775
+ self.fields = dict(fields)
776
+ self.fields.update(
777
+ {
778
+ "Origin": dist,
779
+ "Label": dist,
780
+ "Suite": dist,
781
+ "Codename": dist,
782
+ "Description": "Generated by debkit",
783
+ }
784
+ )
785
+ self._start_file(self.params.indices_path("Release"))
786
+
787
+ def _sign_gpg(self, enc_data: bytes) -> None:
788
+ """Sign the root Release into the layout's `InRelease` and `Release.gpg`.
789
+
790
+ Args:
791
+ enc_data: The encoded root Release to sign.
792
+
793
+ Raises:
794
+ ReleaseWriteException: GnuPG sign error
795
+ """
796
+ GPG_ERR_MSG = "GnuPG sign error (maybe wrong passphrase?)"
797
+
798
+ # only reached in `VERIFY_AND_SIGN`, so a missing GnuPG is a caller bug
799
+ assert self.gpg is not None, "signing without GnuPG"
800
+
801
+ signed_data = self.gpg.sign(enc_data).encode("utf-8")
802
+ if len(signed_data):
803
+ signed_filename = self.params.indices_path("InRelease")
804
+ logger.info("Save signed InRelease...")
805
+ self.storage.put(signed_filename, signed_data)
806
+ else:
807
+ raise ReleaseWriteException(GPG_ERR_MSG)
808
+
809
+ detached_signature = self.gpg.sign(enc_data, detach=True).encode("utf-8")
810
+ if len(detached_signature):
811
+ detached_filename = self.params.indices_path("Release.gpg")
812
+ logger.info("Save detached GPG signature...")
813
+ self.storage.put(detached_filename, detached_signature)
814
+ else:
815
+ raise ReleaseWriteException(GPG_ERR_MSG)
816
+
817
+ def _remove_root_signatures(self) -> None:
818
+ """Delete the root `InRelease` and `Release.gpg` an unsigned save leaves stale.
819
+
820
+ Both sign the previous content, so apt would read a hash mismatch or a bad
821
+ signature -> [CRYPTO.md](CRYPTO.md#verification-switches).
822
+ """
823
+ for path in (
824
+ self.params.indices_path("InRelease"),
825
+ self.params.indices_path("Release.gpg"),
826
+ ):
827
+ try:
828
+ self.storage.delete(path)
829
+ except StorageNotFoundException:
830
+ continue
831
+ logger.warning("Release saved unsigned: removed stale signature %s", path)
832
+ self.found_indices_files = [f for f in self.found_indices_files if f != path]
833
+
834
+ def _signed_date(self, field: str) -> datetime | None:
835
+ """Get a date field of this source Release, refusing a malformed one."""
836
+ try:
837
+ return self.date(field)
838
+ except ValueError as exc:
839
+ raise ReleaseFreshnessException(f"source {field} is {exc}") from None
840
+
841
+ def check_fresh_against(self, target_date: str | None, now: datetime) -> None:
842
+ """Refuse this source Release when it is expired or older than the target.
843
+
844
+ A signature proves who signed a Release, not that it is current: a replayed
845
+ older Release would roll the target back, and the orphan pass would purge every
846
+ newer object -> [CRYPTO.md](CRYPTO.md#release-freshness).
847
+
848
+ Args:
849
+ target_date: The target Release `Date` as read, None when it has none or was not
850
+ loaded.
851
+ now: Zone-aware current time.
852
+
853
+ Raises:
854
+ ReleaseFreshnessException: This Release is expired, has no `Date` while the
855
+ target has one, is older than the target, or carries a malformed date.
856
+ """
857
+ valid_until = self._signed_date("Valid-Until")
858
+ source_date = self._signed_date("Date")
859
+
860
+ if valid_until is not None and valid_until < now:
861
+ raise ReleaseFreshnessException(
862
+ f"source Release expired at {self.fields['Valid-Until']}"
863
+ )
864
+
865
+ if target_date is None:
866
+ return
867
+ try:
868
+ target_dated = parse_release_date(target_date)
869
+ except ValueError as exc:
870
+ logger.warning("Target Release Date is %s; not compared with the source", exc)
871
+ return
872
+
873
+ if source_date is None:
874
+ raise ReleaseFreshnessException(
875
+ f"source Release has no Date; the target Release is dated {target_date}"
876
+ )
877
+ if source_date < target_dated:
878
+ raise ReleaseFreshnessException(
879
+ f"source Release dated {self.fields['Date']} is older than the target Release "
880
+ f"dated {target_date}"
881
+ )