Skip to content
Myr

test_security.py

This file

Path

tests/test_security.py

186 lines · 6.8 KiB · Python

Last changed by

Merge branch 'master' of github.com:pallets/jinjaArmin Ronacherbefore adoption4a70e7a

History of this file

Take it

Merge branch 'lkarthee-pytest_migration'Markus Unterwaditzerbefore adoption1c5f1e8

lines 1–14why, one step back
1# -*- coding: utf-8 -*-
2"""3 jinja2.testsuite.security4 ~~~~~~~~~~~~~~~~~~~~~~~~~56 Checks the sandbox and other security features.78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import pytest1213from jinja2 import Environment14from jinja2.sandbox import SandboxedEnvironment, \

Merge branch '2.8-maintenance'Armin Ronacherbefore adoption3097b97

line 15why, one step back
15 ImmutableSandboxedEnvironment, unsafe, has_format

Merge branch 'lkarthee-pytest_migration'Markus Unterwaditzerbefore adoption1c5f1e8

lines 16–161why, one step back
16from jinja2 import Markup, escape
17from jinja2.exceptions import SecurityError, TemplateSyntaxError, \18 TemplateRuntimeError19from jinja2._compat import text_type202122class PrivateStuff(object):2324 def bar(self):25 return 232627 @unsafe28 def foo(self):29 return 423031 def __repr__(self):32 return 'PrivateStuff'333435class PublicStuff(object):36 bar = lambda self: 2337 _foo = lambda self: 423839 def __repr__(self):40 return 'PublicStuff'414243@pytest.mark.sandbox44class TestSandbox():4546 def test_unsafe(self, env):47 env = SandboxedEnvironment()48 pytest.raises(SecurityError, env.from_string("{{ foo.foo() }}").render,49 foo=PrivateStuff())50 assert env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) == '23'5152 pytest.raises(SecurityError,53 env.from_string("{{ foo._foo() }}").render,54 foo=PublicStuff())55 assert env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) == '23'56 assert env.from_string("{{ foo.__class__ }}").render(foo=42) == ''57 assert env.from_string("{{ foo.func_code }}").render(foo=lambda:None) == ''58 # security error comes from __class__ already.59 pytest.raises(SecurityError, env.from_string(60 "{{ foo.__class__.__subclasses__() }}").render, foo=42)6162 def test_immutable_environment(self, env):63 env = ImmutableSandboxedEnvironment()64 pytest.raises(SecurityError, env.from_string(65 '{{ [].append(23) }}').render)66 pytest.raises(SecurityError, env.from_string(67 '{{ {1:2}.clear() }}').render)6869 def test_restricted(self, env):70 env = SandboxedEnvironment()71 pytest.raises(TemplateSyntaxError, env.from_string,72 "{% for item.attribute in seq %}...{% endfor %}")73 pytest.raises(TemplateSyntaxError, env.from_string,74 "{% for foo, bar.baz in seq %}...{% endfor %}")7576 def test_markup_operations(self, env):77 # adding two strings should escape the unsafe one78 unsafe = '<script type="application/x-some-script">alert("foo");</script>'79 safe = Markup('<em>username</em>')80 assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)8182 # string interpolations are safe to use too83 assert Markup('<em>%s</em>') % '<bad user>' == \84 '<em>&lt;bad user&gt;</em>'85 assert Markup('<em>%(username)s</em>') % {86 'username': '<bad user>'87 } == '<em>&lt;bad user&gt;</em>'8889 # an escaped object is markup too90 assert type(Markup('foo') + 'bar') is Markup9192 # and it implements __html__ by returning itself93 x = Markup("foo")94 assert x.__html__() is x9596 # it also knows how to treat __html__ objects97 class Foo(object):98 def __html__(self):99 return '<em>awesome</em>'100101 def __unicode__(self):102 return 'awesome'103 assert Markup(Foo()) == '<em>awesome</em>'104 assert Markup('<strong>%s</strong>') % Foo() == \105 '<strong><em>awesome</em></strong>'106107 # escaping and unescaping108 assert escape('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'109 assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"110 assert Markup("&lt;test&gt;").unescape() == "<test>"111112 def test_template_data(self, env):113 env = Environment(autoescape=True)114 t = env.from_string('{% macro say_hello(name) %}'115 '<p>Hello {{ name }}!</p>{% endmacro %}'116 '{{ say_hello("<blink>foo</blink>") }}')117 escaped_out = '<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>'118 assert t.render() == escaped_out119 assert text_type(t.module) == escaped_out120 assert escape(t.module) == escaped_out121 assert t.module.say_hello('<blink>foo</blink>') == escaped_out122 assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out123124 def test_attr_filter(self, env):125 env = SandboxedEnvironment()126 tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')127 pytest.raises(SecurityError, tmpl.render, cls=int)128129 def test_binary_operator_intercepting(self, env):130 def disable_op(left, right):131 raise TemplateRuntimeError('that operator so does not work')132 for expr, ctx, rv in ('1 + 2', {}, '3'), ('a + 2', {'a': 2}, '4'):133 env = SandboxedEnvironment()134 env.binop_table['+'] = disable_op135 t = env.from_string('{{ %s }}' % expr)136 assert t.render(ctx) == rv137 env.intercepted_binops = frozenset(['+'])138 t = env.from_string('{{ %s }}' % expr)139 try:140 t.render(ctx)141 except TemplateRuntimeError as e:142 pass143 else:144 assert False, 'expected runtime error'145146 def test_unary_operator_intercepting(self, env):147 def disable_op(arg):148 raise TemplateRuntimeError('that operator so does not work')149 for expr, ctx, rv in ('-1', {}, '-1'), ('-a', {'a': 2}, '-2'):150 env = SandboxedEnvironment()151 env.unop_table['-'] = disable_op152 t = env.from_string('{{ %s }}' % expr)153 assert t.render(ctx) == rv154 env.intercepted_unops = frozenset(['-'])155 t = env.from_string('{{ %s }}' % expr)156 try:157 t.render(ctx)158 except TemplateRuntimeError as e:159 pass160 else:161 assert False, 'expected runtime error'

Merge branch '2.8-maintenance'Armin Ronacherbefore adoption3097b97

lines 162–177why, one step back
162
163164@pytest.mark.sandbox165@pytest.mark.skipif(not has_format, reason='No format support')166class TestStringFormat(object):167168 def test_basic_format_safety(self):169 env = SandboxedEnvironment()170 t = env.from_string('{{ "a{0.__class__}b".format(42) }}')171 assert t.render() == 'ab'172173 def test_basic_format_all_okay(self):174 env = SandboxedEnvironment()175 t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')176 assert t.render() == 'a42b'177

Merge branch 'master' of github.com:pallets/jinjaArmin Ronacherbefore adoption4a70e7a

line 178why, one step back
178 def test_safe_format_safety(self):

Merge branch '2.8-maintenance'Armin Ronacherbefore adoption3097b97

lines 179–182why, one step back
179 env = SandboxedEnvironment()
180 t = env.from_string('{{ ("a{0.__class__}b{1}"|safe).format(42, "<foo>") }}')181 assert t.render() == 'ab&lt;foo&gt;'182

Merge branch 'master' of github.com:pallets/jinjaArmin Ronacherbefore adoption4a70e7a

line 183why, one step back
183 def test_safe_format_all_okay(self):

Merge branch '2.8-maintenance'Armin Ronacherbefore adoption3097b97

lines 184–186why, one step back
184 env = SandboxedEnvironment()
185 t = env.from_string('{{ ("a{0.foo}b{1}"|safe).format({"foo": 42}, "<foo>") }}')186 assert t.render() == 'a42b&lt;foo&gt;'