Skip to content
Myr

improved sandbox and updated setup.py

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 4dcc237 · Browse files · 6 files+84 added−60 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+84 added−60 removed

  • other:+84 added−60 removed

6 files+84 added−60 removed

modified:docs/sandbox.rst+1 added-1 removed
26 unmodified lines
27.. autofunction:: unsafe2829.. autofunction:: is_internal_attribute3031.. autofunction:: modifies_builtin_mutable31.. autofunction:: modifies_known_mutable
modified:jinja2/_speedups.c+1 added-1 removed
155 unmodified lines
156 return s;157}158159160static PyObject *160static PyObject*161tb_set_next(PyObject *self, PyObject *args)162{163 PyTracebackObject *tb, *old;164 PyObject *next;
49 unmodified lines
modified:jinja2/runtime.py-4 removed
115 unmodified lines
116 """117 return dict(self.parent, **self.vars)118119 def call(__self, __obj, *args, **kwargs):120 """Called by the template code to inject the current context121 or environment as first arguments. Then forwards the call to122 the object with the arguments and keyword arguments.123 """120 if __debug__:121 __traceback_hide__ = True122 if isinstance(__obj, _context_function_types):123 if getattr(__obj, 'contextfunction', 0):
324 unmodified lines
modified:jinja2/sandbox.py+60 added-39 removed
11 unmodified lines
12 :copyright: Copyright 2008 by Armin Ronacher.13 :license: BSD.14"""15import operator16from UserDict import UserDict, DictMixin17from UserList import UserList18from sets import Set, ImmutableSet16from types import FunctionType, MethodType, TracebackType, CodeType, \17 FrameType, GeneratorType18from jinja2.runtime import Undefined19from jinja2.environment import Environment
9 unmodified lines
2930#: unsafe method attributes. function attributes are unsafe for methods too31UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])3236SET_TYPES = (ImmutableSet, Set, set)37MODIFYING_SET_ATTRIBUTES = set([38 'add', 'clear', 'difference_update', 'discard', 'pop', 'remove',39 'symmetric_difference_update', 'update'40])3342DICT_TYPES = (UserDict, DictMixin, dict)43MODIFYING_DICT_ATTRIBUTES = set(['clear', 'pop', 'popitem', 'setdefault',44 'update'])34from collections import deque35from sets import Set, ImmutableSet36from UserDict import UserDict, DictMixin37from UserList import UserList38_mutable_set_types = (ImmutableSet, Set, set)39_mutable_mapping_types = (UserDict, DictMixin, dict)40_mutable_sequence_types = (UserList, list)4146LIST_TYPES = (UserList, list)47MODIFYING_LIST_ATTRIBUTES = set(['append', 'reverse', 'insert', 'sort',48 'extend', 'remove'])42#: register Python 2.6 abstract base classes43try:44 from collections import MutableSet, MutableMapping, MutableSequence45 _mutable_set_types += (MutableSet,)46 _mutable_mapping_types += (MutableMapping,)47 _mutable_sequence_types += (MutableSequence,)48except ImportError:49 pass5051_mutable_spec = (52 (_mutable_set_types, frozenset([53 'add', 'clear', 'difference_update', 'discard', 'pop', 'remove',54 'symmetric_difference_update', 'update'55 ])),56 (_mutable_mapping_types, frozenset([57 'clear', 'pop', 'popitem', 'setdefault', 'update'58 ])),59 (_mutable_sequence_types, frozenset([60 'append', 'reverse', 'insert', 'sort', 'extend', 'remove'61 ])),62 (deque, frozenset([63 'append', 'appendleft', 'clear', 'extend', 'extendleft', 'pop',64 'popleft', 'remove', 'rotate'65 ]))66)676869def safe_range(*args):70 """A range that can't generate ranges with a length of more than71 MAX_RANGE items.72 """
30 unmodified lines
103 >>> is_internal_attribute(str, "upper")104 False105 """106 if isinstance(obj, FunctionType):89 return attr in UNSAFE_FUNCTION_ATTRIBUTES90 if isinstance(obj, MethodType):91 return attr in UNSAFE_FUNCTION_ATTRIBUTES or \92 attr in UNSAFE_METHOD_ATTRIBUTES93 if isinstance(obj, type):94 return attr == 'mro'95 if isinstance(obj, (CodeType, TracebackType, FrameType)):107 if attr in UNSAFE_FUNCTION_ATTRIBUTES:108 return True109 elif isinstance(obj, MethodType):110 if attr in UNSAFE_FUNCTION_ATTRIBUTES or \111 attr in UNSAFE_METHOD_ATTRIBUTES:112 return True113 elif isinstance(obj, type):114 if attr == 'mro':115 return True116 elif isinstance(obj, (CodeType, TracebackType, FrameType)):117 return True97 if isinstance(obj, GeneratorType):98 return attr == 'gi_frame'118 elif isinstance(obj, GeneratorType):119 if attr == 'gi_frame':120 return True121 return attr.startswith('__')122123102def modifies_builtin_mutable(obj, attr):124def modifies_known_mutable(obj, attr):125 """This function checks if an attribute on a builtin mutable object104 (list, dict or set) would modify it if called. It also supports105 the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.)126 (list, dict, set or deque) would modify it if called. It also supports127 the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and128 with Python 2.6 onwards the abstract base classes `MutableSet`,129 `MutableMapping`, and `MutableSequence`.130107 >>> modifies_builtin_mutable({}, "clear")131 >>> modifies_known_mutable({}, "clear")132 True109 >>> modifies_builtin_mutable({}, "keys")133 >>> modifies_known_mutable({}, "keys")134 False111 >>> modifies_builtin_mutable([], "append")135 >>> modifies_known_mutable([], "append")136 True113 >>> modifies_builtin_mutable([], "index")137 >>> modifies_known_mutable([], "index")138 False139140 If called with an unsupported object (such as unicode) `False` is141 returned.142119 >>> modifies_builtin_mutable("foo", "upper")143 >>> modifies_known_mutable("foo", "upper")144 False145 """122 if isinstance(obj, LIST_TYPES):123 return attr in MODIFYING_LIST_ATTRIBUTES124 elif isinstance(obj, DICT_TYPES):125 return attr in MODIFYING_DICT_ATTRIBUTES126 elif isinstance(obj, SET_TYPES):127 return attr in MODIFYING_SET_ATTRIBUTES146 for typespec, unsafe in _mutable_spec:147 if isinstance(obj, typespec):148 return attr in unsafe149 return False150151152class SandboxedEnvironment(Environment):
66 unmodified lines
219220class ImmutableSandboxedEnvironment(SandboxedEnvironment):221 """Works exactly like the regular `SandboxedEnvironment` but does not222 permit modifications on the builtin mutable objects `list`, `set`, and202 `dict` by using the :func:`modifies_builtin_mutable` function.223 `dict` by using the :func:`modifies_known_mutable` function.224 """225226 def is_safe_attribute(self, obj, attr, value):227 if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):228 return False208 return not modifies_builtin_mutable(obj, attr)229 return not modifies_known_mutable(obj, attr)
modified:jinja2/utils.py+21 added-14 removed
251 unmodified lines
252 return self.__class__(unicode(escape(other)) + unicode(self))253 return NotImplemented254255 def __mul__(self, num):256 if not isinstance(num, (int, long)):257 return NotImplemented258 return self.__class__(unicode.__mul__(self, num))256 if isinstance(num, (int, long)):257 return self.__class__(unicode.__mul__(self, num))258 return NotImplemented259 __rmul__ = __mul__260261 def __mod__(self, arg):262 if isinstance(arg, tuple):
55 unmodified lines
318319 def make_wrapper(name):320 orig = getattr(unicode, name)321 def func(self, *args, **kwargs):322 args = list(args)323 for idx, arg in enumerate(args):324 if hasattr(arg, '__html__') or isinstance(arg, basestring):325 args[idx] = escape(arg)326 for name, arg in kwargs.iteritems():327 if hasattr(arg, '__html__') or isinstance(arg, basestring):328 kwargs[name] = escape(arg)322 args = _escape_argspec(list(args), enumerate(args))323 _escape_argspec(kwargs, kwargs.iteritems())324 return self.__class__(orig(self, *args, **kwargs))325 func.__name__ = orig.__name__326 func.__doc__ = orig.__doc__327 return func328329 for method in '__getitem__', '__getslice__', 'capitalize', \330 'title', 'lower', 'upper', 'replace', 'ljust', \331 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \332 'translate', 'expandtabs', 'swapcase', 'zfill':333 locals()[method] = make_wrapper(method)334335 # new in python 2.5336 if hasattr(unicode, 'partition'):341 locals().update(342 partition=make_wrapper('partition'),343 rpartition=make_wrapper('rpartition')344 )337 partition = make_wrapper('partition'),338 rpartition = make_wrapper('rpartition')339340 # new in python 2.6341 if hasattr(unicode, 'format'):342 format = make_wrapper('format')343344 del method, make_wrapper345346347def _escape_argspec(obj, iterable):348 """Helper for various string-wrapped functions."""349 for key, value in iterable:350 if hasattr(value, '__html__') or isinstance(value, basestring):351 obj[key] = escape(value)352 return obj353354355class _MarkupEscapeHelper(object):356 """Helper for Markup.__mod__"""357358 def __init__(self, obj):
217 unmodified lines
modified:setup.py+1 added-1 removed
118 unmodified lines
119 'Topic :: Text Processing :: Markup :: HTML'120 ],121 packages=['jinja2'],122 data_files=[123 ##('docs', list(list_files('docs/_build/html')))123 ('docs', list(list_files('docs/_build/html')))124 ],125 features={126 'speedups': Feature("optional C speed-enhancements",127 standard=True,
11 unmodified lines