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