| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import abc |
| 4 |
import copy |
| 5 |
import typing as t |
| 6 |
|
| 7 |
from yaml import Node, ScalarNode |
| 8 |
from yaml.constructor import SafeConstructor |
| 9 |
from yaml.resolver import BaseResolver |
| 10 |
|
| 11 |
from ansible import constants as C |
| 12 |
from ansible.module_utils.common.text.converters import to_text |
| 13 |
from ansible.module_utils._internal._datatag import AnsibleTagHelper, AnsibleDatatagBase |
| 14 |
from ansible._internal._datatag._tags import Origin, TrustedAsTemplate |
| 15 |
from ansible.parsing.vault import EncryptedString |
| 16 |
from ansible.utils.display import Display |
| 17 |
|
| 18 |
from ._errors import AnsibleConstructorError |
| 19 |
from ...module_utils.secrets import register_secret |
| 20 |
|
| 21 |
display = Display() |
| 22 |
|
| 23 |
_TRUSTED_AS_TEMPLATE: t.Final[TrustedAsTemplate] = TrustedAsTemplate() |
| 24 |
|
| 25 |
|
| 26 |
class _BaseConstructor(SafeConstructor, metaclass=abc.ABCMeta): |
| 27 |
"""Base class for Ansible YAML constructors.""" |
| 28 |
|
| 29 |
@classmethod |
| 30 |
@abc.abstractmethod |
| 31 |
def _register_constructors(cls) -> None: |
| 32 |
"""Method used to register constructors to derived types during class initialization.""" |
| 33 |
|
| 34 |
def __init_subclass__(cls, **kwargs) -> None: |
| 35 |
"""Initialization for derived types.""" |
| 36 |
cls._register_constructors() |
| 37 |
|
| 38 |
|
| 39 |
class AnsibleInstrumentedConstructor(_BaseConstructor): |
| 40 |
"""Ansible constructor which supports Ansible custom behavior such as `Origin` tagging, but no Ansible-specific YAML tags.""" |
| 41 |
|
| 42 |
name: t.Any # provided by the YAML parser, which retrieves it from the stream |
| 43 |
|
| 44 |
def __init__(self, origin: Origin, trusted_as_template: bool, sensitive_source_data: bool = False) -> None: |
| 45 |
if not origin.line_num: |
| 46 |
origin = origin.replace(line_num=1) |
| 47 |
|
| 48 |
self._origin = origin |
| 49 |
self._trusted_as_template = trusted_as_template |
| 50 |
self._sensitive_source_data = sensitive_source_data |
| 51 |
self._duplicate_key_mode = C.config.get_config_value('DUPLICATE_YAML_DICT_KEY') |
| 52 |
|
| 53 |
super().__init__() |
| 54 |
|
| 55 |
@property |
| 56 |
def trusted_as_template(self) -> bool: |
| 57 |
return self._trusted_as_template |
| 58 |
|
| 59 |
def construct_yaml_map(self, node): |
| 60 |
data = self._node_position_info(node).tag({}) # always an ordered dictionary on py3.7+ |
| 61 |
yield data |
| 62 |
value = self.construct_mapping(node) |
| 63 |
data.update(value) |
| 64 |
|
| 65 |
def construct_mapping(self, node, deep=False): |
| 66 |
# Delegate to built-in implementation to construct the mapping. |
| 67 |
# This is done before checking for duplicates to leverage existing error checking on the input node. |
| 68 |
mapping = super().construct_mapping(node, deep) |
| 69 |
keys = set() |
| 70 |
|
| 71 |
if self._sensitive_source_data: |
| 72 |
for k, v in mapping.items(): |
| 73 |
if isinstance(v, str): |
| 74 |
register_secret(v) |
| 75 |
elif isinstance(v, (int, float)) and not isinstance(v, bool): |
| 76 |
register_secret(str(v)) |
| 77 |
|
| 78 |
# Now that the node is known to be a valid mapping, handle any duplicate keys. |
| 79 |
for key_node, _value_node in node.value: |
| 80 |
if (key := self.construct_object(key_node, deep=deep)) in keys: |
| 81 |
msg = f'Found duplicate mapping key {key!r}.' |
| 82 |
|
| 83 |
if self._duplicate_key_mode == 'error': |
| 84 |
raise AnsibleConstructorError(problem=msg, problem_mark=key_node.start_mark) |
| 85 |
|
| 86 |
if self._duplicate_key_mode == 'warn': |
| 87 |
display.warning(msg=msg, obj=key, help_text='Using last defined value only.') |
| 88 |
|
| 89 |
keys.add(key) |
| 90 |
|
| 91 |
return mapping |
| 92 |
|
| 93 |
def construct_yaml_int(self, node): |
| 94 |
value = super().construct_yaml_int(node) |
| 95 |
return self._node_position_info(node).tag(value) |
| 96 |
|
| 97 |
def construct_yaml_float(self, node): |
| 98 |
value = super().construct_yaml_float(node) |
| 99 |
return self._node_position_info(node).tag(value) |
| 100 |
|
| 101 |
def construct_yaml_timestamp(self, node): |
| 102 |
value = super().construct_yaml_timestamp(node) |
| 103 |
return self._node_position_info(node).tag(value) |
| 104 |
|
| 105 |
def construct_yaml_omap(self, node): |
| 106 |
origin = self._node_position_info(node) |
| 107 |
display.deprecated( |
| 108 |
msg='Use of the YAML `!!omap` tag is deprecated.', |
| 109 |
version='2.23', |
| 110 |
obj=origin, |
| 111 |
help_text='Use a standard mapping instead, as key order is always preserved.', |
| 112 |
) |
| 113 |
items = list(super().construct_yaml_omap(node))[0] |
| 114 |
items = [origin.tag(item) for item in items] |
| 115 |
yield origin.tag(items) |
| 116 |
|
| 117 |
def construct_yaml_pairs(self, node): |
| 118 |
origin = self._node_position_info(node) |
| 119 |
display.deprecated( |
| 120 |
msg='Use of the YAML `!!pairs` tag is deprecated.', |
| 121 |
version='2.23', |
| 122 |
obj=origin, |
| 123 |
help_text='Use a standard mapping instead.', |
| 124 |
) |
| 125 |
items = list(super().construct_yaml_pairs(node))[0] |
| 126 |
items = [origin.tag(item) for item in items] |
| 127 |
yield origin.tag(items) |
| 128 |
|
| 129 |
def construct_yaml_str(self, node: ScalarNode) -> str: |
| 130 |
# Override the default string handling function |
| 131 |
# to always return unicode objects |
| 132 |
# DTFIX-FUTURE: is this to_text conversion still necessary under Py3? |
| 133 |
value = to_text(self.construct_scalar(node)) |
| 134 |
|
| 135 |
tags: list[AnsibleDatatagBase] = [self._node_position_info(node)] |
| 136 |
|
| 137 |
if self.trusted_as_template: |
| 138 |
# NB: since we're not context aware, this will happily add trust to dictionary keys; this is actually necessary for |
| 139 |
# certain backward compat scenarios, though might be accomplished in other ways if we wanted to avoid trusting keys in |
| 140 |
# the general scenario |
| 141 |
tags.append(_TRUSTED_AS_TEMPLATE) |
| 142 |
|
| 143 |
return AnsibleTagHelper.tag(value, tags) |
| 144 |
|
| 145 |
def construct_yaml_binary(self, node): |
| 146 |
value = super().construct_yaml_binary(node) |
| 147 |
|
| 148 |
return AnsibleTagHelper.tag(value, self._node_position_info(node)) |
| 149 |
|
| 150 |
def construct_yaml_set(self, node): |
| 151 |
data = AnsibleTagHelper.tag(set(), self._node_position_info(node)) |
| 152 |
yield data |
| 153 |
value = self.construct_mapping(node) |
| 154 |
data.update(value) |
| 155 |
|
| 156 |
def construct_yaml_seq(self, node): |
| 157 |
data = self._node_position_info(node).tag([]) |
| 158 |
yield data |
| 159 |
values = self.construct_sequence(node) |
| 160 |
|
| 161 |
if self._sensitive_source_data: |
| 162 |
for v in values: |
| 163 |
if isinstance(v, str): |
| 164 |
register_secret(v) |
| 165 |
elif isinstance(v, (int, float)) and not isinstance(v, bool): |
| 166 |
register_secret(str(v)) |
| 167 |
|
| 168 |
data.extend(values) |
| 169 |
|
| 170 |
def _resolve_and_construct_object(self, node): |
| 171 |
# use a copied node to avoid mutating existing node and tripping the recursion check in construct_object |
| 172 |
copied_node = copy.copy(node) |
| 173 |
# repeat implicit resolution process to determine the proper tag for the value in the unsafe node |
| 174 |
copied_node.tag = t.cast(BaseResolver, self).resolve(type(node), node.value, (True, False)) |
| 175 |
|
| 176 |
# re-entrant call using the correct tag |
| 177 |
# non-deferred construction of hierarchical nodes so the result is a fully realized object, and so our stateful unsafe propagation behavior works |
| 178 |
return self.construct_object(copied_node, deep=True) |
| 179 |
|
| 180 |
def _node_position_info(self, node) -> Origin: |
| 181 |
# the line number where the previous token has ended (plus empty lines) |
| 182 |
# Add one so that the first line is line 1 rather than line 0 |
| 183 |
return self._origin.replace(line_num=node.start_mark.line + self._origin.line_num, col_num=node.start_mark.column + 1) |
| 184 |
|
| 185 |
@classmethod |
| 186 |
def _register_constructors(cls) -> None: |
| 187 |
constructors: dict[str, t.Callable] = { |
| 188 |
'tag:yaml.org,2002:binary': cls.construct_yaml_binary, |
| 189 |
'tag:yaml.org,2002:float': cls.construct_yaml_float, |
| 190 |
'tag:yaml.org,2002:int': cls.construct_yaml_int, |
| 191 |
'tag:yaml.org,2002:map': cls.construct_yaml_map, |
| 192 |
'tag:yaml.org,2002:omap': cls.construct_yaml_omap, |
| 193 |
'tag:yaml.org,2002:pairs': cls.construct_yaml_pairs, |
| 194 |
'tag:yaml.org,2002:python/dict': cls.construct_yaml_map, |
| 195 |
'tag:yaml.org,2002:python/unicode': cls.construct_yaml_str, |
| 196 |
'tag:yaml.org,2002:seq': cls.construct_yaml_seq, |
| 197 |
'tag:yaml.org,2002:set': cls.construct_yaml_set, |
| 198 |
'tag:yaml.org,2002:str': cls.construct_yaml_str, |
| 199 |
'tag:yaml.org,2002:timestamp': cls.construct_yaml_timestamp, |
| 200 |
} |
| 201 |
|
| 202 |
for tag, constructor in constructors.items(): |
| 203 |
cls.add_constructor(tag, constructor) |
| 204 |
|
| 205 |
|
| 206 |
class AnsibleConstructor(AnsibleInstrumentedConstructor): |
| 207 |
"""Ansible constructor which supports Ansible custom behavior such as `Origin` tagging, as well as Ansible-specific YAML tags.""" |
| 208 |
|
| 209 |
def __init__(self, origin: Origin, trusted_as_template: bool, sensitive_source_data: bool = False) -> None: |
| 210 |
self._unsafe_depth = 0 # volatile state var used during recursive construction of a value tagged unsafe |
| 211 |
|
| 212 |
super().__init__(origin=origin, trusted_as_template=trusted_as_template, sensitive_source_data=sensitive_source_data) |
| 213 |
|
| 214 |
@property |
| 215 |
def trusted_as_template(self) -> bool: |
| 216 |
return self._trusted_as_template and not self._unsafe_depth |
| 217 |
|
| 218 |
def construct_yaml_unsafe(self, node): |
| 219 |
self._unsafe_depth += 1 |
| 220 |
|
| 221 |
try: |
| 222 |
return self._resolve_and_construct_object(node) |
| 223 |
finally: |
| 224 |
self._unsafe_depth -= 1 |
| 225 |
|
| 226 |
def construct_yaml_vault(self, node: Node) -> EncryptedString: |
| 227 |
ciphertext = self._resolve_and_construct_object(node) |
| 228 |
|
| 229 |
if not isinstance(ciphertext, str): |
| 230 |
raise AnsibleConstructorError(problem=f"the {node.tag!r} tag requires a string value", problem_mark=node.start_mark) |
| 231 |
|
| 232 |
encrypted_string = AnsibleTagHelper.tag_copy(ciphertext, EncryptedString(ciphertext=AnsibleTagHelper.untag(ciphertext))) |
| 233 |
|
| 234 |
return encrypted_string |
| 235 |
|
| 236 |
def construct_yaml_vault_encrypted(self, node: Node) -> EncryptedString: |
| 237 |
origin = self._node_position_info(node) |
| 238 |
display.deprecated( |
| 239 |
msg='Use of the YAML `!vault-encrypted` tag is deprecated.', |
| 240 |
version='2.23', |
| 241 |
obj=origin, |
| 242 |
help_text='Use the `!vault` tag instead.', |
| 243 |
) |
| 244 |
|
| 245 |
return self.construct_yaml_vault(node) |
| 246 |
|
| 247 |
@classmethod |
| 248 |
def _register_constructors(cls) -> None: |
| 249 |
super()._register_constructors() |
| 250 |
|
| 251 |
constructors: dict[str, t.Callable] = { |
| 252 |
'!unsafe': cls.construct_yaml_unsafe, |
| 253 |
'!vault': cls.construct_yaml_vault, |
| 254 |
'!vault-encrypted': cls.construct_yaml_vault_encrypted, |
| 255 |
} |
| 256 |
|
| 257 |
for tag, constructor in constructors.items(): |
| 258 |
cls.add_constructor(tag, constructor) |