Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_gnupg/cli.py

raw
1 # Copyright (c) 2023, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import abc
11 import os
12
13
14 class GPGError(Exception):
15 pass
16
17
18 class GPGRunner(metaclass=abc.ABCMeta):
19 @abc.abstractmethod
20 def run_command(
21 self, command: list[str], *, check_rc: bool = True, data: bytes | None = None
22 ) -> tuple[int, str, str]:
23 """
24 Run ``[gpg] + command`` and return ``(rc, stdout, stderr)``.
25
26 If ``data`` is not ``None``, it will be provided as stdin.
27 The code assumes it is a bytes string.
28
29 Returned stdout and stderr are native Python strings.
30 Pass ``check_rc=False`` to allow return codes != 0.
31
32 Raises a ``GPGError`` in case of errors.
33 """
34
35
36 def get_fingerprint_from_stdout(*, stdout: str) -> str:
37 lines = stdout.splitlines(False)
38 for line in lines:
39 if line.startswith("fpr:"):
40 parts = line.split(":")
41 if len(parts) <= 9 or not parts[9]:
42 raise GPGError(
43 f'Result line "{line}" does not have fingerprint as 10th component'
44 )
45 return parts[9]
46 raise GPGError(f'Cannot extract fingerprint from stdout "{stdout}"')
47
48
49 def get_fingerprint_from_file(*, gpg_runner: GPGRunner, path: str) -> str:
50 if not os.path.exists(path):
51 raise GPGError(f"{path} does not exist")
52 stdout = gpg_runner.run_command(
53 [
54 "--no-keyring",
55 "--with-colons",
56 "--import-options",
57 "show-only",
58 "--import",
59 path,
60 ],
61 check_rc=True,
62 )[1]
63 return get_fingerprint_from_stdout(stdout=stdout)
64
65
66 def get_fingerprint_from_bytes(*, gpg_runner: GPGRunner, content: bytes) -> str:
67 stdout = gpg_runner.run_command(
68 [
69 "--no-keyring",
70 "--with-colons",
71 "--import-options",
72 "show-only",
73 "--import",
74 "/dev/stdin",
75 ],
76 data=content,
77 check_rc=True,
78 )[1]
79 return get_fingerprint_from_stdout(stdout=stdout)
80
81
82 __all__ = (
83 "GPGError",
84 "GPGRunner",
85 "get_fingerprint_from_bytes",
86 "get_fingerprint_from_file",
87 "get_fingerprint_from_stdout",
88 )