Debian Codegraph @

lib/ansible/_internal/_secret_input.py

raw
1 # Copyright: Contributors to the Ansible project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 import collections.abc as _c
7 import os
8 import subprocess
9
10 from ansible.errors import AnsibleError
11 from ansible.module_utils.common.file import is_executable
12 from ansible.module_utils.datatag import native_type_name
13 from ansible.module_utils.secrets import register_secrets
14 from ansible.parsing.utils.yaml import from_yaml
15
16 _SUPPORTED_VERSIONS = frozenset((1,))
17
18
19 def load_secret_input_files(paths: _c.Iterable[str | os.PathLike[str]], /) -> None:
20 """Read each secret input file and register its secrets for output masking."""
21 for path in paths:
22 register_secrets(_read_secret_input_file(path))
23
24
25 def _read_secret_input_file(path: str | os.PathLike[str]) -> _c.Iterable[str]:
26 """Parse and validate a single secret input file, returning its list of secret values."""
27 input_path = os.fspath(path)
28
29 # Cannot use os.access(path, os.X_OK) because on macOS running as root any
30 # non regular file (e.g. pipe) will always be True. Our is_executable
31 # check does not suffer from this issue.
32 if is_executable(input_path):
33 raw = _run_secret_input_command(input_path)
34 else:
35 with open(input_path, 'rb') as f:
36 raw = f.read()
37
38 data = from_yaml(
39 raw.decode('utf-8'),
40 file_name=input_path,
41 show_content=False,
42 )
43
44 if not isinstance(data, _c.Mapping):
45 raise AnsibleError(f"Secrets input file {input_path!r} must contain a mapping, not a {native_type_name(data)}.")
46
47 version = data.get('version')
48
49 # bool is a subclass of int, but `version: true` is not a valid version
50 if isinstance(version, bool) or version not in _SUPPORTED_VERSIONS:
51 raise AnsibleError(
52 f"Secrets input file {input_path!r} has an unsupported version {version!r}; "
53 f"supported versions are: {', '.join(str(v) for v in sorted(_SUPPORTED_VERSIONS))}."
54 )
55
56 secrets = data.get('secrets')
57
58 # a str is a Sequence, guard against a bare string being treated as a list of characters
59 if not isinstance(secrets, _c.Sequence) or isinstance(secrets, (str, bytes)):
60 raise AnsibleError(f"Secrets input file {input_path!r} must contain a 'secrets' list.")
61
62 for idx, secret in enumerate(secrets):
63 # values are validated as strings without coercion, so non-string entries are an error
64 # cannot show actual value in error message because it may be a secret, so show idx and type instead
65 if not isinstance(secret, str):
66 raise AnsibleError(f"Secrets input file {input_path!r} entry secrets[{idx}] must be a string, not a {native_type_name(secret)}.")
67
68 return secrets
69
70
71 def _run_secret_input_command(path: str) -> bytes:
72 """Execute an executable secrets input file and return its stdout as bytes."""
73 try:
74 # stderr is passed through so the command can prompt or report errors to the user
75 proc = subprocess.run([path], stdout=subprocess.PIPE, check=False)
76 except OSError as ex:
77 raise AnsibleError(f"Could not run secrets input file {path!r}: {ex}. If this is not an executable, remove the executable bit from the file.") from ex
78
79 if proc.returncode != 0:
80 raise AnsibleError(f"Secrets input file {path!r} returned non-zero exit status {proc.returncode}.")
81
82 return proc.stdout