use Sandbox Environment to render templates

This commit is contained in:
vabene1111
2024-11-26 17:18:47 +01:00
parent 4f9bff20c8
commit e6087d5129

View File

@@ -3,6 +3,8 @@ from gettext import gettext as _
import bleach import bleach
import markdown as md import markdown as md
from jinja2 import Template, TemplateSyntaxError, UndefinedError from jinja2 import Template, TemplateSyntaxError, UndefinedError
from jinja2.exceptions import SecurityError
from jinja2.sandbox import SandboxedEnvironment
from markdown.extensions.tables import TableExtension from markdown.extensions.tables import TableExtension
from cookbook.helper.mdx_attributes import MarkdownFormatExtension from cookbook.helper.mdx_attributes import MarkdownFormatExtension
@@ -89,11 +91,13 @@ def render_instructions(step): # TODO deduplicate markdown cleanup code
return f"<scalable-number v-bind:number='{bleach.clean(str(number))}' v-bind:factor='ingredient_factor'></scalable-number>" return f"<scalable-number v-bind:number='{bleach.clean(str(number))}' v-bind:factor='ingredient_factor'></scalable-number>"
try: try:
template = Template(instructions) env = SandboxedEnvironment()
instructions = template.render(ingredients=ingredients, scale=scale) instructions = env.from_string(instructions).render(ingredients=ingredients, scale=scale)
except TemplateSyntaxError: except TemplateSyntaxError:
return _('Could not parse template code.') + ' Error: Template Syntax broken' return _('Could not parse template code.') + ' Error: Template Syntax broken'
except UndefinedError: except UndefinedError:
return _('Could not parse template code.') + ' Error: Undefined Error' return _('Could not parse template code.') + ' Error: Undefined Error'
except SecurityError:
return _('Could not parse template code.') + ' Error: Security Error'
return instructions return instructions