Debian Codegraph @

python/tests/testsigs/__main__.py

raw
1 # SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 # SPDX-License-Identifier: GPL-2.0-or-later
3 """Test the `debsigs` command-line tool using `debsig-verify` and OpenPGP tools."""
4
5 from __future__ import annotations
6
7 import contextlib
8 import dataclasses
9 import os
10 import pathlib
11 import subprocess # noqa: S404
12 import sys
13 import tempfile
14 import typing
15
16 import click
17 import tomli_w
18 import typedload
19
20 from . import defs
21 from .pgpcli import gnupg as c_gnupg
22 from .pgpcli import sop as c_sop
23
24
25 if typing.TYPE_CHECKING:
26 from collections.abc import Iterator
27 from typing import Final
28
29
30 OPGP_UID: Final = "Kieron Latimer <[email protected]>"
31 """The user ID to generate a test key with."""
32
33 DEB_NAME_1: Final = "single-file"
34 """The name of the first Debian package file to build and sign."""
35
36 DEB_NAME_2: Final = "more-files"
37 """The name of the second Debian package file to build and sign."""
38
39
40 @contextlib.contextmanager
41 def _prepare_temp_dir(cfg: defs.Config) -> Iterator[defs.Config]:
42 """Create a temporary directory, clean it up afterwards."""
43 with tempfile.TemporaryDirectory(prefix="debsigs-functional.") as tempd_obj:
44 tempd: Final = pathlib.Path(tempd_obj)
45 home: Final = tempd / "home"
46 work: Final = tempd / "work"
47
48 home.mkdir(mode=0o755)
49 work.mkdir(mode=0o755)
50
51 env: Final = dict(cfg.env)
52 env["LC_ALL"] = "C.UTF-8"
53 env["LANGUAGE"] = ""
54 env["HOME"] = str(home)
55 for name in (name for name in env if name.startswith(("GNUPG", "GPG"))):
56 del env[name]
57
58 yield dataclasses.replace(
59 cfg,
60 env=env,
61 path=defs.ConfigPaths(base=tempd, home=home, work=work, data=cfg.path.data),
62 )
63
64
65 def _test_sign_file(
66 cfg: defs.Config,
67 keys: defs.KeyFiles,
68 cli_gnupg: c_gnupg.GnuPGCli,
69 cli_sop: c_sop.SOPCli,
70 pub_key: defs.PublicKey,
71 ) -> None:
72 """Create a temporary file, sign it, verify the signature."""
73 contents: Final = "This is a test.\n"
74 testf: Final = cfg.path.work / "sign-test.txt"
75
76 if testf.exists() or testf.is_symlink():
77 raise RuntimeError(repr(testf))
78
79 try:
80 testf.write_text(contents, encoding="UTF-8")
81 signature: Final = cli_gnupg.sign_detached(keys, testf)
82 if signature.parent != testf.parent:
83 raise RuntimeError(repr((testf, signature)))
84
85 cli_sop.verify_detached(keys, pub_key, testf, signature)
86 signature.unlink()
87
88 det_signature: Final = cli_sop.sign_detached(keys, testf)
89 if det_signature != signature:
90 raise RuntimeError(repr((signature, det_signature)))
91 cli_gnupg.verify_detached(keys, pub_key, testf, signature)
92 finally:
93 if signature.exists():
94 signature.unlink()
95 if testf.exists():
96 testf.unlink()
97
98
99 def _get_deb_changes(cfg: defs.Config) -> defs.ChangesFile:
100 """Fetch a Debian package from the configured Apt repositories."""
101 ppath: Final = cfg.path.home / "deb-orig"
102 if not ppath.is_dir():
103 ppath.mkdir(mode=0o755)
104
105 current_files: Final = {path for path in ppath.iterdir() if path.is_file()}
106 for dirname in (DEB_NAME_1, DEB_NAME_2):
107 subprocess.check_call( # noqa: S603
108 ["dpkg-deb", "-b", cfg.path.data / "dpkg" / dirname, ppath], # noqa: S607
109 cwd=cfg.path.work,
110 env=cfg.env,
111 )
112 all_files: Final = {path for path in ppath.iterdir() if path.is_file()}
113 new_files: Final = list(all_files - current_files)
114 gone_files: Final = list(current_files - all_files)
115 match (new_files, gone_files):
116 case ([_first, _second], []):
117 pass
118
119 case _:
120 raise RuntimeError(repr((current_files, all_files)))
121
122 others: Final = [ppath / "debsigs-test-more.txt"]
123 others[0].write_text("This file should not be changed.\n", encoding="UTF-8")
124
125 changes: Final = defs.ChangesFile.craft(cfg, ppath / "debsigs-test.changes", new_files, others)
126 changes.verify(cfg)
127 return changes
128
129
130 def _store_test_config(
131 cfg: defs.Config,
132 keys: defs.KeyFiles,
133 pub_key: defs.PublicKey,
134 changes_orig: defs.ChangesFile,
135 ) -> dict[str, str]:
136 """Dump the configuration into TOML files, store the paths into the environment."""
137 cfgpath: Final = cfg.path.work / "test-config.toml"
138 with cfgpath.open(mode="wb") as cfgf:
139 tomli_w.dump(
140 typedload.dump(
141 {
142 "format": {"version": {"major": 1, "minor": 0}},
143 "cfg": cfg,
144 "keys": keys,
145 "pub_key": pub_key,
146 "changes_orig": changes_orig,
147 },
148 ),
149 cfgf,
150 )
151
152 env_test: Final = dict(cfg.env)
153 env_test["DEBSIGS_TEST_CONFIG_FILE"] = str(cfgpath)
154 return env_test
155
156
157 def run_test(cfg: defs.Config) -> None:
158 """Prepare the working directory, run the tests."""
159 cli_gnupg: Final = c_gnupg.GnuPGCli(cfg)
160 cli_sop: Final = c_sop.SOPCli(cfg)
161
162 keys: Final = cli_sop.generate_keys(OPGP_UID)
163 pub_key: Final = cli_gnupg.import_secret_key(keys, OPGP_UID)
164 _test_sign_file(cfg, keys, cli_gnupg, cli_sop, pub_key)
165
166 changes_orig: Final = _get_deb_changes(cfg)
167
168 env_test: Final = _store_test_config(cfg, keys, pub_key, changes_orig)
169 subprocess.check_call( # noqa: S603
170 [
171 sys.executable,
172 "-m",
173 "pytest",
174 "--pyargs",
175 "-vv",
176 "testsigs.unit",
177 ],
178 cwd=cfg.path.work,
179 env=env_test,
180 )
181
182
183 @click.command(name="functional")
184 @click.option(
185 "--debsigs-program",
186 type=click.Path(exists=True, executable=True, path_type=pathlib.Path, resolve_path=True),
187 default="/usr/bin/debsigs",
188 help="the debsigs program to test",
189 )
190 @click.option(
191 "--debsig-verify-program",
192 type=click.Path(exists=True, executable=True, path_type=pathlib.Path, resolve_path=True),
193 default="/usr/bin/debsig-verify",
194 help="the debsig-verify program to check the signed package files with",
195 )
196 @click.option(
197 "--gnupg-program",
198 type=click.Path(exists=True, executable=True, path_type=pathlib.Path, resolve_path=True),
199 default="/usr/bin/gpg",
200 help="the GnuPG program to test and sign with",
201 )
202 @click.option(
203 "--sop-program",
204 type=click.Path(exists=True, executable=True, path_type=pathlib.Path, resolve_path=True),
205 default="/usr/bin/sqop",
206 help="the stateless OpenPGP program to generate keys with",
207 )
208 @click.option(
209 "--test-datadir",
210 type=click.Path(
211 exists=True,
212 file_okay=False,
213 dir_okay=True,
214 path_type=pathlib.Path,
215 resolve_path=True,
216 ),
217 default="test-data",
218 help="the path to the directory containing the test data files",
219 )
220 def main(
221 *,
222 debsigs_program: pathlib.Path,
223 debsig_verify_program: pathlib.Path,
224 gnupg_program: pathlib.Path,
225 sop_program: pathlib.Path,
226 test_datadir: pathlib.Path,
227 ) -> None:
228 """Parse command-line options, prepare the working directory, run the tests."""
229 base_cfg: Final = defs.Config(
230 env=dict(os.environ),
231 path=defs.ConfigPaths(
232 base=pathlib.Path(),
233 home=pathlib.Path(),
234 work=pathlib.Path(),
235 data=test_datadir,
236 ),
237 prog=defs.ConfigPrograms(
238 debsigs=debsigs_program,
239 debsig_verify=debsig_verify_program,
240 gnupg=gnupg_program,
241 sop=sop_program,
242 ),
243 )
244 with _prepare_temp_dir(base_cfg) as cfg:
245 run_test(cfg)
246
247
248 if __name__ == "__main__":
249 main()