Set macro autoescape behavior at call instead of compile time. Fixes #565
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent b3c174b · Browse files · 5 files·+69 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+69 added−20 removed
- tests:+13 added−1 removed
- other:+56 added−19 removed
Provenance
- Commit
b9655a4- Tree
cbfa2f5- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
b3c174b
5 files changed+69 added−20 removed
modified:jinja2/compiler.py+19 added-16 removed
297 unmodified lines298 """Enable buffering for the frame from that point onwards."""299 frame.buffer = self.temporary_identifier()300 self.writeline('%s = []' % frame.buffer)301 302- def return_buffer_contents(self, frame):302+ def return_buffer_contents(self, frame, force_unescaped=False):303 """Return the buffer contents of the frame."""304+ if not force_unescaped:304- if frame.eval_ctx.volatile:305- self.writeline('if context.eval_ctx.autoescape:')306- self.indent()307- self.writeline('return Markup(concat(%s))' % frame.buffer)308- self.outdent()309- self.writeline('else:')310- self.indent()311- self.writeline('return concat(%s)' % frame.buffer)312- self.outdent()313- elif frame.eval_ctx.autoescape:314- self.writeline('return Markup(concat(%s))' % frame.buffer)315- else:316- self.writeline('return concat(%s)' % frame.buffer)305+ if frame.eval_ctx.volatile:306+ self.writeline('if context.eval_ctx.autoescape:')307+ self.indent()308+ self.writeline('return Markup(concat(%s))' % frame.buffer)309+ self.outdent()310+ self.writeline('else:')311+ self.indent()312+ self.writeline('return concat(%s)' % frame.buffer)313+ self.outdent()314+ return315+ elif frame.eval_ctx.autoescape:316+ self.writeline('return Markup(concat(%s))' % frame.buffer)317+ return318+ self.writeline('return concat(%s)' % frame.buffer)319 320 def indent(self):321 """Indent by one."""322 self._indentation += 1200 unmodified lines523 self.visit(default, frame)524 self.outdent()525 526 self.blockvisit(node.body, frame)525- self.return_buffer_contents(frame)527+ self.return_buffer_contents(frame, force_unescaped=True)528 self.leave_frame(frame, with_python_scope=True)529 self.outdent()530 531 return frame, macro_ref3 unmodified lines535 arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args)536 name = getattr(macro_ref.node, 'name', None)537 if len(macro_ref.node.args) == 1:538 arg_tuple += ','537- self.write('Macro(environment, macro, %r, (%s), %r, %r, %r)' %539+ self.write('Macro(environment, macro, %r, (%s), %r, %r, %r, '540+ 'context.eval_ctx.autoescape)' %541 (name, arg_tuple, macro_ref.accesses_kwargs,542 macro_ref.accesses_varargs, macro_ref.accesses_caller))543 544 def position(self, node):999 unmodified linesmodified:jinja2/runtime.py+35 added-3 removed
11 unmodified lines12 13 from itertools import chain14 from jinja2.nodes import EvalContext, _context_function_types15 from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \16- internalcode, object_type_repr16+ internalcode, object_type_repr, evalcontextfunction17 from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \18 TemplateNotFound19 from jinja2._compat import imap, text_type, iteritems, \20 implements_iterator, implements_to_string, string_types, PY2376 unmodified lines397 class Macro(object):398 """Wraps a macro function."""399 400 def __init__(self, environment, func, name, arguments,401- catch_kwargs, catch_varargs, caller):401+ catch_kwargs, catch_varargs, caller,402+ default_autoescape=None):403 self._environment = environment404 self._func = func405 self._argument_count = len(arguments)406 self.name = name407 self.arguments = arguments408 self.catch_kwargs = catch_kwargs409 self.catch_varargs = catch_varargs410 self.caller = caller411+ if default_autoescape is None:412+ default_autoescape = environment.autoescape413+ self._default_autoescape = default_autoescape414 415 @internalcode416+ @evalcontextfunction417 def __call__(self, *args, **kwargs):418+ # This requires a bit of explanation, In the past we used to419+ # decide largely based on compile-time information if a macro is420+ # safe or unsafe. While there was a volatile mode it was largely421+ # unused for deciding on escaping. This turns out to be422+ # problemtic for macros because if a macro is safe or not not so423+ # much depends on the escape mode when it was defined but when it424+ # was used.425+ #426+ # Because however we export macros from the module system and427+ # there are historic callers that do not pass an eval context (and428+ # will continue to not pass one), we need to perform an instance429+ # check here.430+ #431+ # This is considered safe because an eval context is not a valid432+ # argument to callables otherwise anwyays. Worst case here is433+ # that if no eval context is passed we fall back to the compile434+ # time autoescape flag.435+ if args and isinstance(args[0], EvalContext):436+ autoescape = args[0].autoescape437+ args = args[1:]438+ else:439+ autoescape = self._default_autoescape440+441 # try to consume the positional arguments442 arguments = list(args[:self._argument_count])443 off = len(arguments)444 26 unmodified lines471 arguments.append(args[self._argument_count:])472 elif len(args) > self._argument_count:473 raise TypeError('macro %r takes not more than %d argument(s)' %474 (self.name, len(self.arguments)))447- return self._func(*arguments)475 476+ rv = self._func(*arguments)477+ if autoescape:478+ rv = Markup(rv)479+ return rv480+481 def __repr__(self):482 return '<%s %s>' % (483 self.__class__.__name__,484 self.name is None and 'anonymous' or repr(self.name)226 unmodified linesmodified:tests/test_ext.py+8 added
353 unmodified lines354 '"<test>") }}{% endautoescape %}')355 assert t.render(ae=True) == '<strong>Wert: <test></strong>'356 assert t.render(ae=False) == '<strong>Wert: <test></strong>'357 358+ def test_autoescape_macros(self):359+ env = Environment(autoescape=False, extensions=['jinja2.ext.autoescape'])360+ template = (361+ '{% macro m() %}<html>{% endmacro %}'362+ '{% autoescape true %}{{ m() }}{% endautoescape %}'363+ )364+ assert env.from_string(template).render() == '<html>'365+366 def test_num_used_twice(self):367 tmpl = newstyle_i18n_env.get_template('ngettext_long.html')368 assert tmpl.render(apples=5, LANGUAGE='de') == u'5 Äpfel'369 106 unmodified linesmodified:tests/test_security.py+5 added-1 removed
14 unmodified lines15 ImmutableSandboxedEnvironment, unsafe, has_format16 from jinja2 import Markup, escape17 from jinja2.exceptions import SecurityError, TemplateSyntaxError, \18 TemplateRuntimeError19+from jinja2.nodes import EvalContext20 from jinja2._compat import text_type21 22 23 class PrivateStuff(object):95 unmodified lines119 assert t.render() == escaped_out120 assert text_type(t.module) == escaped_out121 assert escape(t.module) == escaped_out122 assert t.module.say_hello('<blink>foo</blink>') == escaped_out122- assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out123+ assert escape(t.module.say_hello(124+ EvalContext(env), '<blink>foo</blink>')) == escaped_out125+ assert escape(t.module.say_hello(126+ '<blink>foo</blink>')) == escaped_out127 128 def test_attr_filter(self, env):129 env = SandboxedEnvironment()130 tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')60 unmodified linesmodified:CHANGES+2 added
21 unmodified lines22 quote the parameter.23 - Depend on MarkupSafe 0.23 or higher.24 - Improved the `truncate` filter to support better truncation in case25 the string is barely truncated at all.26+- Change the logic for macro autoescaping to be based on the runtime27+ autoescaping information at call time instead of macro define time.28 29 Version 2.8.230 -------------31 381 unmodified lines