3 C\B@sdZddlZddlZddlmZddlmZddlmZddl m Z m Z ddl m Z ddlmZdd lmZd Ze red d d ddgZneZedddgZeddgZeddgZeddgZddlZejddeddddlmZefZefZe fZ!y6ddl"m"Z"m#Z#ddl$m$Z$ee"e#f7Zee$f7ZWne%k rDYnXydd l&m'Z'ee'f7ZWne%k rvYnXdd!lm(Z(m)Z)m*Z*ee(f7Zee)f7Ze!e*f7Z!ee+d"d#d$d%d&d'd(d)gfee+d#d&d*d+d)gfe!e+d,d-d.d/d0d'gfee+d,d1d#d0d2d&d3d'd4g ffZ,Gd5d6d6eZ-d7d8Z.d9d:Z/d;d<Z0d=d>Z1d?d@Z2GdAdBdBeZ3GdCdDdDe3Z4yddEl5m6Z6Wne%k rdFdGZ6YnXGdHdIdIe7Z8GdJdKdKe8eZ9GdLdMdMe8eZ:dS)Naj jinja2.sandbox ~~~~~~~~~~~~~~ Adds a sandbox layer to Jinja as it was the default behavior in the old Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the default behavior is easier to use. The behavior can be changed by subclassing the environment. :copyright: (c) 2017 by the Jinja Team. :license: BSD. N)Mapping) Environment) SecurityError) string_typesPY2)Markup)EscapeFormatter) FormatteriZ func_closure func_codeZ func_dictZ func_defaultsZ func_globalsZim_classZim_funcZim_selfgi_framegi_codecr_framecr_codeag_codeag_frameignorezthe sets modulezjinja2.sandbox)module)deque)UserDict DictMixin)UserList)Set) MutableSetMutableMappingMutableSequenceaddcleardifference_updatediscardpopremovesymmetric_difference_updateupdatepopitem setdefaultappendreverseinsertsortextend appendleft extendleftpopleftrotatec@s0eZdZdZddZddZddZdd Zd S) _MagicFormatMappingzThis class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See https://bugs.python.org/issue13598 for information about why this is necessary. cCs||_||_d|_dS)Nr)_args_kwargs _last_index)selfargskwargsr5f/private/var/folders/pf/wv4htv3x0qs2c2mp0dnn0kchsvlck3/T/pip-install-emcbgzcf/jinja2/jinja2/sandbox.py__init__rsz_MagicFormatMapping.__init__c CsN|dkrD|j}|jd7_y |j|Stk r:YnXt|}|j|S)N)r1r/ LookupErrorstrr0)r2keyidxr5r5r6 __getitem__ws z_MagicFormatMapping.__getitem__cCs t|jS)N)iterr0)r2r5r5r6__iter__sz_MagicFormatMapping.__iter__cCs t|jS)N)lenr0)r2r5r5r6__len__sz_MagicFormatMapping.__len__N)__name__ __module__ __qualname____doc__r7r>r@rBr5r5r5r6r.js  r.cCs:t|tjtjf s|jdkr"dS|j}t|tr6|SdS)Nformat format_map)rGrH) isinstancetypes MethodTypeBuiltinMethodTyperC__self__r)callableobjr5r5r6inspect_format_methods   rPcGs$t|}t|tkr tdt|S)zWA range that can't generate ranges with a length of more than MAX_RANGE items. z+range too big, maximum size for range is %d)rangerA MAX_RANGE OverflowError)r3rngr5r5r6 safe_ranges  rUcCs d|_|S)znMarks a function or method as unsafe. :: @unsafe def delete(self): pass T)unsafe_callable)fr5r5r6unsafes rXcCst|tjr|tkrdSnt|tjr<|tks6|tkrdSnt|trT|dkrdSnzt|tjtjtj frndSt|tj r|t krdSnFt tdrt|tj r|tkrdSn"t tdrt|tjr|tkrdS|jdS)aTest if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False Tmro CoroutineTypeAsyncGeneratorType__)rIrJ FunctionTypeUNSAFE_FUNCTION_ATTRIBUTESrKUNSAFE_METHOD_ATTRIBUTEStypeCodeType TracebackType FrameType GeneratorTypeUNSAFE_GENERATOR_ATTRIBUTEShasattrrZUNSAFE_COROUTINE_ATTRIBUTESr[!UNSAFE_ASYNC_GENERATOR_ATTRIBUTES startswith)rOattrr5r5r6is_internal_attributes,    rkcCs(x"tD]\}}t||r||kSqWdS)aThis function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `MutableSet`, `MutableMapping`, and `MutableSequence`. >>> modifies_known_mutable({}, "clear") True >>> modifies_known_mutable({}, "keys") False >>> modifies_known_mutable([], "append") True >>> modifies_known_mutable([], "index") False If called with an unsupported object (such as unicode) `False` is returned. >>> modifies_known_mutable("foo", "upper") False F) _mutable_specrI)rOrjZtypespecrXr5r5r6modifies_known_mutables  rmc@seZdZdZdZejejejej ej ej ej dZ ejejdZeZeZddZddZd d Zd d Zd dZddZddZddZddZdddZddZdS)SandboxedEnvironmentaThe sandboxed environment. It works like the regular environment but tells the compiler to generate sandboxed code. Additionally subclasses of this environment may override the methods that tell the runtime what attributes or functions are safe to access. If the template tries to access insecure code a :exc:`SecurityError` is raised. However also other exceptions may occur during the rendering so the caller has to ensure that all exceptions are caught. T)+-*/z//z**%)rorpcCsdS)aCalled during template compilation with the name of a unary operator to check if it should be intercepted at runtime. If this method returns `True`, :meth:`call_unop` is excuted for this unary operator. The default implementation of :meth:`call_unop` will use the :attr:`unop_table` dictionary to perform the operator with the same logic as the builtin one. The following unary operators are interceptable: ``+`` and ``-`` Intercepted calls are always slower than the native operator call, so make sure only to intercept the ones you are interested in. .. versionadded:: 2.6 Fr5)r2operatorr5r5r6intercept_unop+sz#SandboxedEnvironment.intercept_unopcOs8tj|f||t|jd<|jj|_|jj|_dS)NrQ) rr7rUglobalsdefault_binop_tablecopy binop_tabledefault_unop_table unop_table)r2r3r4r5r5r6r7=s  zSandboxedEnvironment.__init__cCs|jdpt|| S)aYThe sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python objects as returned by the :func:`is_internal_attribute` function. _)rirk)r2rOrjvaluer5r5r6is_safe_attributeCsz&SandboxedEnvironment.is_safe_attributecCst|ddpt|dd S)aCheck if an object is safely callable. Per default a function is considered safe unless the `unsafe_callable` attribute exists and is True. Override this method to alter the behavior, but this won't affect the `unsafe` decorator from this module. rVFZ alters_data)getattr)r2rOr5r5r6is_safe_callableLs z%SandboxedEnvironment.is_safe_callablecCs|j|||S)zFor intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 )ry)r2contextrtleftrightr5r5r6 call_binopUszSandboxedEnvironment.call_binopcCs|j||S)zFor intercepted unary operator calls (:meth:`intercepted_unops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 )r{)r2rrtargr5r5r6 call_unop^szSandboxedEnvironment.call_unopcCsy||Sttfk rt|try t|}Wntk rFYnDXyt||}Wntk rjYn X|j|||r~|S|j ||SYnX|j ||dS)z(Subscribe an object from sandboxed code.)rOname) TypeErrorr:rIrr; ExceptionrAttributeErrorr~unsafe_undefined undefined)r2rOZargumentrjr}r5r5r6getitemgs   zSandboxedEnvironment.getitemcCsryt||}Wn6tk rDy||Sttfk r>YnXYn X|j|||rX|S|j||S|j||dS)zSubscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring. )rOr)rrrr:r~rr)r2rO attributer}r5r5r6r|s  zSandboxedEnvironment.getattrcCs|jd||jjf||tdS)z1Return an undefined object for unsafe attributes.z.access to attribute %r of %r object is unsafe.)rrOexc)r __class__rCr)r2rOrr5r5r6rs z%SandboxedEnvironment.unsafe_undefinedNcCst|trt||j}nt|}|dk rf|jdkrft|dksB|rZtdt||dk |d}d}t||}|j |||}t ||S)zIf a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. NrHr9z0format_map() takes exactly one argument %d givenr) rIrSandboxedEscapeFormatterescapeSandboxedFormatterrCrArr.vformatr`)r2sr3r4Z format_func formatterrvr5r5r6 format_strings  z"SandboxedEnvironment.format_stringcOsJt|}|dk r |j||||S|j|s8td|f|j|f||S)z#Call an object from sandboxed code.Nz%r is not safely callable)rPrrrcall)Z_SandboxedEnvironment__selfZ_SandboxedEnvironment__contextZ_SandboxedEnvironment__objr3r4fmtr5r5r6rs  zSandboxedEnvironment.call)N)rCrDrErFZ sandboxedrtrsubmultruedivfloordivpowmodrwposnegrz frozensetZintercepted_binopsZintercepted_unopsrur7r~rrrrrrrrr5r5r5r6rns0        rnc@seZdZdZddZdS)ImmutableSandboxedEnvironmentzWorks exactly like the regular `SandboxedEnvironment` but does not permit modifications on the builtin mutable objects `list`, `set`, and `dict` by using the :func:`modifies_known_mutable` function. cCs tj||||sdSt|| S)NF)rnr~rm)r2rOrjr}r5r5r6r~sz/ImmutableSandboxedEnvironment.is_safe_attributeN)rCrDrErFr~r5r5r5r6rsr)formatter_field_name_splitcCs|jS)N)Z_formatter_field_name_split) field_namer5r5r6rsrc@seZdZddZddZdS)SandboxedFormatterMixincCs ||_dS)N)_env)r2envr5r5r6r7sz SandboxedFormatterMixin.__init__c CsVt|\}}|j|||}x2|D]*\}}|r<|jj||}q |jj||}q W||fS)N)r get_valuerrr) r2rr3r4firstrestrOis_attrir5r5r6 get_fields z!SandboxedFormatterMixin.get_fieldN)rCrDrEr7rr5r5r5r6rsrc@seZdZddZdS)rcCstj||tj|dS)N)rr7r )r2rr5r5r6r7s zSandboxedFormatter.__init__N)rCrDrEr7r5r5r5r6rsrc@seZdZddZdS)rcCstj||tj||dS)N)rr7r)r2rrr5r5r6r7s z!SandboxedEscapeFormatter.__init__N)rCrDrEr7r5r5r5r6rsr);rFrJrt collectionsrZjinja2.environmentrZjinja2.exceptionsrZjinja2._compatrrZ jinja2.utilsrZ markupsaferstringr rRsetr^r_rergrhwarningsfilterwarningsDeprecationWarningrZ_mutable_set_typesdictZ_mutable_mapping_typeslistZ_mutable_sequence_typesrrr ImportErrorZsetsrrrrrrlr.rPrUrXrkrmrnr_stringrobjectrrrr5r5r5r6s                        $O