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
Provenance
- Commit
d71fff0- Tree
e53706c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
4dcc237
6 files changed+84 added−60 removed
modified:docs/sandbox.rst+1 added-1 removed
26 unmodified lines27 .. autofunction:: unsafe28 29 .. autofunction:: is_internal_attribute30 31-.. autofunction:: modifies_builtin_mutable31+.. autofunction:: modifies_known_mutablemodified:jinja2/_speedups.c+1 added-1 removed
155 unmodified lines156 return s;157 }158 159 160-static PyObject *160+static PyObject*161 tb_set_next(PyObject *self, PyObject *args)162 {163 PyTracebackObject *tb, *old;164 PyObject *next;49 unmodified linesmodified:jinja2/runtime.py-4 removed
115 unmodified lines116 """117 return dict(self.parent, **self.vars)118 119 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 linesmodified:jinja2/sandbox.py+60 added-39 removed
11 unmodified lines12 :copyright: Copyright 2008 by Armin Ronacher.13 :license: BSD.14 """15 import operator16-from UserDict import UserDict, DictMixin17-from UserList import UserList18-from sets import Set, ImmutableSet16 from types import FunctionType, MethodType, TracebackType, CodeType, \17 FrameType, GeneratorType18 from jinja2.runtime import Undefined19 from jinja2.environment import Environment9 unmodified lines29 30 #: unsafe method attributes. function attributes are unsafe for methods too31 UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])32 36-SET_TYPES = (ImmutableSet, Set, set)37-MODIFYING_SET_ATTRIBUTES = set([38- 'add', 'clear', 'difference_update', 'discard', 'pop', 'remove',39- 'symmetric_difference_update', 'update'40-])33 42-DICT_TYPES = (UserDict, DictMixin, dict)43-MODIFYING_DICT_ATTRIBUTES = set(['clear', 'pop', 'popitem', 'setdefault',44- 'update'])34+from collections import deque35+from sets import Set, ImmutableSet36+from UserDict import UserDict, DictMixin37+from UserList import UserList38+_mutable_set_types = (ImmutableSet, Set, set)39+_mutable_mapping_types = (UserDict, DictMixin, dict)40+_mutable_sequence_types = (UserList, list)41 46-LIST_TYPES = (UserList, list)47-MODIFYING_LIST_ATTRIBUTES = set(['append', 'reverse', 'insert', 'sort',48- 'extend', 'remove'])42+#: register Python 2.6 abstract base classes43+try:44+ from collections import MutableSet, MutableMapping, MutableSequence45+ _mutable_set_types += (MutableSet,)46+ _mutable_mapping_types += (MutableMapping,)47+ _mutable_sequence_types += (MutableSequence,)48+except ImportError:49+ pass50 51+_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+)67 68+69 def safe_range(*args):70 """A range that can't generate ranges with a length of more than71 MAX_RANGE items.72 """30 unmodified lines103 >>> 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('__')122 123 102-def modifies_builtin_mutable(obj, attr):124+def 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`.130 107- >>> 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 False139 140 If called with an unsupported object (such as unicode) `False` is141 returned.142 119- >>> 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 False150 151 152 class SandboxedEnvironment(Environment):66 unmodified lines219 220 class 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 """225 226 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 lines252 return self.__class__(unicode(escape(other)) + unicode(self))253 return NotImplemented254 255 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__260 261 def __mod__(self, arg):262 if isinstance(arg, tuple):55 unmodified lines318 319 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 func328+329 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)334 335 # 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')339+340+ # new in python 2.6341+ if hasattr(unicode, 'format'):342+ format = make_wrapper('format')343+344 del method, make_wrapper345 346 347+def _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 obj353+354+355 class _MarkupEscapeHelper(object):356 """Helper for Markup.__mod__"""357 358 def __init__(self, obj):217 unmodified linesmodified:setup.py+1 added-1 removed
118 unmodified lines119 '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