Skip to content
Myr

test_security.py

This file

Path

tests/test_security.py

202 lines · 6.9 KiB · Python

Last changed by

Merge branch 'stable'David Lordbefore adoption220e67a

History of this file

Take it

1import pytest2from markupsafe import escape34from jinja2 import Environment5from jinja2.exceptions import SecurityError6from jinja2.exceptions import TemplateRuntimeError7from jinja2.exceptions import TemplateSyntaxError8from jinja2.nodes import EvalContext9from jinja2.sandbox import ImmutableSandboxedEnvironment10from jinja2.sandbox import SandboxedEnvironment11from jinja2.sandbox import unsafe121314class PrivateStuff:15    def bar(self):16        return 231718    @unsafe19    def foo(self):20        return 422122    def __repr__(self):23        return "PrivateStuff"242526class PublicStuff:27    def bar(self):28        return 232930    def _foo(self):31        return 423233    def __repr__(self):34        return "PublicStuff"353637class TestSandbox:38    def test_unsafe(self, env):39        env = SandboxedEnvironment()40        pytest.raises(41            SecurityError, env.from_string("{{ foo.foo() }}").render, foo=PrivateStuff()42        )43        assert env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) == "23"4445        pytest.raises(46            SecurityError, env.from_string("{{ foo._foo() }}").render, foo=PublicStuff()47        )48        assert env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) == "23"49        assert env.from_string("{{ foo.__class__ }}").render(foo=42) == ""50        assert env.from_string("{{ foo.func_code }}").render(foo=lambda: None) == ""51        # security error comes from __class__ already.52        pytest.raises(53            SecurityError,54            env.from_string("{{ foo.__class__.__subclasses__() }}").render,55            foo=42,56        )5758    def test_immutable_environment(self, env):59        env = ImmutableSandboxedEnvironment()60        pytest.raises(SecurityError, env.from_string("{{ [].append(23) }}").render)61        pytest.raises(SecurityError, env.from_string("{{ [].clear() }}").render)62        pytest.raises(SecurityError, env.from_string("{{ [1].pop() }}").render)63        pytest.raises(SecurityError, env.from_string("{{ {1:2}.clear() }}").render)6465    def test_restricted(self, env):66        env = SandboxedEnvironment()67        pytest.raises(68            TemplateSyntaxError,69            env.from_string,70            "{% for item.attribute in seq %}...{% endfor %}",71        )72        pytest.raises(73            TemplateSyntaxError,74            env.from_string,75            "{% for foo, bar.baz in seq %}...{% endfor %}",76        )7778    def test_template_data(self, env):79        env = Environment(autoescape=True)80        t = env.from_string(81            "{% macro say_hello(name) %}"82            "<p>Hello {{ name }}!</p>{% endmacro %}"83            '{{ say_hello("<blink>foo</blink>") }}'84        )85        escaped_out = "<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>"86        assert t.render() == escaped_out87        assert str(t.module) == escaped_out88        assert escape(t.module) == escaped_out89        assert t.module.say_hello("<blink>foo</blink>") == escaped_out90        assert (91            escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))92            == escaped_out93        )94        assert escape(t.module.say_hello("<blink>foo</blink>")) == escaped_out9596    def test_attr_filter(self, env):97        env = SandboxedEnvironment()98        tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')99        pytest.raises(SecurityError, tmpl.render, cls=int)100101    def test_binary_operator_intercepting(self, env):102        def disable_op(left, right):103            raise TemplateRuntimeError("that operator so does not work")104105        for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):106            env = SandboxedEnvironment()107            env.binop_table["+"] = disable_op108            t = env.from_string(f"{{{{ {expr} }}}}")109            assert t.render(ctx) == rv110            env.intercepted_binops = frozenset(["+"])111            t = env.from_string(f"{{{{ {expr} }}}}")112            with pytest.raises(TemplateRuntimeError):113                t.render(ctx)114115    def test_unary_operator_intercepting(self, env):116        def disable_op(arg):117            raise TemplateRuntimeError("that operator so does not work")118119        for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):120            env = SandboxedEnvironment()121            env.unop_table["-"] = disable_op122            t = env.from_string(f"{{{{ {expr} }}}}")123            assert t.render(ctx) == rv124            env.intercepted_unops = frozenset(["-"])125            t = env.from_string(f"{{{{ {expr} }}}}")126            with pytest.raises(TemplateRuntimeError):127                t.render(ctx)128129130class TestStringFormat:131    def test_basic_format_safety(self):132        env = SandboxedEnvironment()133        t = env.from_string('{{ "a{0.__class__}b".format(42) }}')134        assert t.render() == "ab"135136    def test_basic_format_all_okay(self):137        env = SandboxedEnvironment()138        t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')139        assert t.render() == "a42b"140141    def test_safe_format_safety(self):142        env = SandboxedEnvironment()143        t = env.from_string('{{ ("a{0.__class__}b{1}"|safe).format(42, "<foo>") }}')144        assert t.render() == "ab&lt;foo&gt;"145146    def test_safe_format_all_okay(self):147        env = SandboxedEnvironment()148        t = env.from_string('{{ ("a{0.foo}b{1}"|safe).format({"foo": 42}, "<foo>") }}')149        assert t.render() == "a42b&lt;foo&gt;"150151    def test_empty_braces_format(self):152        env = SandboxedEnvironment()153        t1 = env.from_string('{{ ("a{}b{}").format("foo", "42")}}')154        t2 = env.from_string('{{ ("a{}b{}"|safe).format(42, "<foo>") }}')155        assert t1.render() == "afoob42"156        assert t2.render() == "a42b&lt;foo&gt;"157158159class TestStringFormatMap:160    def test_basic_format_safety(self):161        env = SandboxedEnvironment()162        t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')163        assert t.render() == "ab"164165    def test_basic_format_all_okay(self):166        env = SandboxedEnvironment()167        t = env.from_string('{{ "a{x.foo}b".format_map({"x":{"foo": 42}}) }}')168        assert t.render() == "a42b"169170    def test_safe_format_all_okay(self):171        env = SandboxedEnvironment()172        t = env.from_string(173            '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'174        )175        assert t.render() == "a42b&lt;foo&gt;"176177    def test_indirect_call(self):178        def run(value, arg):179            return value.run(arg)180181        env = SandboxedEnvironment()182        env.filters["run"] = run183        t = env.from_string(184            """{% set185                ns = namespace(run="{0.__call__.__builtins__[__import__]}".format)186            %}187            {{ ns | run(not_here) }}188            """189        )190191        with pytest.raises(SecurityError):192            t.render()193194    def test_attr_filter(self) -> None:195        env = SandboxedEnvironment()196        t = env.from_string(197            """{{ "{0.__call__.__builtins__[__import__]}"198                  | attr("format")(not_here) }}"""199        )200201        with pytest.raises(SecurityError):202            t.render()