added sandbox and exchageable undefined objects
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 f437fa3 · Browse files · 9 files·+230 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+230 added−49 removed
- other:+230 added−49 removed
Provenance
- Commit
c63243e- Tree
c68fa37- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f437fa3
9 files changed+230 added−49 removed
modified:jinja2/__init__.py+1 added
55 unmodified lines56 :copyright: 2008 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58 """59 from jinja2.environment import Environment60+from jinja2.runtime import Undefined, DebugUndefined, StrictUndefinedmodified:jinja2/compiler.py+11 added-8 removed
455 unmodified lines456 # generate the root render function.457 self.writeline('def root(globals, environment=environment'458 ', standalone=False):', extra=1)459 self.indent()460- self.writeline('context = TemplateContext(globals, %r, blocks'461- ', standalone)' % self.filename)460+ self.writeline('context = TemplateContext(environment, globals, %r, '461+ 'blocks, standalone)' % self.filename)462 if have_extends:463 self.writeline('parent_root = None')464 self.outdent()465 146 unmodified lines612 613 # the expression pointing to the parent loop. We make the614 # undefined a bit more debug friendly at the same time.615 parent_loop = 'loop' in aliases and aliases['loop'] \616- or "Undefined('loop', extra=%r)" % \616+ or "environment.undefined('loop', extra=%r)" % \617 'the filter section of a loop as well as the ' \618 'else block doesn\'t have access to the special ' \619 "'loop' variable of the current loop. Because " \620 'there is no parent loop it\'s undefined.'69 unmodified lines690 self.write('context[%r] = ' % node.name)691 arg_tuple = ', '.join(repr(x.name) for x in node.args)692 if len(node.args) == 1:693 arg_tuple += ','694- self.write('l_%s = Macro(macro, %r, (%s), (' % (node.name, node.name,695- arg_tuple))694+ self.write('l_%s = Macro(environment, macro, %r, (%s), (' %695+ (node.name, node.name, arg_tuple))696 for arg in node.defaults:697 self.visit(arg, macro_frame)698 self.write(', ')699 self.write('), %s, %s)' % (14 unmodified lines714 self.outdent()715 arg_tuple = ', '.join(repr(x.name) for x in node.args)716 if len(node.args) == 1:717 arg_tuple += ','718- self.writeline('caller = Macro(call, None, (%s), (' % arg_tuple)718+ self.writeline('caller = Macro(environment, call, None, (%s), (' %719+ arg_tuple)720 for arg in node.defaults:721 self.visit(arg)722 self.write(', ')723 self.write('), %s, 0)' % (call_frame.accesses_arguments and '1' or '0'))236 unmodified lines960 if isinstance(const, (int, long, float)):961 self.visit(node.node, frame)962 self.write('[%s]' % const)963 return963- self.write('subscribe(')964+ self.write('environment.subscribe(')965 self.visit(node.node, frame)966 self.write(', ')967 if have_const:968 self.write(repr(const))50 unmodified lines1019 self.visit(node.expr2, frame)1020 self.write(')')1021 1022 def visit_Call(self, node, frame, extra_kwargs=None):1023+ if self.environment.sandboxed:1024+ self.write('environment.call(')1025 self.visit(node.node, frame)1023- self.write('(')1026+ self.write(self.environment.sandboxed and ', ' or '(')1027 self.signature(node, frame, False, extra_kwargs)1028 self.write(')')1029 1030 def visit_Keyword(self, node, frame):3 unmodified linesmodified:jinja2/defaults.py+4 added-6 removed
1 # -*- coding: utf-8 -*-2 """3- jinja.defaults4- ~~~~~~~~~~~~~~3+ jinja2.defaults4+ ~~~~~~~~~~~~~~~5 6 Jinja default filters and tags.7 8- :copyright: 2007 by Armin Ronacher.8+ :copyright: 2007-2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from jinja2.filters import FILTERS as DEFAULT_FILTERS12 from jinja.tests import TESTS as DEFAULT_TESTS13+14 DEFAULT_NAMESPACE = {15 'range': xrange16 }16-17-18-__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']modified:jinja2/environment.py+75 added
10 unmodified lines11 from jinja2.lexer import Lexer12 from jinja2.parser import Parser13 from jinja2.optimizer import optimize14 from jinja2.compiler import generate15+from jinja2.runtime import Undefined16 from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE17 18 19 class Environment(object):3 unmodified lines23 important shared variables like configuration, filters, tests,24 globals and others.25 """26 27+ #: if this environment is sandboxed. Modifying this variable won't make28+ #: the environment sandboxed though. For a real sandboxed environment29+ #: have a look at jinja2.sandbox30+ sandboxed = False31+32 def __init__(self,33 block_start_string='{%',34 block_end_string='%}',35 variable_start_string='{{',2 unmodified lines38 comment_end_string='#}',39 line_statement_prefix=None,40 trim_blocks=False,41 optimized=True,42+ undefined=Undefined,43 loader=None):44 """Here the possible initialization parameters:45 46 ========================= ============================================14 unmodified lines61 after a block is removed (block, not62 variable tag!). Defaults to ``False``.63 `optimized` should the optimizer be enabled? Default is64 ``True``.65+ `undefined` a subclass of `Undefined` that is used to66+ represent undefined variables.67 `loader` the loader which should be used.68 ========================= ============================================69 """70+ assert issubclass(undefined, Undefined), 'undefined must be ' \71+ 'a subclass of undefined because filters depend on it.'72 73 # lexer / parser information74 self.block_start_string = block_start_string75 self.block_end_string = block_end_string2 unmodified lines78 self.comment_start_string = comment_start_string79 self.comment_end_string = comment_end_string80 self.line_statement_prefix = line_statement_prefix81 self.trim_blocks = trim_blocks82+ self.undefined = undefined83 self.optimized = optimized84 85 # defaults86 self.filters = DEFAULT_FILTERS.copy()11 unmodified lines98 99 # create lexer100 self.lexer = Lexer(self)101 102+ def subscribe(self, obj, argument):103+ """Get an item or attribute of an object."""104+ try:105+ return getattr(obj, str(argument))106+ except (AttributeError, UnicodeError):107+ try:108+ return obj[argument]109+ except (TypeError, LookupError):110+ return self.undefined(obj, argument)111+112 def parse(self, source, filename=None):113 """Parse the sourcecode and return the abstract syntax tree. This tree114 of nodes is used by the compiler to convert the template into115 executable source- or bytecode.91 unmodified lines207 gen = self.root_render_func(context)208 # skip the first item which is a reference to the stream209 gen.next()210 return gen211+212+ def __repr__(self):213+ return '<%s %r>' % (214+ self.__class__.__name__,215+ self.name216+ )217+218+219+class TemplateStream(object):220+ """Wraps a genererator for outputing template streams."""221+222+ def __init__(self, gen):223+ self._gen = gen224+ self._next = gen.next225+ self.buffered = False226+227+ def disable_buffering(self):228+ """Disable the output buffering."""229+ self._next = self._gen.next230+ self.buffered = False231+232+ def enable_buffering(self, size=5):233+ """Enable buffering. Buffer `size` items before yielding them."""234+ if size <= 1:235+ raise ValueError('buffer size too small')236+ self.buffered = True237+238+ def buffering_next():239+ buf = []240+ c_size = 0241+ push = buf.append242+ next = self._gen.next243+244+ try:245+ while 1:246+ item = next()247+ if item:248+ push(item)249+ c_size += 1250+ if c_size >= size:251+ raise StopIteration()252+ except StopIteration:253+ if not c_size:254+ raise255+ return u''.join(buf)256+257+ self._next = buffering_next258+259+ def __iter__(self):260+ return self261+262+ def next(self):263+ return self._next()modified:jinja2/filters.py+1 added-2 removed
14 unmodified lines15 except ImportError:16 itemgetter = lambda a: lambda b: b[a]17 from urllib import urlencode, quote18 from jinja2.utils import escape, pformat19-from jinja2.nodes import Undefined19+from jinja2.runtime import Undefined20 21 22-22 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')23 24 25 def contextfilter(f):830 unmodified linesmodified:jinja2/nodes.py+1 added-2 removed
14 unmodified lines15 import operator16 from itertools import chain, izip17 from collections import deque18 from copy import copy19-from jinja2.runtime import Undefined, subscribe19 20 21 _binop_to_func = {22 '*': operator.mul,438 unmodified lines461 def as_const(self):462 if self.ctx != 'load':463 raise Impossible()464 try:466- return subscribe(self.node.as_const(), self.arg.as_const())465+ return environmen.subscribe(self.node.as_const(), self.arg.as_const())466 except:467 raise Impossible()468 469 def can_assign(self):105 unmodified linesmodified:jinja2/optimizer.py+1 added-1 removed
19 unmodified lines20 :license: GNU GPL.21 """22 from jinja2 import nodes23 from jinja2.visitor import NodeVisitor, NodeTransformer24-from jinja2.runtime import subscribe, LoopContext24+from jinja2.runtime import LoopContext25 26 27 def optimize(node, environment, context_hint=None):28 """The context hint can be used to perform an static optimization229 unmodified linesmodified:jinja2/runtime.py+49 added-30 removed
12 unmodified lines13 except ImportError:14 defaultdict = None15 16 17-__all__ = ['subscribe', 'LoopContext', 'StaticLoopContext', 'TemplateContext',18- 'Macro', 'IncludedTemplate', 'Undefined', 'TemplateData']17+__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',18+ 'Macro', 'IncludedTemplate', 'TemplateData']19 20 21-def subscribe(obj, argument):22- """Get an item or attribute of an object."""23- try:24- return getattr(obj, str(argument))25- except (AttributeError, UnicodeError):26- try:27- return obj[argument]28- except (TypeError, LookupError):29- return Undefined(obj, argument)30-31-21 class TemplateData(unicode):22 """Marks data as "coming from the template". This is used to let the23 system know that this data is already processed if a finalization is24 used."""8 unmodified lines33 update and other methods will not work as they seem (they don't update34 the exported variables for example).35 """36 48- def __init__(self, globals, filename, blocks, standalone):37+ def __init__(self, environment, globals, filename, blocks, standalone):38 dict.__init__(self, globals)39+ self.environment = environment40 self.exported = set()41 self.filename = filename42 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())43 9 unmodified lines53 """Render a parent block."""54 try:55 func = self.blocks[block][-2]56 except LookupError:67- return Undefined('super', extra='there is probably no parent '68- 'block with this name')57+ return self.environment.undefined('super',58+ extra='there is probably no parent block with this name')59 return SuperBlock(block, self, func)60 61 def __setitem__(self, key, value):62 """If we set items to the dict we track the variables set so14 unmodified lines77 if defaultdict is None:78 def __getitem__(self, name):79 if name in self:80 return self[name]91- return Undefined(name)81+ return self.environment.undefined(name)82 else:83 def __missing__(self, key):94- return Undefined(key)84+ return self.environment.undefined(key)85 86 def __repr__(self):87 return '<%s %s of %r>' % (88 self.__class__.__name__,127 unmodified lines216 217 class Macro(object):218 """Wraps a macro."""219 230- def __init__(self, func, name, arguments, defaults, catch_all, caller):220+ def __init__(self, environment, func, name, arguments, defaults, catch_all, caller):221+ self._environment = environment222 self._func = func223 self.name = name224 self.arguments = arguments225 self.defaults = defaults15 unmodified lines241 except KeyError:242 try:243 value = self.defaults[idx - arg_count]244 except IndexError:254- value = Undefined(name, extra='parameter not provided')245+ value = self._environment.undefined(name,246+ extra='parameter not provided')247 arguments['l_' + name] = value248 if self.caller:249 caller = kwargs.pop('caller', None)250 if caller is None:259- caller = Undefined('caller', extra='The macro was called '260- 'from an expression and not a call block.')251+ caller = self._environment.undefined('caller',252+ extra='The macro was called from an expression and not '253+ 'a call block.')254 arguments['l_caller'] = caller255 if self.catch_all:256 arguments['l_arguments'] = kwargs257 return self._func(**arguments)5 unmodified lines263 )264 265 266 class Undefined(object):274- """The object for undefined values."""267+ """The default undefined implementation. This undefined implementation268+ can be printed and iterated over, but every other access will raise a269+ `NameError`. Custom undefined classes must subclass this.270+ """271 272 def __init__(self, name=None, attr=None, extra=None):273 if attr is None:274 self._undefined_hint = '%r is undefined' % name2 unmodified lines277 % (attr, name)278 if extra is not None:279 self._undefined_hint += ' (' + extra + ')'280 285- def fail(self, *args, **kwargs):281+ def fail_with_error(self, *args, **kwargs):282 raise NameError(self._undefined_hint)287- __getattr__ = __getitem__ = __add__ = __mul__ = __div__ = \288- __realdiv__ = __floordiv__ = __mod__ = __pos__ = __neg__ = \289- __call__ = fail290- del fail283+ __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \284+ __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \285+ __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \286+ __getattr__ = __getitem__ = fail_with_error287+ del fail_with_error288 289 def __unicode__(self):293- return ''290+ return u''291 292+ def __str__(self):293+ return self.__unicode__().encode('utf-8')294+295 def __repr__(self):296- return 'Undefined'296+ return 'undefined'297 298 def __len__(self):299 return 0300 301 def __iter__(self):302 if 0:303 yield None304+305+ def __nonzero__(self):306+ return False307+308+309+class DebugUndefined(Undefined):310+ """An undefined that returns the debug info when printed."""311+312+ def __unicode__(self):313+ return u'{{ %s }}' % self._undefined_hint314+315+316+class StrictUndefined(Undefined):317+ """An undefined that barks on print and iteration."""318+319+ def fail_with_error(self, *args, **kwargs):320+ raise NameError(self._undefined_hint)321+ __iter__ = __unicode__ = __len__ = fail_with_error322+ del fail_with_erroradded:jinja2/sandbox.py+87 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja2.sandbox4+ ~~~~~~~~~~~~~~5+6+ Adds a sandbox layer to Jinja as it was the default behavior in the old7+ Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the8+ default behavior is easier to use.9+10+ The behavior can be changed by subclassing the environment.11+12+ :copyright: Copyright 2008 by Armin Ronacher.13+ :license: BSD.14+"""15+from types import FunctionType, MethodType16+from jinja2.runtime import Undefined17+from jinja2.environment import Environment18+19+20+#: maximum number of items a range may produce21+MAX_RANGE = 10000022+23+24+def safe_range(*args):25+ """A range that can't generate ranges with a length of more than26+ MAX_RANGE items."""27+ rng = xrange(*args)28+ if len(rng) > MAX_RANGE:29+ raise OverflowError('range too big')30+ return rng31+32+33+def unsafe(f):34+ """Mark a function as unsafe."""35+ f.unsafe_callable = True36+ return f37+38+39+class SandboxedEnvironment(Environment):40+ """The sandboxed environment"""41+ sandboxed = True42+43+ def __init__(self, *args, **kwargs):44+ Environment.__init__(self, *args, **kwargs)45+ self.globals['range'] = safe_range46+47+ def is_safe_attribute(self, obj, attr):48+ """The sandboxed environment will call this method to check if the49+ attribute of an object is safe to access. Per default all attributes50+ starting with an underscore are considered private as well as the51+ special attributes of functions and methods.52+ """53+ if attr.startswith('_'):54+ return False55+ if isinstance(obj, FunctionType):56+ return not attr.startswith('func_')57+ if isinstance(obj, MethodType):58+ return not attr.startswith('im_')59+ return True60+61+ def is_safe_callable(self, obj):62+ """Check if an object is safely callable. Per default a function is63+ considered safe unless the `unsafe_callable` attribute exists and is64+ truish. Override this method to alter the behavior, but this won't65+ affect the `unsafe` decorator from this module.66+ """67+ return not getattr(obj, 'unsafe_callable', False)68+69+ def subscribe(self, obj, arg):70+ """Subscribe an object from sandboxed code."""71+ try:72+ return obj[arg]73+ except (TypeError, LookupError):74+ if not self.is_safe_attribute(obj, arg):75+ return Undefined(obj, arg, extra='attribute unsafe')76+ try:77+ return getattr(obj, str(arg))78+ except (AttributeError, UnicodeError):79+ return Undefined(obj, arg)80+81+ def call(__self, __obj, *args, **kwargs):82+ """Call an object from sandboxed code."""83+ # the double prefixes are to avoid double keyword argument84+ # errors when proxying the call.85+ if not __self.is_safe_callable(__obj):86+ raise TypeError('%r is not safely callable' % (__obj,))87+ return __obj(*args, **kwargs)