Debian Codegraph @

tests/test_security.py

raw
1 import pytest
2 from markupsafe import escape
3
4 from jinja2 import Environment
5 from jinja2.exceptions import SecurityError
6 from jinja2.exceptions import TemplateRuntimeError
7 from jinja2.exceptions import TemplateSyntaxError
8 from jinja2.nodes import EvalContext
9 from jinja2.sandbox import ImmutableSandboxedEnvironment
10 from jinja2.sandbox import SandboxedEnvironment
11 from jinja2.sandbox import unsafe
12
13
14 class PrivateStuff:
15 def bar(self):
16 return 23
17
18 @unsafe
19 def foo(self):
20 return 42
21
22 def __repr__(self):
23 return "PrivateStuff"
24
25
26 class PublicStuff:
27 def bar(self):
28 return 23
29
30 def _foo(self):
31 return 42
32
33 def __repr__(self):
34 return "PublicStuff"
35
36
37 class 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"
44
45 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 )
57
58 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)
64
65 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 )
77
78 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_out
87 assert str(t.module) == escaped_out
88 assert escape(t.module) == escaped_out
89 assert t.module.say_hello("<blink>foo</blink>") == escaped_out
90 assert (
91 escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))
92 == escaped_out
93 )
94 assert escape(t.module.say_hello("<blink>foo</blink>")) == escaped_out
95
96 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)
100
101 def test_binary_operator_intercepting(self, env):
102 def disable_op(left, right):
103 raise TemplateRuntimeError("that operator so does not work")
104
105 for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):
106 env = SandboxedEnvironment()
107 env.binop_table["+"] = disable_op
108 t = env.from_string(f"{{{{ {expr} }}}}")
109 assert t.render(ctx) == rv
110 env.intercepted_binops = frozenset(["+"])
111 t = env.from_string(f"{{{{ {expr} }}}}")
112 with pytest.raises(TemplateRuntimeError):
113 t.render(ctx)
114
115 def test_unary_operator_intercepting(self, env):
116 def disable_op(arg):
117 raise TemplateRuntimeError("that operator so does not work")
118
119 for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):
120 env = SandboxedEnvironment()
121 env.unop_table["-"] = disable_op
122 t = env.from_string(f"{{{{ {expr} }}}}")
123 assert t.render(ctx) == rv
124 env.intercepted_unops = frozenset(["-"])
125 t = env.from_string(f"{{{{ {expr} }}}}")
126 with pytest.raises(TemplateRuntimeError):
127 t.render(ctx)
128
129
130 class 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"
135
136 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"
140
141 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;"
145
146 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;"
150
151 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;"
157
158
159 class 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"
164
165 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"
169
170 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;"
176
177 def test_indirect_call(self):
178 def run(value, arg):
179 return value.run(arg)
180
181 env = SandboxedEnvironment()
182 env.filters["run"] = run
183 t = env.from_string(
184 """{% set
185 ns = namespace(run="{0.__call__.__builtins__[__import__]}".format)
186 %}
187 {{ ns | run(not_here) }}
188 """
189 )
190
191 with pytest.raises(SecurityError):
192 t.render()
193
194 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 )
200
201 with pytest.raises(SecurityError):
202 t.render()