Debian Codegraph @

python/tests/testsigs/pgpcli/sop.py

raw
1 # SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 # SPDX-License-Identifier: GPL-2.0-or-later
3 """Run a stateless OpenPGP command-line tool."""
4
5 from __future__ import annotations
6
7 import subprocess # noqa: S404
8 import typing
9
10 from testsigs import defs
11
12 from . import base
13
14
15 if typing.TYPE_CHECKING:
16 import pathlib
17 from typing import Final
18
19
20 class SOPCli(base.PGPCli):
21 """Invoke a stateless OpenPGP command-line tool."""
22
23 def generate_keys(self, uid: str) -> defs.KeyFiles:
24 """Generate an OpenPGP key to sign with."""
25 keydir: Final = self.cfg.path.home / "keys"
26 keydir.mkdir(mode=0o755)
27 keys: Final = defs.KeyFiles(
28 secret=keydir / "secret.asc",
29 secret_bin=keydir / "secret.gpg",
30 public=keydir / "public.asc",
31 public_bin=keydir / "public.gpg",
32 )
33
34 secret_text: Final = subprocess.check_output( # noqa: S603
35 [self.cfg.prog.sop, "generate-key", "--profile=rfc4880", uid],
36 cwd=self.cfg.path.work,
37 encoding="UTF-8",
38 env=self.cfg.env,
39 )
40 if not secret_text.startswith("-----BEGIN PGP PRIVATE KEY BLOCK-----"):
41 raise RuntimeError(repr((self.cfg.prog.sop, secret_text)))
42 keys.secret.write_text(secret_text, encoding="UTF-8")
43
44 # This is not UTF-8 text; it may contain arbitrary byte values.
45 secret_bin: Final = subprocess.check_output( # noqa: S603
46 [self.cfg.prog.sop, "dearmor"],
47 cwd=self.cfg.path.work,
48 env=self.cfg.env,
49 input=secret_text.encode("UTF-8"),
50 )
51 keys.secret_bin.write_bytes(secret_bin)
52
53 public_text: Final = subprocess.check_output( # noqa: S603
54 [self.cfg.prog.sop, "extract-cert"],
55 cwd=self.cfg.path.work,
56 encoding="UTF-8",
57 env=self.cfg.env,
58 input=secret_text,
59 )
60 if not public_text.startswith("-----BEGIN PGP PUBLIC KEY BLOCK-----"):
61 raise RuntimeError(repr((self.cfg.prog.sop, public_text)))
62 keys.public.write_text(public_text, encoding="UTF-8")
63
64 # This is not UTF-8 text; it may contain arbitrary byte values.
65 public_bin: Final = subprocess.check_output( # noqa: S603
66 [self.cfg.prog.sop, "dearmor"],
67 cwd=self.cfg.path.work,
68 env=self.cfg.env,
69 input=public_text.encode("UTF-8"),
70 )
71 keys.public_bin.write_bytes(public_bin)
72
73 return keys
74
75 def import_secret_key(self, keys: defs.KeyFiles, uid: str) -> defs.PublicKey:
76 """Import a secret key, return the parts of the public key we care about."""
77 # We don't need that yet, and we cannot parse an OpenPGP key's structure by ourselves.
78 raise NotImplementedError
79
80 def sign_detached(self, keys: defs.KeyFiles, datafile: pathlib.Path) -> pathlib.Path:
81 """Create an ASCII-armored detached signature, return the path to the new file."""
82 signature: Final = datafile.with_name(f"{datafile.name}.asc")
83 sig_contents: Final = subprocess.check_output( # noqa: S603
84 [self.cfg.prog.sop, "sign", keys.secret],
85 cwd=self.cfg.path.work,
86 env=self.cfg.env,
87 input=datafile.read_bytes(),
88 )
89 signature.write_bytes(sig_contents)
90 return signature
91
92 def verify_detached(
93 self,
94 keys: defs.KeyFiles,
95 pub_key: defs.PublicKey,
96 datafile: pathlib.Path,
97 signature: pathlib.Path,
98 ) -> None:
99 """Verify an OpenPGP detached signature in a file."""
100 sig_report: Final = subprocess.check_output( # noqa: S603
101 [self.cfg.prog.sop, "verify", signature, keys.public],
102 cwd=self.cfg.path.work,
103 env=self.cfg.env,
104 input=datafile.read_bytes(),
105 ).decode()
106 if not any(
107 line.split()[2] in {pub_key.key_id, pub_key.fpr} and line.split()[3] == "mode:binary"
108 for line in sig_report.splitlines()
109 ):
110 raise RuntimeError(repr((pub_key, sig_report)))