Exemplo n.º 1
0
    def __init__(self, check, context):
        self.check = check
        self.env = ImmutableSandboxedEnvironment()

        _ctx = copy.deepcopy(context)
        self.variables = _ctx.pop("variables", {})
        self.ctx = {"depc": _ctx}
Exemplo n.º 2
0
 def __init__(
     self, string: str, context: Dict[str, Any] = {}, *args, **kwargs
 ) -> None:
     assert isinstance(string, str), "Expression must be a string"
     self.string = string
     self.environment = ImmutableSandboxedEnvironment(undefined=StrictUndefined)
     self.context = context
     self.environment.globals = self.context
Exemplo n.º 3
0
def create_sandboxed_environment(*, loader: Optional[BaseLoader]=None) \
                                -> Environment:
    """Create a sandboxed environment."""
    if loader is None:
        # A loader that never finds a template.
        loader = FunctionLoader(lambda name: None)

    return ImmutableSandboxedEnvironment(loader=loader, autoescape=True)
Exemplo n.º 4
0
def create_sandboxed_env():
    """Create a sandboxed environment."""
    # A loader that never finds a template.
    dummy_loader = FunctionLoader(lambda name: None)

    return ImmutableSandboxedEnvironment(loader=dummy_loader,
                                         autoescape=True,
                                         lstrip_blocks=True,
                                         trim_blocks=True)
    def __init__(self, args={}):
        self.log = RevSysLogger(args["verbose_debug"])
        self.nginx_conf = {}

        self._set_default_values()
        self._interpret_arguments(args)

        self.env = ImmutableSandboxedEnvironment(line_statement_prefix=None,
                                                 trim_blocks=True,
                                                 lstrip_blocks=True,
                                                 undefined=StrictUndefined)
Exemplo n.º 6
0
def render(template: str, context: Dict[str, Any] = {}) -> str:
    environment = ImmutableSandboxedEnvironment(undefined=StrictUndefined)
    environment.globals = context

    jinja_template = environment.from_string(template)
    output = None

    try:
        output = jinja_template.render()
    except UndefinedError as e:
        raise TemplateException(e.message)
    except TypeError as e:
        if str(e) == "no loader for this environment specified":
            raise TemplateException("Extending templates is not allowed")
        else:
            raise e

    return output
Exemplo n.º 7
0
def jinja_render(content, context):
    if not content:
        content = {}
    from jinja2.runtime import Undefined
    env = ImmutableSandboxedEnvironment(
        loader=DjangoLoader(),
        cache_size=0,
        undefined=Undefined,
    )
    context.update(default_jinja_context)
    try:
        return env.get_template(content).render(context)
    except Exception as e:
        logger.debug('----- render content failed -----')
        logger.debug(content)
        logger.debug('--------------- end -------------')
        import traceback
        traceback.print_exc()
        raise
Exemplo n.º 8
0
def create_sandbox_env():
    """Build an safe environment for rendering emails

    We want non-developers to be able to write emails, but using the main
    templating system would grant them access to secrets as well as the
    ability to run arbitrary code. ImmutableSandboxedEnvironment gets us
    most of the way there, but doesn't know which config is sensitive,
    or whether globals can be safely accessed.

    To avoid being annoyingly different, we try to match what Flask
    does in `create_jinja_environment`, but with a pared-down set of
    config and globals.
    """

    default_jinja_options = {}
    if app.jinja_options != default_jinja_options:
        # This code doesn't support any unusual options yet. If we've
        # (say) added an extension to the main template system, it should
        # be allowed or ignored here.
        raise NotImplementedError

    # Don't autoescape because this is used to generate plaintext output
    env = ImmutableSandboxedEnvironment(autoescape=False)

    config_to_copy = [
        "DEBUG",
        "SERVER_NAME",
    ]
    config = {c: app.config[c] for c in config_to_copy if c in app.config}

    # We don't need things like request and session for emails
    env.globals.update(
        url_for=url_for,
        config=config,
    )
    return env
Exemplo n.º 9
0
from collections import namedtuple
from distutils.version import LooseVersion
from operator import attrgetter

from jinja2.sandbox import ImmutableSandboxedEnvironment

from cumulusci.core.config import TaskConfig
from cumulusci.core.config import FlowConfig
from cumulusci.core.exceptions import FlowConfigError, FlowInfiniteLoopError
from cumulusci.core.utils import import_global

# TODO: define exception types: flowfailure, taskimporterror, etc?

RETURN_VALUE_OPTION_PREFIX = "^^"

jinja2_env = ImmutableSandboxedEnvironment()


class StepVersion(LooseVersion):
    """Like LooseVersion, but converts "/" into -1 to support comparisons"""
    def parse(self, vstring: str):
        super().parse(vstring)
        self.version = tuple(-1 if x == "/" else x for x in self.version)


class StepSpec(object):
    """ simple namespace to describe what the flowrunner should do each step """

    __slots__ = (
        "step_num",  # type: str
        "task_name",  # type: str
Exemplo n.º 10
0
 def test_immutable_environment(self):
     env = ImmutableSandboxedEnvironment()
     self.assert_raises(SecurityError,
                        env.from_string('{{ [].append(23) }}').render)
     self.assert_raises(SecurityError,
                        env.from_string('{{ {1:2}.clear() }}').render)
Exemplo n.º 11
0
 def test_immutable_environment(self, env):
     env = ImmutableSandboxedEnvironment()
     pytest.raises(SecurityError,
                   env.from_string("{{ [].append(23) }}").render)
     pytest.raises(SecurityError,
                   env.from_string("{{ {1:2}.clear() }}").render)
Exemplo n.º 12
0
 def __init__(self, templates_dict: Dict[str, str]):
     self._templates_dict = templates_dict
     self._environment = ImmutableSandboxedEnvironment(loader=DictLoader(
         self._templates_dict),
                                                       enable_async=True)