Debian Codegraph @

test/units/_internal/templating/test_jinja_bits.py

raw
1 from __future__ import annotations
2
3 import copy
4 import pathlib
5 import sys
6 import typing as t
7
8 from contextlib import nullcontext
9
10 import pytest
11 import pytest_mock
12
13 from ansible._internal import _display_utils
14 from ansible._internal._templating._access import NotifiableAccessContextBase
15 from ansible.errors import AnsibleUndefinedVariable, AnsibleTemplateError
16 from ansible._internal._templating._errors import AnsibleTemplatePluginRuntimeError
17 from ansible.module_utils._internal._datatag import AnsibleTaggedObject
18 from ansible._internal._templating._jinja_common import CapturedExceptionMarker, MarkerError, Marker, UndefinedMarker
19 from ansible._internal._templating._utils import TemplateContext
20 from ansible._internal._datatag._tags import TrustedAsTemplate
21 from ansible._internal._templating._jinja_bits import (AnsibleEnvironment, TemplateOverrides, _TEMPLATE_OVERRIDE_FIELD_NAMES, defer_template_error,
22 AnsibleTemplate, _BUILTIN_TEST_ALIASES)
23 from ansible._internal._templating import _jinja_plugins
24 from ansible._internal._templating._engine import TemplateEngine, TemplateOptions
25 from jinja2.loaders import DictLoader
26
27 if t.TYPE_CHECKING:
28 import unittest.mock
29
30 TRUST = TrustedAsTemplate()
31
32
33 @pytest.mark.parametrize("template,expected,variables,sources,options", [
34 # no change; non-template data should be ignored
35 (r'c:\newdir', r'c:\newdir', None, None, None),
36 # default behavior always escapes backslashes in string constants in template expressions
37 (r'{{ "c:\newdir" }}', r'c:\newdir', None, None, None),
38 # escaping applies only to string literals in expressions in the current template; includes are never escaped
39 (r'{{ "c:\newdir" }} {% include "foo" %}', r'c:\newdir c:\newdir', None,
40 dict(foo=TRUST.tag(r'{{ "c:\\newdir" }}')), None),
41 # escaping applies only to string literals in expressions in the current template; imports are never escaped
42 (r'{{ "c:\newdir" }} {% import "foo" as foo %}{{ foo.m() }}', r'c:\newdir c:\newdir', None,
43 dict(foo=TRUST.tag(r'{% macro m() %}{{ "c:\\newdir" }}{% endmacro %}')), None),
44 # escape disable only applies to the current template; includes are still never escaped
45 (r'{{ "c:\\newdir" }} {% include "foo" %}', r'c:\newdir c:\newdir', None,
46 dict(foo=TRUST.tag(r'{{ "c:\\newdir" }}')), TemplateOptions(escape_backslashes=False)),
47 # escape disable only applies to the current template; imports are still never escaped
48 (r'{{ "c:\\newdir" }} {% import "foo" as foo %}{{ foo.m() }}', r'c:\newdir c:\newdir', None,
49 dict(foo=TRUST.tag(r'{% macro m() %}{{ "c:\\newdir" }}{% endmacro %}')), TemplateOptions(escape_backslashes=False)),
50 # escaping behavior should not apply to string constants in non-expression blocks (eg, `set`)
51 (r'{% set foo="c:\\newdir" %}{{ foo }}', r'c:\newdir', None, None, None),
52 # default behavior escapes indirect templates
53 (r'{{ indirect }}', r'c:\newdir', dict(indirect=TRUST.tag(r'{{ "c:\newdir" }}')), None, None),
54 # disable does *not* propagate to indirect template rendering
55 (r'{{ "c:\\newdir" }} {{ indirect }}', r'c:\newdir c:\newdir',
56 dict(indirect=TRUST.tag(r'{{ "c:\newdir" }}')), None, TemplateOptions(escape_backslashes=False)),
57 # default escaping works on input containers
58 (dict(key=TRUST.tag(r'{{ "c:\newdir" }}')), dict(key=r'c:\newdir'), None, None, None),
59 # disable only applies to string templar inputs; templates in containers are always escaped
60 (dict(key=TRUST.tag(r'{{ "c:\newdir" }}')), dict(key=r'c:\newdir'), None, None, TemplateOptions(escape_backslashes=False)),
61
62 ])
63 def test_escape_backslashes(template: t.Any, expected: t.Any, variables: dict[str, t.Any], sources: dict[str, str], options: TemplateOptions | None) -> None:
64 template = TRUST.tag(template)
65
66 templar = TemplateEngine(loader=None, variables=variables)
67 templar.environment.loader = DictLoader(sources or {})
68
69 if options is None:
70 options = TemplateOptions.DEFAULT
71
72 assert templar.template(template, options=options) == expected
73
74
75 def test_templatemodule_ignore(template_context):
76 """Ensure that `TemplateModule` silently passes through try_create()."""
77 template = TRUST.tag('{% import "foo" as foo %}{{ foo }}')
78
79 templar = TemplateEngine()
80 templar.environment.loader = DictLoader(dict(foo=TRUST.tag('{{ undefined_in_import }}')))
81
82 with _display_utils.DeferredWarningContext(variables=templar.available_variables) as warnings:
83 result = templar.template(template)
84
85 assert not warnings.get_warnings()
86 assert isinstance(result, UndefinedMarker)
87
88
89 @pytest.mark.xfail(reason="template local propagation to nested templar calls is not implemented")
90 def test_context_local_propagation():
91 trusted = TrustedAsTemplate()
92 trusted_scalar = trusted.tag("{{ hi_from }}")
93 play_vars = dict(
94 hi_from="play var",
95 templated_scalar=trusted_scalar,
96 templated_dict=dict(
97 templated_scalar=trusted_scalar,
98 ),
99 )
100 templar = TemplateEngine(loader=None, variables=play_vars)
101
102 # shared template fragment that we'll use both directly and in an imported template
103 validate_me = "[hi_from, templated_scalar, templated_dict.templated_scalar, templated_dict]"
104
105 # Imports are one of the rare cases where Jinja calls (Ansible)Template.new_context() itself and directly consumes/concats the results; need to ensure
106 # that whatever solution gets implemented can handle that case as well (since it's easier to handle the cases where we own the new_context call).
107 templar.environment.loader = DictLoader(dict(importme=trusted.tag(
108 "{% set hi_from='imported template local' %}"
109 "{% macro validate_this() %}"
110 "{{ " + validate_me + " }}"
111 "{% endmacro %}"
112 )))
113
114 # The template-local variable hi_from should mask the one passed in; it currently does not whenever a nested template call is made, because template locals
115 # are only available in AnsibleContext.vars, and Jinja's getattr and getitem are implemented on (Ansible)Environment, which are context-agnostic. We're
116 # hopeful this could be supported by Jinja in the future, at which point we can implement template-local var propagation to nested Templars/template calls.
117 # The getitem/getattr calls would need to be implemented on (Ansible)Context, or otherwise gain the ability to consult the context vars to safely
118 # propagate locals. A ContextVar is insufficient to handle this problem with a new context, since the possibility of overlapping contexts from
119 # abandoned-but-not-closed generators is real. PEP568 would solve this problem, if it's ever implemented...
120 res = templar.template(trusted.tag(
121 "{% set hi_from='template local' %}"
122 "{% from 'importme' import validate_this with context %}"
123 "{{ " + validate_me + " + validate_this() }}"
124 ))
125
126 assert res == [
127 "template local",
128 "template local",
129 "template local",
130 dict(templated_scalar="template local"),
131 "imported template local",
132 "template local",
133 "template local",
134 dict(templated_scalar="template local"),
135 ]
136
137
138 @pytest.mark.parametrize("key", _TEMPLATE_OVERRIDE_FIELD_NAMES)
139 def test_template_overrides_defaults(key: str) -> None:
140 overrides = TemplateOverrides()
141 env = AnsibleEnvironment()
142
143 assert getattr(overrides, key) == getattr(env, key)
144
145
146 @pytest.mark.parametrize("value, expected_overrides", [
147 ("#jinja2:newline_sequence:'\\r\\n'\n", TemplateOverrides(newline_sequence='\r\n')),
148 ("#jinja2:trim_blocks:False\n", TemplateOverrides(trim_blocks=False)),
149 ("#jinja2:line_statement_prefix:None\n{{'template constant'}}\n{{'another'}}\n", TemplateOverrides.DEFAULT),
150 ("#jinja2:line_statement_prefix:'!!'\n{{'template constant'}}\n{{'another'}}\n", TemplateOverrides(line_statement_prefix="!!")),
151 ], ids=lambda value: repr(value.overlay_kwargs() if isinstance(value, TemplateOverrides) else value))
152 def test_template_override_extract_success(value: str, expected_overrides: TemplateOverrides):
153 expected_template = value.split('\n', maxsplit=1)[1]
154 template, overrides = TemplateOverrides.DEFAULT._extract_template_overrides(value)
155
156 assert template == expected_template
157 assert overrides == expected_overrides
158
159
160 @pytest.mark.parametrize("value", [
161 "#jinja2:newline_sequence:'\\n\\r'\n",
162 "#jinja2:bogus_key:''\n",
163 "#jinja2:variable_start_string:2\n",
164 "#jinja2:variable_start_string:'{{'",
165 "#jinja2:variable_start_string\n",
166 "#jinja2:\n",
167 "#jinja2:,\n",
168 "#jinja2:variable_start_string:'boo',\n",
169 ])
170 def test_template_override_extract_failure(value: str):
171 with pytest.raises(tuple([TypeError, ValueError])):
172 TemplateOverrides.DEFAULT._extract_template_overrides(value)
173
174
175 def test_filter_plugin_error_wrap():
176 expected_error_cause = Exception("bang")
177
178 def raises_error(_input):
179 raise expected_error_cause
180
181 templar = TemplateEngine()
182 templar.environment.filters['raises_error'] = raises_error
183
184 with pytest.raises(AnsibleTemplatePluginRuntimeError) as err:
185 templar.template(TRUST.tag("{{ true | raises_error }}"))
186
187 assert err.value.__cause__ is expected_error_cause
188
189
190 def test_test_plugin_error_wrap():
191 expected_error_cause = Exception("bang")
192
193 def raises_error(_input):
194 raise expected_error_cause
195
196 templar = TemplateEngine()
197 templar.environment.tests['raises_error'] = raises_error
198
199 with pytest.raises(AnsibleTemplatePluginRuntimeError) as err:
200 templar.template(TRUST.tag("{{ true is raises_error }}"))
201
202 assert err.value.__cause__ is expected_error_cause
203
204
205 def test_lookup_plugin_error_wrap(mocker: pytest_mock.MockerFixture):
206 expected_error_cause = Exception("bang")
207
208 from ansible.plugins.lookup import LookupBase
209
210 class RaisesError(LookupBase):
211 def run(self, _input, *args, **kwargs):
212 raise expected_error_cause
213
214 def mock_lookup_get(name, *args, **kwargs) -> t.Any:
215 return RaisesError()
216
217 templar = TemplateEngine()
218 mock_lookup_loader = mocker.MagicMock()
219 mock_lookup_loader.get = mock_lookup_get
220
221 mocker.patch.object(_jinja_plugins, 'lookup_loader', mock_lookup_loader)
222
223 with pytest.raises(AnsibleTemplatePluginRuntimeError) as err:
224 templar.template(TRUST.tag("{{ lookup('raises_error') }}"))
225
226 assert err.value.__cause__ is expected_error_cause
227
228
229 ok = "ok"
230 undefined_with_unsafe = AnsibleUndefinedVariable("is unsafe")
231
232
233 @pytest.mark.parametrize("expr, expected", (
234 ('on_dict["_native_copy"]', ok), # [] prefers getitem, matching dict key present (no attr lookup)
235 ('on_dict._native_copy', ok), # . matches `_` prefixed` method on _AnsibleTaggedDict, custom fallback to getitem with valid key
236 ('on_dict["get"]', ok), # [] prefers getitem, matching dict key present (no attr lookup)
237 ('on_dict.get("_native_copy")', ok), # . matches safe method on dict, should be callable to fetch a valid key
238 ('on_dict["clear"]', ok), # [] prefers getitem, matching dict key present (no attr lookup)
239 ('on_dict["_non_method_or_attr"]', ok), # [] prefers getitem, sunder key ok
240 ('on_dict._non_method_or_attr', ok), # . finds nothing, getattr fallback finds dict key, `_` prefix has no effect
241 ('on_list._native_copy', undefined_with_unsafe), # . matches sunder-named method on list, fails
242 ('on_list["_native_copy"]', undefined_with_unsafe), # [] gets TypeError, getattr fallback matches sunder-named method on list, fails
243 ('on_list.0', 42), # . gets AttributeError, getitem fallback succeeds
244 ('on_list[0]', 42), # [] prefers getitem, succeeds
245 # -- Jinja mutable method sandbox test cases follow; if sandbox is re-enabled, the correct behavior is defined by the commented value below
246 ('on_dict.clear | type_debug', 'builtin_function_or_method'),
247 # ('on_dict.clear', ok), # . matches known-mutating method on _AnsibleTaggedDict, custom fallback to getitem with valid key
248 ('on_dict["setdefault"] | type_debug', 'method'),
249 # ('on_dict.setdefault', undefined_with_unsafe), # . finds a known-mutating method, getitem fallback finds no matching dict key, fails
250 ('on_list.sort | type_debug', 'method'),
251 # ('on_list.sort', undefined_with_unsafe), # . matches known-mutating method on list, fails
252 ('on_list["sort"] | type_debug', 'method'),
253 # ('on_list["sort"]', undefined_with_unsafe), # [] gets TypeError, getattr fallback matches known-mutating method on list, fails
254 ))
255 def test_jinja_getattr(expr: str, expected: object) -> None:
256 """Validate expected behavior from Jinja environment getattr/getitem methods, including Ansible-customized fallback behavior."""
257 assert AnsibleTaggedObject._native_copy # validate that the underlying type has the method we're expecting to collide with
258
259 templar = TemplateEngine(variables=dict(
260 on_dict=dict(
261 _native_copy=ok, # same key as sunder method
262 get=ok, # same key as a safe method
263 clear=ok, # same key as an unsafe method
264 _non_method_or_attr=ok, # key with sunder prefix, no matching method
265 ),
266 on_list=[42],
267 ))
268
269 with (pytest.raises(type(expected), match=expected.message) if isinstance(expected, AnsibleUndefinedVariable) else nullcontext()):
270 result = templar.evaluate_expression(TRUST.tag(expr))
271 assert result == expected
272
273
274 def test_defer_template_error_from_marker(marker: Marker) -> None:
275 """Verify that deferring a Marker returns its source."""
276 with pytest.raises(MarkerError) as error:
277 raise MarkerError('', marker)
278
279 result = defer_template_error(error.value, None, is_expression=False)
280
281 assert result is marker
282
283
284 def test_defer_template_error_from_exception(template_context: TemplateContext) -> None:
285 """Verify that deferring an Exception not derived from AnsibleTemplateError returns a CapturedExceptionMarker wrapping an AnsibleTemplateError."""
286 with pytest.raises(Exception) as error:
287 raise Exception()
288
289 result = defer_template_error(error.value, None, is_expression=False)
290
291 assert isinstance(result, CapturedExceptionMarker)
292 assert isinstance(result._marker_captured_exception, AnsibleTemplateError)
293 assert result._marker_captured_exception.__cause__ is error.value
294
295
296 def test_defer_template_error_from_ansible_template_error(template_context: TemplateContext) -> None:
297 """Verify that deferring an AnsibleTemplateError returns a CapturedExceptionMarker wrapping that exception."""
298 with pytest.raises(AnsibleTemplateError) as error:
299 raise AnsibleTemplateError()
300
301 result = defer_template_error(error.value, None, is_expression=False)
302
303 assert isinstance(result, CapturedExceptionMarker)
304 assert result._marker_captured_exception is error.value
305
306
307 def test_defer_template_requires_traceback(template_context: TemplateContext):
308 """Verify that deferring an exception that has not been raised results in an AssertionError."""
309 with pytest.raises(AssertionError, match='ex must be a previously raised exception'):
310 # an exception without a traceback should be rejected with an AssertionError
311 defer_template_error(AnsibleTemplateError(), None, is_expression=False)
312
313
314 @pytest.fixture
315 def mock_breakpointhook(mocker: pytest_mock.MockerFixture) -> t.Iterator[unittest.mock.Mock]:
316 """Yields a Mock object patched on `sys.breakpointhook` (causes explicit `breakpoint()` calls to no-op)."""
317 breakpointhook = mocker.Mock()
318
319 mocker.patch.object(sys, 'breakpointhook', breakpointhook)
320
321 yield breakpointhook
322
323
324 @pytest.fixture(params=(True, False))
325 def debuggable_templar(request: pytest.FixtureRequest, tmp_path: pathlib.Path) -> TemplateEngine:
326 """Multiplying parameterized fixture that yields a Templar with template source debugging force-enabled and force-disabled."""
327 templar = TemplateEngine()
328
329 env = templar.environment
330 env._debuggable_template_source = request.param
331 env._debuggable_template_source_path = tmp_path
332
333 return templar
334
335
336 @pytest.mark.parametrize("expression", (
337 'templar.environment.get_template("importme")',
338 'templar.environment.from_string("{{ 42 }}")',
339 'templar.environment.compile_expression("42")._template',
340 ))
341 def test_template_source_debug(expression: str, debuggable_templar: TemplateEngine, mock_breakpointhook: unittest.mock.Mock):
342 """Ensures that template source debug support creates source files and sets debugger support attributes correctly."""
343 debuggable_templar.environment.loader = DictLoader(dict(importme=TRUST.tag('{{ 42 }}')))
344
345 template: AnsibleTemplate = eval(expression, globals(), dict(templar=debuggable_templar))
346
347 debug_enabled = debuggable_templar.environment._debuggable_template_source
348
349 if debug_enabled:
350 assert template.root_render_func.__code__.co_filename == template.filename
351 assert pathlib.Path(template.filename).exists()
352 else:
353 assert template.filename == '<template>'
354
355 assert mock_breakpointhook.called == debug_enabled
356
357
358 @pytest.mark.parametrize("kwargs, expected", (
359 ({}, TemplateOverrides.DEFAULT),
360 (dict(variable_start_string="{{"), TemplateOverrides.DEFAULT),
361 (dict(variable_start_string="!!"), TemplateOverrides(variable_start_string="!!")),
362 ), ids=lambda arg: str(arg) if isinstance(arg, dict) else "TemplateOverrides")
363 def test_template_overrides_from_kwargs(kwargs: dict[str, t.Any], expected: TemplateOverrides) -> None:
364 result = TemplateOverrides.from_kwargs(kwargs)
365
366 if expected is TemplateOverrides.DEFAULT:
367 assert result is expected
368 else:
369 assert result == expected
370
371
372 @pytest.mark.parametrize("name", _BUILTIN_TEST_ALIASES)
373 def test_builtin_alt_names(name: str) -> None:
374 """Verify that Jinja2 plugin alternate names are valid."""
375 tests = AnsibleEnvironment.__mro__[1]().tests
376 alt_name = _BUILTIN_TEST_ALIASES[name]
377
378 assert tests[name] is tests[alt_name]
379
380
381 @pytest.mark.parametrize("template,variables,expected", (
382 # macro getting an undefined from a getitem should continue execution
383 (
384 "{{ macro_user('badkey') }}",
385 dict(data={}, macro_user=TRUST.tag("{% macro a_macro(a_key) %}{{ data[a_key] | default('thedefault') }}{% endmacro %}{{ a_macro }}")),
386 "thedefault",
387 ),
388 # call block getting an undefined from a getitem should continue execution
389 (
390 "{% macro a_macro() %}it was {{ caller() }}{% endmacro %}{% call a_macro() %}{{ data['nope'] | default('thedefault') }}{% endcall %}",
391 dict(data={}),
392 "it was thedefault",
393 ),
394 # macro receiving an undefined arg should always execute
395 (
396 "{{ macro_user(an_undefined_var) }}",
397 dict(data={}, macro_user=TRUST.tag("{% macro a_macro(value) %}{{ value | default('thedefault') }}{% endmacro %}{{ a_macro }}")),
398 "thedefault",
399 ),
400 ))
401 def test_macro_marker_handling(template: str, variables: dict[str, object], expected: object) -> None:
402 """
403 Ensure that `JinjaCallContext` Marker handling is masked/set correctly for Jinja macro callables.
404 Jinja's generated macro code handles Markers, so preemptive raise on retrieval should be disabled for the macro `call()`.
405 """
406 res = TemplateEngine(variables=variables).template(TRUST.tag(template))
407
408 assert res == expected
409
410
411 @pytest.mark.parametrize("expression, result", (
412 ("(0x20).__or__(0xf)", 47),
413 ("(0x20).__and__(0x29)", 32),
414 ("(0x20).__lshift__(1)", 64),
415 ("(0x20).__rshift__(1)", 16),
416 ("(0x20).__xor__(0x29)", 9),
417 ))
418 def test_bitwise_dunder_methods(expression: str, result: object) -> None:
419 """
420 Verify a limited set of dunder methods are supported.
421 This feature may be deprecated and removed in the future after bitwise filters are implemented.
422 """
423 assert TemplateEngine().evaluate_expression(TRUST.tag(expression)) == result
424
425
426 @pytest.mark.parametrize("expression", (
427 "{1:2}.__delitem__(1)",
428 "[123].__len__()",
429 ))
430 def test_disallowed_dunder_methods(expression: str) -> None:
431 """Verify dunder methods are disallowed by the Jinja sandbox."""
432 with pytest.raises(AnsibleUndefinedVariable, match="is unsafe"):
433 TemplateEngine().evaluate_expression(TRUST.tag(expression))
434
435
436 @pytest.mark.parametrize("template, result", (
437 ("{% set my_list = [] %}{% set _ = my_list.append(1) %}{{ my_list }}", [1]),
438 ("{% set my_list = [] %}{% set _ = my_list.extend([1, 2]) %}{{ my_list }}", [1, 2]),
439 ("{% set my_dict = {} %}{% set _ = my_dict.update(a=1) %}{{ my_dict }}", dict(a=1)),
440 ))
441 def test_mutation_methods(template: str, result: object) -> None:
442 """
443 Verify mutation methods are allowed by the Jinja sandbox.
444 This feature may be deprecated and removed in a future release by using Jinja's ImmutableSandboxedEnvironment.
445 """
446 assert TemplateEngine().template(TRUST.tag(template)) == result
447
448
449 class ExampleMarkerAccessTracker(NotifiableAccessContextBase):
450 def __init__(self) -> None:
451 self._type_interest = frozenset(Marker._concrete_subclasses)
452 self._markers: list[Marker] = []
453
454 def _notify(self, o: Marker) -> None:
455 self._markers.append(o)
456
457
458 @pytest.mark.parametrize("template", (
459 '{{ adict["bogus"] | default("ok") }}',
460 '{{ adict.bogus | default("ok") }}',
461 ))
462 def test_marker_access_getattr_and_getitem(template: str) -> None:
463 """Ensure that getattr and getitem always access markers."""
464 # the absence of a JinjaCallContext should cause the access done by getattr and getitem not to trip when a marker is encountered
465 assert TemplateEngine(variables=dict(adict={})).template(TRUST.tag(template)) == "ok"
466
467 with ExampleMarkerAccessTracker() as tracker: # the access done by getattr and getitem should immediately trip when a marker is encountered
468 TemplateEngine(variables=dict(adict={})).template(TRUST.tag(template))
469
470 assert type(tracker._markers[0]) is UndefinedMarker # pylint: disable=unidiomatic-typecheck
471
472
473 def test_ansible_template_deepcopy() -> None:
474 """Ensure that AnsibleTemplate instances return themselves when a deep copy is made."""
475 template = AnsibleEnvironment().from_string("Hello")
476 deep_copy = copy.deepcopy(template)
477
478 assert deep_copy is template