Skip to content
Myr

sandbox.rst

This file

Path

docs/sandbox.rst

111 lines · 4.1 KiB

Last changed by

Merge pull request #1616 from pallets/docs-sandboxDavid Lordbefore adoption350bc53

History of this file

Take it

1Sandbox2=======34The Jinja sandbox can be used to render untrusted templates. Access to5attributes, method calls, operators, mutating data structures, and6string formatting can be intercepted and prohibited.78.. code-block:: pycon910    >>> from jinja2.sandbox import SandboxedEnvironment11    >>> env = SandboxedEnvironment()12    >>> func = lambda: "Hello, Sandbox!"13    >>> env.from_string("{{ func() }}").render(func=func)14    'Hello, Sandbox!'15    >>> env.from_string("{{ func.__code__.co_code }}").render(func=func)16    Traceback (most recent call last):17      ...18    SecurityError: access to attribute '__code__' of 'function' object is unsafe.1920A sandboxed environment can be useful, for example, to allow users of an21internal reporting system to create custom emails. You would document22what data is available in the templates, then the user would write a23template using that information. Your code would generate the report24data and pass it to the user's sandboxed template to render.252627Security Considerations28-----------------------2930The sandbox alone is not a solution for perfect security. Keep these31things in mind when using the sandbox.3233Templates can still raise errors when compiled or rendered. Your code34should attempt to catch errors instead of crashing.3536It is possible to construct a relatively small template that renders to37a very large amount of output, which could correspond to a high use of38CPU or memory. You should run your application with limits on resources39such as CPU and memory to mitigate this.4041Jinja only renders text, it does not understand, for example, JavaScript42code. Depending on how the rendered template will be used, you may need43to do other postprocessing to restrict the output.4445Pass only the data that is relevant to the template. Avoid passing46global data, or objects with methods that have side effects. By default47the sandbox prevents private and internal attribute access. You can48override :meth:`~SandboxedEnvironment.is_safe_attribute` to further49restrict attributes access. Decorate methods with :func:`unsafe` to50prevent calling them from templates when passing objects as data. Use51:class:`ImmutableSandboxedEnvironment` to prevent modifying lists and52dictionaries.535455API56---5758.. module:: jinja2.sandbox5960.. autoclass:: SandboxedEnvironment([options])61    :members: is_safe_attribute, is_safe_callable, default_binop_table,62              default_unop_table, intercepted_binops, intercepted_unops,63              call_binop, call_unop6465.. autoclass:: ImmutableSandboxedEnvironment([options])6667.. autoexception:: SecurityError6869.. autofunction:: unsafe7071.. autofunction:: is_internal_attribute7273.. autofunction:: modifies_known_mutable747576Operator Intercepting77---------------------7879For performance, Jinja outputs operators directly when compiling. This80means it's not possible to intercept operator behavior by overriding81:meth:`SandboxEnvironment.call <Environment.call>` by default, because82operator special methods are handled by the Python interpreter, and83might not correspond with exactly one method depending on the operator's84use.8586The sandbox can instruct the compiler to output a function to intercept87certain operators instead. Override88:attr:`SandboxedEnvironment.intercepted_binops` and89:attr:`SandboxedEnvironment.intercepted_unops` with the operator symbols90you want to intercept. The compiler will replace the symbols with calls91to :meth:`SandboxedEnvironment.call_binop` and92:meth:`SandboxedEnvironment.call_unop` instead. The default93implementation of those methods will use94:attr:`SandboxedEnvironment.binop_table` and95:attr:`SandboxedEnvironment.unop_table` to translate operator symbols96into :mod:`operator` functions.9798For example, the power (``**``) operator can be disabled:99100.. code-block:: python101102    from jinja2.sandbox import SandboxedEnvironment103104    class MyEnvironment(SandboxedEnvironment):105        intercepted_binops = frozenset(["**"])106107        def call_binop(self, context, operator, left, right):108            if operator == "**":109                return self.undefined("The power (**) operator is unavailable.")110111            return super().call_binop(self, context, operator, left, right)