|
|
@@ -1,11 +1,13 @@
|
|
|
import importlib.abc
|
|
|
import importlib.util
|
|
|
+import json
|
|
|
import logging
|
|
|
import os
|
|
|
import sys
|
|
|
import warnings
|
|
|
from collections import defaultdict
|
|
|
|
|
|
+from django.apps import apps as django_apps
|
|
|
from django.core.exceptions import ValidationError
|
|
|
from django.core.files.storage import storages
|
|
|
from django.db import models
|
|
|
@@ -14,11 +16,14 @@ from django.utils.http import content_disposition_header
|
|
|
from django.utils.module_loading import import_string
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
from jinja2 import TemplateError
|
|
|
+from rest_framework.utils.encoders import JSONEncoder
|
|
|
|
|
|
from core.models import ObjectType
|
|
|
from extras.constants import DEFAULT_MIME_TYPE, JINJA_ENV_PARAMS_ALLOWED, SCRIPT_MODULE_NAME_PREFIX
|
|
|
from extras.utils import filename_from_model, filename_from_object
|
|
|
-from utilities.jinja2 import render_jinja2
|
|
|
+from netbox.constants import TEMPLATE_RENDERING_RESTRICTED
|
|
|
+from netbox.plugins import PluginConfig
|
|
|
+from utilities.jinja2 import RestrictedRenderState, get_template_rendering_mode, render_jinja2
|
|
|
|
|
|
__all__ = (
|
|
|
'PythonModuleMixin',
|
|
|
@@ -30,6 +35,9 @@ logger = logging.getLogger(__name__)
|
|
|
# (model name, pk) of templates that have already emitted the stored 'finalize' deprecation warning (#23498)
|
|
|
_stored_finalize_warned = set()
|
|
|
|
|
|
+# (plugin name, context key) of plugin Jinja context values already reported as omitted from restricted rendering
|
|
|
+_plugin_context_warned = set()
|
|
|
+
|
|
|
|
|
|
class CustomStoragesLoader(importlib.abc.Loader):
|
|
|
"""
|
|
|
@@ -133,14 +141,22 @@ class RenderTemplateMixin(models.Model):
|
|
|
help_text=_("Download file as attachment")
|
|
|
)
|
|
|
|
|
|
+ # The TEMPLATE_RENDERING feature which governs this model's rendering (set by subclasses)
|
|
|
+ template_rendering_feature = None
|
|
|
+
|
|
|
class Meta:
|
|
|
abstract = True
|
|
|
|
|
|
- def get_context(self, context=None, queryset=None):
|
|
|
- from django.apps import apps as django_apps
|
|
|
-
|
|
|
- from netbox.plugins import PluginConfig
|
|
|
+ def uses_restricted_rendering(self):
|
|
|
+ """
|
|
|
+ Return True if TEMPLATE_RENDERING selects restricted mode for this model's templates.
|
|
|
+ """
|
|
|
+ return (
|
|
|
+ self.template_rendering_feature is not None and
|
|
|
+ get_template_rendering_mode(self.template_rendering_feature) == TEMPLATE_RENDERING_RESTRICTED
|
|
|
+ )
|
|
|
|
|
|
+ def get_context(self, context=None, queryset=None, user=None):
|
|
|
_context = defaultdict(dict)
|
|
|
|
|
|
# Populate all public models for reference within the template
|
|
|
@@ -161,6 +177,38 @@ class RenderTemplateMixin(models.Model):
|
|
|
|
|
|
return _context
|
|
|
|
|
|
+ def get_restricted_context(self, state, context=None, queryset=None):
|
|
|
+ """
|
|
|
+ Return the context for rendering in restricted mode: each plugin context value which can be serialized to
|
|
|
+ JSON, and the given context. Model classes aren't included.
|
|
|
+ """
|
|
|
+ _context = {}
|
|
|
+ for app_config in django_apps.get_app_configs():
|
|
|
+ if isinstance(app_config, PluginConfig):
|
|
|
+ try:
|
|
|
+ plugin_context = dict(app_config.get_jinja_context())
|
|
|
+ except Exception:
|
|
|
+ logger.exception("Plugin %r raised an exception in get_jinja_context()", app_config.name)
|
|
|
+ continue
|
|
|
+ omitted = []
|
|
|
+ for key, value in plugin_context.items():
|
|
|
+ try:
|
|
|
+ _context[key] = json.loads(json.dumps(value, cls=JSONEncoder))
|
|
|
+ except (TypeError, ValueError):
|
|
|
+ if (app_config.name, key) not in _plugin_context_warned:
|
|
|
+ _plugin_context_warned.add((app_config.name, key))
|
|
|
+ omitted.append(key)
|
|
|
+ if omitted:
|
|
|
+ logger.warning(
|
|
|
+ "Omitting Jinja context from plugin %r which can't be serialized: %s",
|
|
|
+ app_config.name, ', '.join(omitted)
|
|
|
+ )
|
|
|
+
|
|
|
+ if context is not None:
|
|
|
+ _context.update(context)
|
|
|
+
|
|
|
+ return _context
|
|
|
+
|
|
|
def clean(self):
|
|
|
super().clean()
|
|
|
|
|
|
@@ -268,39 +316,58 @@ class RenderTemplateMixin(models.Model):
|
|
|
)
|
|
|
return {**params, 'finalize': stored_finalize}
|
|
|
|
|
|
- def get_environment_params(self):
|
|
|
+ def get_environment_params(self, restricted=False):
|
|
|
"""
|
|
|
- Pre-processing of any defined Jinja environment parameters.
|
|
|
+ Pre-processing of any defined Jinja environment parameters. A stored finalize is ignored in restricted mode.
|
|
|
"""
|
|
|
# Shallow-copy so resolved values don't replace the strings on the model field.
|
|
|
params = dict(self.environment_params or {})
|
|
|
params = self._filter_environment_params(params)
|
|
|
params = self._resolve_mapped_params(params)
|
|
|
+ if restricted:
|
|
|
+ params.pop('finalize', None)
|
|
|
+ return params
|
|
|
params = self._restrict_finalize_to_stored(params)
|
|
|
params = self._resolve_finalize(params)
|
|
|
return params
|
|
|
|
|
|
- def render(self, context=None, queryset=None):
|
|
|
+ def render(self, context=None, queryset=None, user=None):
|
|
|
"""
|
|
|
Render the template with the provided context. The context is passed to the Jinja2 environment as a dictionary.
|
|
|
+ In restricted mode, rendering runs on behalf of the given user.
|
|
|
"""
|
|
|
- context = self.get_context(context=context, queryset=queryset)
|
|
|
- env_params = self.get_environment_params()
|
|
|
+ state = RestrictedRenderState(user) if self.uses_restricted_rendering() else None
|
|
|
+ if state is None:
|
|
|
+ context = self.get_context(context=context, queryset=queryset, user=user)
|
|
|
+ else:
|
|
|
+ context = self.get_restricted_context(state, context=context, queryset=queryset)
|
|
|
+ env_params = self.get_environment_params(restricted=state is not None)
|
|
|
debug = getattr(self, 'debug', False)
|
|
|
- output = render_jinja2(self.template_code, context, env_params, getattr(self, 'data_file', None), debug=debug)
|
|
|
+ output = render_jinja2(
|
|
|
+ self.template_code,
|
|
|
+ context,
|
|
|
+ env_params,
|
|
|
+ getattr(self, 'data_file', None),
|
|
|
+ debug=debug,
|
|
|
+ restricted=state,
|
|
|
+ )
|
|
|
|
|
|
# Replace CRLF-style line terminators
|
|
|
output = output.replace('\r\n', '\n')
|
|
|
|
|
|
return output
|
|
|
|
|
|
- def render_to_response(self, context=None, queryset=None):
|
|
|
- output = self.render(context=context, queryset=queryset)
|
|
|
+ def render_to_response(self, context=None, queryset=None, user=None):
|
|
|
+ output = self.render(context=context, queryset=queryset, user=user)
|
|
|
mime_type = self.mime_type or DEFAULT_MIME_TYPE
|
|
|
|
|
|
# Build the response
|
|
|
response = HttpResponse(output, content_type=mime_type)
|
|
|
|
|
|
+ # Keep any script in output shown inline (e.g. HTML) from running, as for image attachments
|
|
|
+ if not self.as_attachment and self.uses_restricted_rendering():
|
|
|
+ response['Content-Security-Policy'] = "sandbox; default-src 'none'"
|
|
|
+
|
|
|
if self.as_attachment:
|
|
|
extension = f'.{self.file_extension}' if self.file_extension else ''
|
|
|
if self.file_name:
|