Skip to content
Myr

test_security.py

This file

Path

tests/test_security.py

210 lines · 7.3 KiB · Python

Last changed by

remove custom pytest marksDavid Lordbefore adoptiondd5a050

History of this file

Take it

1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import escape6from jinja2 import Markup7from jinja2._compat import text_type8from jinja2.exceptions import SecurityError9from jinja2.exceptions import TemplateRuntimeError10from jinja2.exceptions import TemplateSyntaxError11from jinja2.nodes import EvalContext12from jinja2.sandbox import ImmutableSandboxedEnvironment13from jinja2.sandbox import SandboxedEnvironment14from jinja2.sandbox import unsafe151617class PrivateStuff(object):18    def bar(self):19        return 232021    @unsafe22    def foo(self):23        return 422425    def __repr__(self):26        return "PrivateStuff"272829class PublicStuff(object):30    def bar(self):31        return 233233    def _foo(self):34        return 423536    def __repr__(self):37        return "PublicStuff"383940class TestSandbox(object):41    def test_unsafe(self, env):42        env = SandboxedEnvironment()43        pytest.raises(44            SecurityError, env.from_string("{{ foo.foo() }}").render, foo=PrivateStuff()45        )46        assert env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) == "23"4748        pytest.raises(49            SecurityError, env.from_string("{{ foo._foo() }}").render, foo=PublicStuff()50        )51        assert env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) == "23"52        assert env.from_string("{{ foo.__class__ }}").render(foo=42) == ""53        assert env.from_string("{{ foo.func_code }}").render(foo=lambda: None) == ""54        # security error comes from __class__ already.55        pytest.raises(56            SecurityError,57            env.from_string("{{ foo.__class__.__subclasses__() }}").render,58            foo=42,59        )6061    def test_immutable_environment(self, env):62        env = ImmutableSandboxedEnvironment()63        pytest.raises(SecurityError, env.from_string("{{ [].append(23) }}").render)64        pytest.raises(SecurityError, env.from_string("{{ {1:2}.clear() }}").render)6566    def test_restricted(self, env):67        env = SandboxedEnvironment()68        pytest.raises(69            TemplateSyntaxError,70            env.from_string,71            "{% for item.attribute in seq %}...{% endfor %}",72        )73        pytest.raises(74            TemplateSyntaxError,75            env.from_string,76            "{% for foo, bar.baz in seq %}...{% endfor %}",77        )7879    def test_markup_operations(self, env):80        # adding two strings should escape the unsafe one81        unsafe = '<script type="application/x-some-script">alert("foo");</script>'82        safe = Markup("<em>username</em>")83        assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)8485        # string interpolations are safe to use too86        assert Markup("<em>%s</em>") % "<bad user>" == "<em>&lt;bad user&gt;</em>"87        assert (88            Markup("<em>%(username)s</em>") % {"username": "<bad user>"}89            == "<em>&lt;bad user&gt;</em>"90        )9192        # an escaped object is markup too93        assert type(Markup("foo") + "bar") is Markup9495        # and it implements __html__ by returning itself96        x = Markup("foo")97        assert x.__html__() is x9899        # it also knows how to treat __html__ objects100        class Foo(object):101            def __html__(self):102                return "<em>awesome</em>"103104            def __unicode__(self):105                return "awesome"106107        assert Markup(Foo()) == "<em>awesome</em>"108        assert (109            Markup("<strong>%s</strong>") % Foo() == "<strong><em>awesome</em></strong>"110        )111112        # escaping and unescaping113        assert escape("\"<>&'") == "&#34;&lt;&gt;&amp;&#39;"114        assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"115        assert Markup("&lt;test&gt;").unescape() == "<test>"116117    def test_template_data(self, env):118        env = Environment(autoescape=True)119        t = env.from_string(120            "{% macro say_hello(name) %}"121            "<p>Hello {{ name }}!</p>{% endmacro %}"122            '{{ say_hello("<blink>foo</blink>") }}'123        )124        escaped_out = "<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>"125        assert t.render() == escaped_out126        assert text_type(t.module) == escaped_out127        assert escape(t.module) == escaped_out128        assert t.module.say_hello("<blink>foo</blink>") == escaped_out129        assert (130            escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))131            == escaped_out132        )133        assert escape(t.module.say_hello("<blink>foo</blink>")) == escaped_out134135    def test_attr_filter(self, env):136        env = SandboxedEnvironment()137        tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')138        pytest.raises(SecurityError, tmpl.render, cls=int)139140    def test_binary_operator_intercepting(self, env):141        def disable_op(left, right):142            raise TemplateRuntimeError("that operator so does not work")143144        for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):145            env = SandboxedEnvironment()146            env.binop_table["+"] = disable_op147            t = env.from_string("{{ %s }}" % expr)148            assert t.render(ctx) == rv149            env.intercepted_binops = frozenset(["+"])150            t = env.from_string("{{ %s }}" % expr)151            with pytest.raises(TemplateRuntimeError):152                t.render(ctx)153154    def test_unary_operator_intercepting(self, env):155        def disable_op(arg):156            raise TemplateRuntimeError("that operator so does not work")157158        for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):159            env = SandboxedEnvironment()160            env.unop_table["-"] = disable_op161            t = env.from_string("{{ %s }}" % expr)162            assert t.render(ctx) == rv163            env.intercepted_unops = frozenset(["-"])164            t = env.from_string("{{ %s }}" % expr)165            with pytest.raises(TemplateRuntimeError):166                t.render(ctx)167168169class TestStringFormat(object):170    def test_basic_format_safety(self):171        env = SandboxedEnvironment()172        t = env.from_string('{{ "a{0.__class__}b".format(42) }}')173        assert t.render() == "ab"174175    def test_basic_format_all_okay(self):176        env = SandboxedEnvironment()177        t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')178        assert t.render() == "a42b"179180    def test_safe_format_safety(self):181        env = SandboxedEnvironment()182        t = env.from_string('{{ ("a{0.__class__}b{1}"|safe).format(42, "<foo>") }}')183        assert t.render() == "ab&lt;foo&gt;"184185    def test_safe_format_all_okay(self):186        env = SandboxedEnvironment()187        t = env.from_string('{{ ("a{0.foo}b{1}"|safe).format({"foo": 42}, "<foo>") }}')188        assert t.render() == "a42b&lt;foo&gt;"189190191@pytest.mark.skipif(192    not hasattr(str, "format_map"), reason="requires str.format_map method"193)194class TestStringFormatMap(object):195    def test_basic_format_safety(self):196        env = SandboxedEnvironment()197        t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')198        assert t.render() == "ab"199200    def test_basic_format_all_okay(self):201        env = SandboxedEnvironment()202        t = env.from_string('{{ "a{x.foo}b".format_map({"x":{"foo": 42}}) }}')203        assert t.render() == "a42b"204205    def test_safe_format_all_okay(self):206        env = SandboxedEnvironment()207        t = env.from_string(208            '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'209        )210        assert t.render() == "a42b&lt;foo&gt;"