sandbox.py
This file
Path
src/jinja2/sandbox.py
434 lines · 14.6 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
The walk stopped after 200 commits: lines older than c580dd0 point at it.
update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1–3why, one step back1"""A sandbox layer that ensures unsafe operations cannot be performed.2Useful when the template itself comes from an untrusted source.3"""Merge branch '3.1.x'David Lordbefore adoptionde61312
line 4why, one step back4update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 5–6why, one step back5import operator6import typesMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 7why, one step back7import typing as t[pre-commit.ci] pre-commit autoupdate (#1993)David Lordbefore adoption9c6c319
line 8why, one step back8from _string import formatter_field_name_split # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 9–10why, one step back9from collections import abc10from collections import dequeMerge branch 'stable'David Lordbefore adoption6aeab5d
line 11why, one step back11from functools import update_wrapperupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 12–18why, one step back12from string import Formatter1314from markupsafe import EscapeFormatter15from markupsafe import Markup1617from .environment import Environment18from .exceptions import SecurityErrorMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 19–20why, one step back19from .runtime import Context20from .runtime import Undefinedupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 21why, one step back21Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 22–23why, one step back22F = t.TypeVar("F", bound=t.Callable[..., t.Any])23update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 24–27why, one step back24#: maximum number of items a range may produce25MAX_RANGE = 1000002627#: Unsafe function attributes.Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 28why, one step back28UNSAFE_FUNCTION_ATTRIBUTES: set[str] = set()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 29–30why, one step back2930#: Unsafe method attributes. Function attributes are unsafe for methods too.Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 31why, one step back31UNSAFE_METHOD_ATTRIBUTES: set[str] = set()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 32–41why, one step back3233#: unsafe generator attributes.34UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}3536#: unsafe attributes on coroutines37UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}3839#: unsafe attributes on async generators40UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}41Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 42why, one step back42_mutable_spec: tuple[tuple[type[t.Any], frozenset[str]], ...] = (update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 43–63why, one step back43 (44 abc.MutableSet,45 frozenset(46 [47 "add",48 "clear",49 "difference_update",50 "discard",51 "pop",52 "remove",53 "symmetric_difference_update",54 "update",55 ]56 ),57 ),58 (59 abc.MutableMapping,60 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),61 ),62 (63 abc.MutableSequence,Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 64–66why, one step back64 frozenset(65 ["append", "clear", "pop", "reverse", "insert", "sort", "extend", "remove"]66 ),update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 67–86why, one step back67 ),68 (69 deque,70 frozenset(71 [72 "append",73 "appendleft",74 "clear",75 "extend",76 "extendleft",77 "pop",78 "popleft",79 "remove",80 "rotate",81 ]82 ),83 ),84)8586Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 87why, one step back87def safe_range(*args: int) -> range:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 88–101why, one step back88 """A range that can't generate ranges with a length of more than89 MAX_RANGE items.90 """91 rng = range(*args)9293 if len(rng) > MAX_RANGE:94 raise OverflowError(95 "Range too big. The sandbox blocks ranges larger than"96 f" MAX_RANGE ({MAX_RANGE})."97 )9899 return rng100101Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 102why, one step back102def unsafe(f: F) -> F:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 103–110why, one step back103 """Marks a function or method as unsafe.104105 .. code-block: python106107 @unsafe108 def delete(self):109 pass110 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 111why, one step back111 f.unsafe_callable = True # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 112–114why, one step back112 return f113114Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 115why, one step back115def is_internal_attribute(obj: t.Any, attr: str) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 116–151why, one step back116 """Test if the attribute given is an internal python attribute. For117 example this function returns `True` for the `func_code` attribute of118 python objects. This is useful if the environment method119 :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.120121 >>> from jinja2.sandbox import is_internal_attribute122 >>> is_internal_attribute(str, "mro")123 True124 >>> is_internal_attribute(str, "upper")125 False126 """127 if isinstance(obj, types.FunctionType):128 if attr in UNSAFE_FUNCTION_ATTRIBUTES:129 return True130 elif isinstance(obj, types.MethodType):131 if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:132 return True133 elif isinstance(obj, type):134 if attr == "mro":135 return True136 elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):137 return True138 elif isinstance(obj, types.GeneratorType):139 if attr in UNSAFE_GENERATOR_ATTRIBUTES:140 return True141 elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):142 if attr in UNSAFE_COROUTINE_ATTRIBUTES:143 return True144 elif hasattr(types, "AsyncGeneratorType") and isinstance(145 obj, types.AsyncGeneratorType146 ):147 if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:148 return True149 return attr.startswith("__")150151Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 152why, one step back152def modifies_known_mutable(obj: t.Any, attr: str) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 153–192why, one step back153 """This function checks if an attribute on a builtin mutable object154 (list, dict, set or deque) or the corresponding ABCs would modify it155 if called.156157 >>> modifies_known_mutable({}, "clear")158 True159 >>> modifies_known_mutable({}, "keys")160 False161 >>> modifies_known_mutable([], "append")162 True163 >>> modifies_known_mutable([], "index")164 False165166 If called with an unsupported object, ``False`` is returned.167168 >>> modifies_known_mutable("foo", "upper")169 False170 """171 for typespec, unsafe in _mutable_spec:172 if isinstance(obj, typespec):173 return attr in unsafe174 return False175176177class SandboxedEnvironment(Environment):178 """The sandboxed environment. It works like the regular environment but179 tells the compiler to generate sandboxed code. Additionally subclasses of180 this environment may override the methods that tell the runtime what181 attributes or functions are safe to access.182183 If the template tries to access insecure code a :exc:`SecurityError` is184 raised. However also other exceptions may occur during the rendering so185 the caller has to ensure that all exceptions are caught.186 """187188 sandboxed = True189190 #: default callback table for the binary operators. A copy of this is191 #: available on each instance of a sandboxed environment as192 #: :attr:`binop_table`Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 193why, one step back193 default_binop_table: dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 194–205why, one step back194 "+": operator.add,195 "-": operator.sub,196 "*": operator.mul,197 "/": operator.truediv,198 "//": operator.floordiv,199 "**": operator.pow,200 "%": operator.mod,201 }202203 #: default callback table for the unary operators. A copy of this is204 #: available on each instance of a sandboxed environment as205 #: :attr:`unop_table`Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 206why, one step back206 default_unop_table: dict[str, t.Callable[[t.Any], t.Any]] = {Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 207–209why, one step back207 "+": operator.pos,208 "-": operator.neg,209 }update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 210–224why, one step back210211 #: a set of binary operators that should be intercepted. Each operator212 #: that is added to this set (empty by default) is delegated to the213 #: :meth:`call_binop` method that will perform the operator. The default214 #: operator callback is specified by :attr:`binop_table`.215 #:216 #: The following binary operators are interceptable:217 #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``218 #:219 #: The default operation form the operator table corresponds to the220 #: builtin function. Intercepted calls are always slower than the native221 #: operator call, so make sure only to intercept the ones you are222 #: interested in.223 #:224 #: .. versionadded:: 2.6Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 225why, one step back225 intercepted_binops: frozenset[str] = frozenset()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 226–239why, one step back226227 #: a set of unary operators that should be intercepted. Each operator228 #: that is added to this set (empty by default) is delegated to the229 #: :meth:`call_unop` method that will perform the operator. The default230 #: operator callback is specified by :attr:`unop_table`.231 #:232 #: The following unary operators are interceptable: ``+``, ``-``233 #:234 #: The default operation form the operator table corresponds to the235 #: builtin function. Intercepted calls are always slower than the native236 #: operator call, so make sure only to intercept the ones you are237 #: interested in.238 #:239 #: .. versionadded:: 2.6Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 240why, one step back240 intercepted_unops: frozenset[str] = frozenset()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 241why, one step back241Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 242–243why, one step back242 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:243 super().__init__(*args, **kwargs)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 244–247why, one step back244 self.globals["range"] = safe_range245 self.binop_table = self.default_binop_table.copy()246 self.unop_table = self.default_unop_table.copy()247Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 248why, one step back248 def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 249–256why, one step back249 """The sandboxed environment will call this method to check if the250 attribute of an object is safe to access. Per default all attributes251 starting with an underscore are considered private as well as the252 special attributes of internal python objects as returned by the253 :func:`is_internal_attribute` function.254 """255 return not (attr.startswith("_") or is_internal_attribute(obj, attr))256Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 257–262why, one step back257 def is_safe_callable(self, obj: t.Any) -> bool:258 """Check if an object is safely callable. By default callables259 are considered safe unless decorated with :func:`unsafe`.260261 This also recognizes the Django convention of setting262 ``func.alters_data = True``.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 263–267why, one step back263 """264 return not (265 getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)266 )267Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 268–270why, one step back268 def call_binop(269 self, context: Context, operator: str, left: t.Any, right: t.Any270 ) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 271–278why, one step back271 """For intercepted binary operator calls (:meth:`intercepted_binops`)272 this function is executed instead of the builtin operator. This can273 be used to fine tune the behavior of certain operators.274275 .. versionadded:: 2.6276 """277 return self.binop_table[operator](left, right)278Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 279why, one step back279 def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 280–287why, one step back280 """For intercepted unary operator calls (:meth:`intercepted_unops`)281 this function is executed instead of the builtin operator. This can282 be used to fine tune the behavior of certain operators.283284 .. versionadded:: 2.6285 """286 return self.unop_table[operator](arg)287drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 288why, one step back288 def getitem(self, obj: t.Any, argument: str | t.Any) -> t.Any | Undefined:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 289–303why, one step back289 """Subscribe an object from sandboxed code."""290 try:291 return obj[argument]292 except (TypeError, LookupError):293 if isinstance(argument, str):294 try:295 attr = str(argument)296 except Exception:297 pass298 else:299 try:300 value = getattr(obj, attr)301 except AttributeError:302 pass303 else:Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 304–306why, one step back304 fmt = self.wrap_str_format(value)305 if fmt is not None:306 return fmtupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 307–311why, one step back307 if self.is_safe_attribute(obj, argument, value):308 return value309 return self.unsafe_undefined(obj, argument)310 return self.undefined(obj=obj, name=argument)311drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 312why, one step back312 def getattr(self, obj: t.Any, attribute: str) -> t.Any | Undefined:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 313–323why, one step back313 """Subscribe an object from sandboxed code and prefer the314 attribute. The attribute passed *must* be a bytestring.315 """316 try:317 value = getattr(obj, attribute)318 except AttributeError:319 try:320 return obj[attribute]321 except (TypeError, LookupError):322 pass323 else:Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 324–326why, one step back324 fmt = self.wrap_str_format(value)325 if fmt is not None:326 return fmtupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 327–331why, one step back327 if self.is_safe_attribute(obj, attribute, value):328 return value329 return self.unsafe_undefined(obj, attribute)330 return self.undefined(obj=obj, name=attribute)331Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 332why, one step back332 def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 333–335why, one step back333 """Return an undefined object for unsafe attributes."""334 return self.undefined(335 f"access to attribute {attribute!r} of"Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 336why, one step back336 f" {type(obj).__name__!r} object is unsafe.",update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 337–341why, one step back337 name=attribute,338 obj=obj,339 exc=SecurityError,340 )341drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 342why, one step back342 def wrap_str_format(self, value: t.Any) -> t.Callable[..., str] | None:Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 343–346why, one step back343 """If the given value is a ``str.format`` or ``str.format_map`` method,344 return a new function than handles sandboxing. This is done at access345 rather than in :meth:`call`, so that calls made without ``call`` are346 also sandboxed.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 347why, one step back347 """Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 348–357why, one step back348 if not isinstance(349 value, (types.MethodType, types.BuiltinMethodType)350 ) or value.__name__ not in ("format", "format_map"):351 return None352353 f_self: t.Any = value.__self__354355 if not isinstance(f_self, str):356 return None357Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 358why, one step back358 str_type: type[str] = type(f_self)Merge branch 'stable'David Lordbefore adoption6aeab5d
line 359why, one step back359 is_format_map = value.__name__ == "format_map"Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 360why, one step back360 formatter: SandboxedFormatterMerge branch 'stable'David Lordbefore adoption6aeab5d
lines 361–363why, one step back361362 if isinstance(f_self, Markup):363 formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 364–366why, one step back364 else:365 formatter = SandboxedFormatter(self)366Merge branch 'stable'David Lordbefore adoption6aeab5d
line 367why, one step back367 vformat = formatter.vformatupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 368why, one step back368Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 369–372why, one step back369 def wrapper(*args: t.Any, **kwargs: t.Any) -> str:370 if is_format_map:371 if kwargs:372 raise TypeError("format_map() takes no keyword arguments")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 373why, one step back373Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 374–377why, one step back374 if len(args) != 1:375 raise TypeError(376 f"format_map() takes exactly one argument ({len(args)} given)"377 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 378why, one step back378Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 379–385why, one step back379 kwargs = args[0]380 args = ()381382 return str_type(vformat(f_self, args, kwargs))383384 return update_wrapper(wrapper, value)385Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 386–392why, one step back386 def call(387 __self, # noqa: B902388 __context: Context,389 __obj: t.Any,390 *args: t.Any,391 **kwargs: t.Any,392 ) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 393–407why, one step back393 """Call an object from sandboxed code."""394395 # the double prefixes are to avoid double keyword argument396 # errors when proxying the call.397 if not __self.is_safe_callable(__obj):398 raise SecurityError(f"{__obj!r} is not safely callable")399 return __context.call(__obj, *args, **kwargs)400401402class ImmutableSandboxedEnvironment(SandboxedEnvironment):403 """Works exactly like the regular `SandboxedEnvironment` but does not404 permit modifications on the builtin mutable objects `list`, `set`, and405 `dict` by using the :func:`modifies_known_mutable` function.406 """407Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 408–409why, one step back408 def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:409 if not super().is_safe_attribute(obj, attr, value):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 410why, one step back410 return FalseMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 411why, one step back411update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 412–414why, one step back412 return not modifies_known_mutable(obj, attr)413414Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 415–416why, one step back415class SandboxedFormatter(Formatter):416 def __init__(self, env: Environment, **kwargs: t.Any) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 417why, one step back417 self._env = envMerge branch '3.0.x'David Lordbefore adoption896a621
line 418why, one step back418 super().__init__(**kwargs)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 419why, one step back419Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 420–421why, one step back420 def get_field(421 self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 422why, one step back422 ) -> tuple[t.Any, str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 423–432why, one step back423 first, rest = formatter_field_name_split(field_name)424 obj = self.get_value(first, args, kwargs)425 for is_attr, i in rest:426 if is_attr:427 obj = self._env.getattr(obj, i)428 else:429 obj = self._env.getitem(obj, i)430 return obj, first431432Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 433–434why, one step back433class SandboxedEscapeFormatter(SandboxedFormatter, EscapeFormatter):434 pass