| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import abc |
| 4 |
import collections.abc as c |
| 5 |
import enum |
| 6 |
import inspect |
| 7 |
import itertools |
| 8 |
import typing as t |
| 9 |
|
| 10 |
from jinja2 import UndefinedError, StrictUndefined, TemplateRuntimeError |
| 11 |
from jinja2.utils import missing |
| 12 |
|
| 13 |
from ...module_utils._internal import _messages |
| 14 |
from ansible.constants import config |
| 15 |
from ansible.errors import AnsibleUndefinedVariable, AnsibleTypeError |
| 16 |
from ansible._internal._errors._handler import ErrorHandler |
| 17 |
from ansible.module_utils._internal._datatag import Tripwire, _untaggable_types |
| 18 |
|
| 19 |
from ._access import NotifiableAccessContextBase |
| 20 |
from ._jinja_patches import _patch_jinja |
| 21 |
from ._utils import TemplateContext |
| 22 |
from .._errors import _captured |
| 23 |
from ...module_utils.datatag import native_type_name |
| 24 |
|
| 25 |
_patch_jinja() # apply Jinja2 patches before types are declared that are dependent on the changes |
| 26 |
|
| 27 |
|
| 28 |
class _SandboxMode(enum.Enum): |
| 29 |
DEFAULT = enum.auto() |
| 30 |
ALLOW_UNSAFE_ATTRIBUTES = enum.auto() |
| 31 |
|
| 32 |
|
| 33 |
class _TemplateConfig: |
| 34 |
allow_embedded_templates: bool = config.get_config_value("ALLOW_EMBEDDED_TEMPLATES") |
| 35 |
allow_broken_conditionals: bool = config.get_config_value('ALLOW_BROKEN_CONDITIONALS') |
| 36 |
jinja_extensions: list[str] = config.get_config_value('DEFAULT_JINJA2_EXTENSIONS') |
| 37 |
sandbox_mode: _SandboxMode = _SandboxMode.__members__[config.get_config_value('_TEMPLAR_SANDBOX_MODE').upper()] |
| 38 |
|
| 39 |
unknown_type_encountered_handler = ErrorHandler.from_config('_TEMPLAR_UNKNOWN_TYPE_ENCOUNTERED') |
| 40 |
unknown_type_conversion_handler = ErrorHandler.from_config('_TEMPLAR_UNKNOWN_TYPE_CONVERSION') |
| 41 |
untrusted_template_handler = ErrorHandler.from_config('_TEMPLAR_UNTRUSTED_TEMPLATE_BEHAVIOR') |
| 42 |
|
| 43 |
|
| 44 |
class MarkerError(UndefinedError): |
| 45 |
""" |
| 46 |
An Ansible specific subclass of Jinja's UndefinedError, used to preserve and later restore the original Marker instance that raised the error. |
| 47 |
This error is only raised by Marker and should never escape the templating system. |
| 48 |
""" |
| 49 |
|
| 50 |
def __init__(self, message: str, source: Marker) -> None: |
| 51 |
super().__init__(message) |
| 52 |
|
| 53 |
self.source = source |
| 54 |
|
| 55 |
|
| 56 |
class Marker(StrictUndefined, Tripwire): |
| 57 |
""" |
| 58 |
Extends Jinja's `StrictUndefined`, allowing any kind of error occurring during recursive templating operations to be captured and deferred. |
| 59 |
Direct or managed access to most `Marker` attributes will raise a `MarkerError`, which usually ends the current innermost templating |
| 60 |
operation and converts the `MarkerError` back to the origin Marker instance (subject to the `MarkerBehavior` in effect at the time). |
| 61 |
""" |
| 62 |
|
| 63 |
__slots__ = ('_marker_template_source',) |
| 64 |
|
| 65 |
_concrete_subclasses: t.ClassVar[set[type[Marker]]] = set() |
| 66 |
|
| 67 |
def __init__( |
| 68 |
self, |
| 69 |
hint: t.Optional[str] = None, |
| 70 |
obj: t.Any = missing, |
| 71 |
name: t.Optional[str] = None, |
| 72 |
exc: t.Type[TemplateRuntimeError] = UndefinedError, # Ansible doesn't set this argument or consume the attribute it is stored under. |
| 73 |
*args, |
| 74 |
_no_template_source=False, |
| 75 |
**kwargs, |
| 76 |
) -> None: |
| 77 |
if not hint and name and obj is not missing: |
| 78 |
hint = f"object of type {native_type_name(obj)!r} has no attribute {name!r}" |
| 79 |
|
| 80 |
kwargs.update( |
| 81 |
hint=hint, |
| 82 |
obj=obj, |
| 83 |
name=name, |
| 84 |
exc=exc, |
| 85 |
) |
| 86 |
|
| 87 |
super().__init__(*args, **kwargs) |
| 88 |
|
| 89 |
if _no_template_source: |
| 90 |
self._marker_template_source = None |
| 91 |
else: |
| 92 |
self._marker_template_source = TemplateContext.current().template_value |
| 93 |
|
| 94 |
def _as_exception(self) -> Exception: |
| 95 |
"""Return the exception instance to raise in a top-level templating context.""" |
| 96 |
return AnsibleUndefinedVariable(self._undefined_message, obj=self._marker_template_source) |
| 97 |
|
| 98 |
def _as_message(self) -> str: |
| 99 |
"""Return the error message to show when this marker must be represented as a string, such as for substitutions or warnings.""" |
| 100 |
return self._undefined_message |
| 101 |
|
| 102 |
def _fail_with_undefined_error(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn: |
| 103 |
"""Ansible-specific replacement for Jinja's _fail_with_undefined_error tripwire on dunder methods.""" |
| 104 |
self.trip() |
| 105 |
|
| 106 |
def trip(self) -> t.NoReturn: |
| 107 |
"""Raise an internal exception which can be converted back to this instance.""" |
| 108 |
raise MarkerError(self._undefined_message, self) |
| 109 |
|
| 110 |
def __setattr__(self, name: str, value: t.Any) -> None: |
| 111 |
""" |
| 112 |
Any attempt to set an unknown attribute on a `Marker` should invoke the trip method to propagate the original context. |
| 113 |
This does not protect against mutation of known attributes, but the implementation is fairly simple. |
| 114 |
""" |
| 115 |
try: |
| 116 |
super().__setattr__(name, value) |
| 117 |
except AttributeError: |
| 118 |
pass |
| 119 |
else: |
| 120 |
return |
| 121 |
|
| 122 |
self.trip() |
| 123 |
|
| 124 |
def __getattr__(self, name: str) -> t.Any: |
| 125 |
"""Raises AttributeError for dunder-looking accesses, self-propagates otherwise.""" |
| 126 |
if name.startswith('__') and name.endswith('__'): |
| 127 |
raise AttributeError(name) |
| 128 |
|
| 129 |
return self |
| 130 |
|
| 131 |
def __getitem__(self, key): |
| 132 |
"""Self-propagates on all item accesses.""" |
| 133 |
return self |
| 134 |
|
| 135 |
@classmethod |
| 136 |
def __init_subclass__(cls, **kwargs) -> None: |
| 137 |
if not inspect.isabstract(cls): |
| 138 |
_untaggable_types.add(cls) |
| 139 |
cls._concrete_subclasses.add(cls) |
| 140 |
|
| 141 |
@classmethod |
| 142 |
def _init_class(cls): |
| 143 |
_untaggable_types.add(cls) |
| 144 |
|
| 145 |
# These are the methods StrictUndefined already intercepts. |
| 146 |
jinja_method_names = ( |
| 147 |
'__add__', |
| 148 |
'__bool__', |
| 149 |
'__call__', |
| 150 |
'__complex__', |
| 151 |
'__contains__', |
| 152 |
'__div__', |
| 153 |
'__eq__', |
| 154 |
'__float__', |
| 155 |
'__floordiv__', |
| 156 |
'__ge__', |
| 157 |
# '__getitem__', # using a custom implementation that propagates self instead |
| 158 |
'__gt__', |
| 159 |
'__hash__', |
| 160 |
'__int__', |
| 161 |
'__iter__', |
| 162 |
'__le__', |
| 163 |
'__len__', |
| 164 |
'__lt__', |
| 165 |
'__mod__', |
| 166 |
'__mul__', |
| 167 |
'__ne__', |
| 168 |
'__neg__', |
| 169 |
'__pos__', |
| 170 |
'__pow__', |
| 171 |
'__radd__', |
| 172 |
'__rdiv__', |
| 173 |
'__rfloordiv__', |
| 174 |
'__rmod__', |
| 175 |
'__rmul__', |
| 176 |
'__rpow__', |
| 177 |
'__rsub__', |
| 178 |
'__rtruediv__', |
| 179 |
'__str__', |
| 180 |
'__sub__', |
| 181 |
'__truediv__', |
| 182 |
) |
| 183 |
|
| 184 |
# These additional methods should be intercepted, even though they are not intercepted by StrictUndefined. |
| 185 |
additional_method_names = ( |
| 186 |
'__aiter__', |
| 187 |
'__delattr__', |
| 188 |
'__format__', |
| 189 |
'__repr__', |
| 190 |
'__setitem__', |
| 191 |
) |
| 192 |
|
| 193 |
for name in jinja_method_names + additional_method_names: |
| 194 |
setattr(cls, name, cls._fail_with_undefined_error) |
| 195 |
|
| 196 |
|
| 197 |
Marker._init_class() |
| 198 |
|
| 199 |
|
| 200 |
class TruncationMarker(Marker): |
| 201 |
""" |
| 202 |
An `Marker` value was previously encountered and reported. |
| 203 |
A subsequent `Marker` value (this instance) indicates the template may have been truncated as a result. |
| 204 |
It will only be visible if the previous `Marker` was ignored/replaced instead of being tripped, which would raise an exception. |
| 205 |
""" |
| 206 |
|
| 207 |
__slots__ = () |
| 208 |
|
| 209 |
def __init__(self) -> None: |
| 210 |
super().__init__(hint='template potentially truncated') |
| 211 |
|
| 212 |
|
| 213 |
class UndefinedMarker(Marker): |
| 214 |
"""A `Marker` value that represents an undefined value encountered during templating.""" |
| 215 |
|
| 216 |
__slots__ = () |
| 217 |
|
| 218 |
|
| 219 |
class ExceptionMarker(Marker, metaclass=abc.ABCMeta): |
| 220 |
"""Base `Marker` class that represents exceptions encountered and deferred during templating.""" |
| 221 |
|
| 222 |
__slots__ = () |
| 223 |
|
| 224 |
@abc.abstractmethod |
| 225 |
def _as_exception(self) -> Exception: |
| 226 |
pass |
| 227 |
|
| 228 |
def _as_message(self) -> str: |
| 229 |
return str(self._as_exception()) |
| 230 |
|
| 231 |
def trip(self) -> t.NoReturn: |
| 232 |
"""Raise an internal exception which can be converted back to this instance while maintaining the cause for callers that follow them.""" |
| 233 |
raise MarkerError(self._undefined_message, self) from self._as_exception() |
| 234 |
|
| 235 |
|
| 236 |
class CapturedExceptionMarker(ExceptionMarker): |
| 237 |
"""A `Marker` value that represents an exception raised during templating.""" |
| 238 |
|
| 239 |
__slots__ = ('_marker_captured_exception',) |
| 240 |
|
| 241 |
def __init__(self, exception: Exception) -> None: |
| 242 |
super().__init__(hint=f'A captured exception marker was tripped: {exception}') |
| 243 |
|
| 244 |
self._marker_captured_exception = exception |
| 245 |
|
| 246 |
def _as_exception(self) -> Exception: |
| 247 |
return self._marker_captured_exception |
| 248 |
|
| 249 |
|
| 250 |
class UndecryptableVaultError(_captured.AnsibleCapturedError): |
| 251 |
"""Template-external error raised by VaultExceptionMarker when an undecryptable variable is accessed.""" |
| 252 |
|
| 253 |
context = 'vault' |
| 254 |
_default_message = "Attempt to use undecryptable variable." |
| 255 |
|
| 256 |
|
| 257 |
class VaultExceptionMarker(ExceptionMarker): |
| 258 |
"""A `Marker` value that represents an error accessing a vaulted value during templating.""" |
| 259 |
|
| 260 |
__slots__ = ('_marker_undecryptable_ciphertext', '_marker_event') |
| 261 |
|
| 262 |
def __init__(self, ciphertext: str, event: _messages.Event) -> None: |
| 263 |
super().__init__(hint='A vault exception marker was tripped.') |
| 264 |
|
| 265 |
self._marker_undecryptable_ciphertext = ciphertext |
| 266 |
self._marker_event = event |
| 267 |
|
| 268 |
def _as_exception(self) -> Exception: |
| 269 |
return UndecryptableVaultError( |
| 270 |
obj=self._marker_undecryptable_ciphertext, |
| 271 |
event=self._marker_event, |
| 272 |
) |
| 273 |
|
| 274 |
def _disarm(self) -> str: |
| 275 |
return self._marker_undecryptable_ciphertext |
| 276 |
|
| 277 |
|
| 278 |
def get_first_marker_arg(args: c.Sequence, kwargs: dict[str, t.Any]) -> Marker | None: |
| 279 |
"""Utility method to inspect plugin args and return the first `Marker` encountered, otherwise `None`.""" |
| 280 |
# CAUTION: This function is exposed in public API as ansible.template.get_first_marker_arg. |
| 281 |
return next(iter_marker_args(args, kwargs), None) |
| 282 |
|
| 283 |
|
| 284 |
def iter_marker_args(args: c.Sequence, kwargs: dict[str, t.Any]) -> t.Generator[Marker]: |
| 285 |
"""Utility method to iterate plugin args and yield any `Marker` encountered.""" |
| 286 |
for arg in itertools.chain(args, kwargs.values()): |
| 287 |
if isinstance(arg, Marker): |
| 288 |
yield arg |
| 289 |
|
| 290 |
|
| 291 |
class JinjaCallContext(NotifiableAccessContextBase): |
| 292 |
""" |
| 293 |
An audit context that wraps all Jinja (template/filter/test/lookup/method/function) calls. |
| 294 |
While active, calls `trip()` on managed access of `Marker` objects unless the callee declares an understanding of markers. |
| 295 |
""" |
| 296 |
|
| 297 |
_mask = True |
| 298 |
|
| 299 |
def __init__(self, accept_lazy_markers: bool) -> None: |
| 300 |
self._type_interest = frozenset() if accept_lazy_markers else frozenset(Marker._concrete_subclasses) |
| 301 |
|
| 302 |
def _notify(self, o: Marker) -> t.NoReturn: |
| 303 |
o.trip() |
| 304 |
|
| 305 |
|
| 306 |
# TODO: see if we can make this a proper generic signature |
| 307 |
def validate_arg_type(name: str, value: t.Any, allowed_type_or_types: type | tuple[type, ...], /) -> t.Any: |
| 308 |
"""Validate the type of the given argument while preserving context for Marker values.""" |
| 309 |
# DTFIX-FUTURE: find a home for this as a general-purpose utliity method and expose it after some API review |
| 310 |
if isinstance(value, allowed_type_or_types): |
| 311 |
return value |
| 312 |
|
| 313 |
if isinstance(allowed_type_or_types, type): |
| 314 |
arg_type_description = repr(native_type_name(allowed_type_or_types)) |
| 315 |
else: |
| 316 |
arg_type_description = ' or '.join(repr(native_type_name(item)) for item in allowed_type_or_types) |
| 317 |
|
| 318 |
if isinstance(value, Marker): |
| 319 |
try: |
| 320 |
value.trip() |
| 321 |
except Exception as ex: |
| 322 |
raise AnsibleTypeError(f"The {name!r} argument must be of type {arg_type_description}.", obj=value) from ex |
| 323 |
|
| 324 |
raise AnsibleTypeError(f"The {name!r} argument must be of type {arg_type_description}, not {native_type_name(value)!r}.", obj=value) |