From 56a724644b1ad9cb03745c10cca732715cdc79e9 Mon Sep 17 00:00:00 2001 From: Sigurd Spieckermann Date: Fri, 26 May 2023 14:32:36 +0200 Subject: [PATCH] fix f-string syntax error in code generation Reference:https://github.com/pallets/jinja/commit/56a724644b1ad9cb03745c10cca732715cdc79e9 --- Jinja2-2.11.2/CHANGES.rst | 3 +++ Jinja2-2.11.2/src/jinja2/compiler.py | 7 ++++++- Jinja2-2.11.2/tests/test_compile.py | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 Jinja2-2.11.2/tests/test_compile.py diff --git a/Jinja2-2.11.2/CHANGES.rst b/Jinja2-2.11.2/CHANGES.rst index 2c7614b..6ef2d3d 100644 --- a/Jinja2-2.11.2/CHANGES.rst +++ b/Jinja2-2.11.2/CHANGES.rst @@ -1,5 +1,8 @@ .. currentmodule:: jinja2 +- Escape template name before formatting it into error messages, to avoid + issues with names that contain f-string syntax. + :issue:`1792`, :ghsa:`gmj6-6f8f-6699` - The ``xmlattr`` filter does not allow keys with ``/`` solidus, ``>`` greater-than sign, or ``=`` equals sign, in addition to disallowing spaces. Regardless of any validation done by Jinja, user input should never be used diff --git a/Jinja2-2.11.2/src/jinja2/compiler.py b/Jinja2-2.11.2/src/jinja2/compiler.py index 63297b4..3d6e3d7 100644 --- a/Jinja2-2.11.2/src/jinja2/compiler.py +++ b/Jinja2-2.11.2/src/jinja2/compiler.py @@ -1034,6 +1034,11 @@ class CodeGenerator(NodeVisitor): ) self.writeline("if %s is missing:" % frame.symbols.ref(alias)) self.indent() + # The position will contain the template name, and will be formatted + # into a string that will be compiled into an f-string. Curly braces + # in the name must be replaced with escapes so that they will not be + # executed as part of the f-string. + position = self.position(node).replace("{", "{{").replace("}", "}}") self.writeline( "%s = undefined(%r %% " "included_template.__name__, " @@ -1042,7 +1047,7 @@ class CodeGenerator(NodeVisitor): frame.symbols.ref(alias), "the template %%r (imported on %s) does " "not export the requested name %s" - % (self.position(node), repr(name)), + % (position, repr(name)), name, ) ) diff --git a/Jinja2-2.11.2/tests/test_compile.py b/Jinja2-2.11.2/tests/test_compile.py new file mode 100644 index 0000000..12ce0e7 --- /dev/null +++ b/Jinja2-2.11.2/tests/test_compile.py @@ -0,0 +1,20 @@ +import pytest + +from jinja2 import UndefinedError +from jinja2.environment import Environment +from jinja2.loaders import DictLoader + +def test_undefined_import_curly_name(): + env = Environment( + loader=DictLoader( + { + "{bad}": "{% from 'macro' import m %}{{ m() }}", + "macro": "", + } + ) + ) + + # Must not raise `NameError: 'bad' is not defined`, as that would indicate + # that `{bad}` is being interpreted as an f-string. It must be escaped. + with pytest.raises(UndefinedError): + env.get_template("{bad}").render() -- 2.33.0