Debian Codegraph @

python/tests/testsigs/defs.py

raw
1 # SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 # SPDX-License-Identifier: GPL-2.0-or-later
3 """Common definitions for the `debsigs` functional test suite."""
4
5 from __future__ import annotations
6
7 import dataclasses
8 import pathlib # noqa: TC003 # typedload needs this
9 import shutil
10 import subprocess # noqa: S404
11 import typing
12
13
14 if typing.TYPE_CHECKING:
15 from typing import Final, TypeVar
16
17 TChangesFile = TypeVar("TChangesFile", bound="ChangesFile")
18
19
20 @dataclasses.dataclass
21 class Error(Exception):
22 """The base class for errors that occurred during the debsigs test."""
23
24
25 @dataclasses.dataclass(frozen=True)
26 class ConfigPaths:
27 """The paths to the temporary directories to run the test in."""
28
29 base: pathlib.Path
30 """The base directory, the temporary directory created for the whole test."""
31
32 home: pathlib.Path
33 """The directory to serve as the current account's home directory."""
34
35 work: pathlib.Path
36 """The directory to run the test in."""
37
38 data: pathlib.Path
39 """The directory containing the data files to test with, e.g. Debian package structure."""
40
41
42 @dataclasses.dataclass(frozen=True)
43 class ConfigPrograms:
44 """The paths to the programs to test and test with."""
45
46 debsigs: pathlib.Path
47 """The path to the `debsigs` implementation to test."""
48
49 debsig_verify: pathlib.Path
50 """The path to the `debsig-verify` program to test the signed files with."""
51
52 gnupg: pathlib.Path
53 """The path to the `gpg` program to use and test with."""
54
55 sop: pathlib.Path
56 """The path to the stateless OpenPGP program to create keys and possibly sign with."""
57
58
59 @dataclasses.dataclass(frozen=True)
60 class Config:
61 """Runtime configuration for the test suite."""
62
63 env: dict[str, str]
64 """The environment variables to run child processes with."""
65
66 path: ConfigPaths
67 """The paths to the temporary directories to run the test in."""
68
69 prog: ConfigPrograms
70 """The paths to the programs to test and test with."""
71
72
73 @dataclasses.dataclass(frozen=True)
74 class KeyFiles:
75 """The paths to the armored and dearmored OpenPGP key files to test with."""
76
77 secret: pathlib.Path
78 """The ASCII-armored secret key file."""
79
80 secret_bin: pathlib.Path
81 """The dearmored secret key file."""
82
83 public: pathlib.Path
84 """The ASCII-armored public key file."""
85
86 public_bin: pathlib.Path
87 """The dearmored public key file."""
88
89
90 @dataclasses.dataclass(frozen=True)
91 class Subkey:
92 """The parts of an OpenPGP subkey that we care about."""
93
94 key_id: str
95 """The hex string identifier of the subkey."""
96
97 fpr: str
98 """The full hex fingerprint of the key."""
99
100 capabilities: set[str]
101 """The capabilities of this subkey (e.g. `s` for sign, `e` for encrypt, etc.)."""
102
103
104 @dataclasses.dataclass(frozen=True)
105 class PublicKey:
106 """The parts of an OpenPGP public key that we care about."""
107
108 key_id: str
109 """The hex string identifier of the public key."""
110
111 fpr: str
112 """The full hex fingerprint of the key."""
113
114 uid: str
115 """The user ID associated with this key."""
116
117 subkeys: list[Subkey]
118 """The subkeys defined for this key (there must be at least one)."""
119
120
121 @dataclasses.dataclass(frozen=True)
122 class ChangesFile:
123 """List the files described in a Debian archive `*.changes` file."""
124
125 path: pathlib.Path
126 """The path to the changes file itself."""
127
128 debs: list[pathlib.Path]
129 """The Debian packages included in the changes file."""
130
131 others: list[pathlib.Path]
132 """Any other files included in the changes file."""
133
134 @classmethod
135 def craft(
136 cls: type[TChangesFile],
137 cfg: Config,
138 path: pathlib.Path,
139 debs: list[pathlib.Path],
140 others: list[pathlib.Path],
141 ) -> TChangesFile:
142 """Create something resembling a `*.changes` file."""
143 if any(item.parent != path.parent or item == path for item in debs):
144 raise RuntimeError(repr((path, debs)))
145 if any(item.parent != path.parent or item == path for item in others):
146 raise RuntimeError(repr((path, others)))
147 if set(debs) & set(others):
148 raise RuntimeError(repr((debs, others)))
149
150 binaries: Final = [deb.name.split("_")[0] for deb in debs]
151 all_files: Final = [*debs, *others]
152 contents = f"""Format: 1.8
153 Date: Wed, 29 Dec 2021 16:46:40 +0200
154 Source: debsigs-test
155 Binary: {" ".join(binaries)}
156 Architecture: source all
157 Version: 0.1.0
158 Distribution: unstable
159 Urgency: medium
160 Maintainer: Peter Pentchev <[email protected]>
161 Changed-By: Peter Pentchev <[email protected]>
162 Description:
163 debsigs-test - test the operation of the debsigs suite
164 Changes:
165 debsigs-test (0.1.0) unstable; urgency=medium
166 .
167 * Nothing really.
168 """
169
170 for heading in ("Sha1", "Sha256"):
171 contents += f"Checksums-{heading}:\n"
172 for filepath in all_files:
173 checksum = subprocess.check_output( # noqa: S603
174 [
175 f"{heading.lower()}sum",
176 "--",
177 filepath,
178 ],
179 encoding="UTF-8",
180 env=cfg.env,
181 ).split()[0]
182 filesize = filepath.stat().st_size
183 contents += f" {checksum} {filesize} {filepath.name}\n"
184
185 contents += "Files:\n"
186 for filepath in all_files:
187 checksum = subprocess.check_output( # noqa: S603
188 [ # noqa: S607
189 "md5sum",
190 "--",
191 filepath,
192 ],
193 cwd=cfg.path.work,
194 encoding="UTF-8",
195 env=cfg.env,
196 ).split()[0]
197 filesize = filepath.stat().st_size
198 contents += f" {checksum} {filesize} devel optional {filepath.name}\n"
199
200 path.write_text(contents, encoding="UTF-8")
201 return cls(path=path, debs=debs, others=others)
202
203 def verify(self, cfg: Config) -> None:
204 """Run `dscverify` without verifying the nonexistent OpenPGP signature."""
205 lines: Final = subprocess.check_output( # noqa: S603
206 ["dscverify", "-u", "--", self.path], # noqa: S607
207 cwd=cfg.path.work,
208 encoding="UTF-8",
209 env=cfg.env,
210 ).splitlines()
211 verified: Final = {
212 part[2] for part in (line.partition("validating ") for line in lines) if part[1]
213 }
214 if verified != {deb.name for deb in self.debs} | {other.name for other in self.others}:
215 raise RuntimeError(repr((self, lines)))
216
217 def copy_to(self: TChangesFile, destdir: pathlib.Path) -> TChangesFile:
218 """Copy the changes file and all the files it references over to another location."""
219 npath: Final = destdir / self.path.name
220 shutil.copy2(self.path, npath)
221
222 ndebs: Final = []
223 for deb in self.debs:
224 ndeb = destdir / deb.name
225 shutil.copy2(deb, ndeb)
226 ndebs.append(ndeb)
227
228 nothers: Final = []
229 for other in self.others:
230 nother = destdir / other.name
231 shutil.copy2(other, nother)
232 nothers.append(nother)
233
234 return type(self)(path=npath, debs=ndebs, others=nothers)
235
236 def get_different_files(self, cfg: Config, other: ChangesFile) -> list[str]:
237 """Get the filenames of the files that differ between this changes file and another one."""
238 ours: Final = {path.name: path for path in [*self.debs, *self.others]}
239 theirs: Final = {path.name: path for path in [*other.debs, *other.others]}
240 our_names: Final = set(ours)
241 their_names: Final = set(theirs)
242 return sorted(
243 our_names.symmetric_difference(their_names)
244 | {
245 name
246 for name in (our_names & their_names)
247 if subprocess.run( # noqa: S603
248 ["cmp", "--", ours[name], theirs[name]], # noqa: S607
249 check=False,
250 cwd=cfg.path.work,
251 env=cfg.env,
252 ).returncode
253 != 0
254 },
255 )
256
257
258 @dataclasses.dataclass(frozen=True)
259 class DebSig:
260 """A single signature on a package."""
261
262 sig_type: str
263 """The type of the signature, e.g. "origin", "maint", etc."""
264
265 key_id: str
266 """The hex identifier of the OpenPGP key that the signature was made with."""