Преглед изворни кода

Closes #23904: Show the restricted context on the Render Config tab

In restricted mode, the Context Data panel showed the legacy context,
including the model instance, rather than what the template receives.
It now shows the restricted context built for the render, with the
object's REST API representation and related objects in brief form.
Jeremy Stretch пре 5 часа
родитељ
комит
e5c328d4dd

+ 1 - 1
docs/features/configuration-rendering.md

@@ -61,7 +61,7 @@ When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) c
 There are {{ query('dcim.site').count() }} sites.
 ```
 
-Each variable provided by a plugin is included only if its value can be serialized to JSON, and a stored `finalize` environment parameter is ignored. Common changes needed when migrating a template:
+Each variable provided by a plugin is included only if its value can be serialized to JSON, and a stored `finalize` environment parameter is ignored. The "Context Data" panel on an object's Render Config tab shows the context in this form, with related objects in their brief representation. Common changes needed when migrating a template:
 
 | Legacy                                   | Restricted                                        |
 |------------------------------------------|---------------------------------------------------|

+ 30 - 0
netbox/dcim/tests/test_views.py

@@ -3439,6 +3439,36 @@ class DeviceTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         self.assertHttpStatus(response, 200)
         self.assertIn(f'Config for device {device.name} at {device.site.slug}', response.content.decode())
 
+    @override_settings(TEMPLATE_RENDERING={'config_templates': 'restricted'})
+    def test_device_renderconfig_restricted_context_data(self):
+        """
+        In restricted mode, the context data panel shows the context the template receives.
+        """
+        device = Device.objects.first()
+        device.config_template = ConfigTemplate.objects.create(
+            name='Test Config Template',
+            template_code='{{ device.site.time_zone }}'
+        )
+        device.local_context_data = {'ntp': ['192.0.2.1']}
+        device.save()
+        self.add_permissions('dcim.view_device', 'dcim.render_config_device', 'dcim.view_site')
+        response = self.client.get(reverse('dcim:device_render-config', kwargs={'pk': device.pk}))
+        self.assertHttpStatus(response, 200)
+
+        context_data = response.context['context_data']
+        self.assertEqual(context_data['ntp'], ['192.0.2.1'])
+        self.assertEqual(context_data['device']['name'], device.name)
+        self.assertEqual(context_data['device']['status']['value'], device.status)
+        # The site is shown in its brief form, although the template fetched its full representation
+        self.assertEqual(context_data['device']['site']['slug'], device.site.slug)
+        self.assertNotIn('time_zone', context_data['device']['site'])
+        self.assertNotIn('<Device', response.content.decode())
+
+        # In legacy mode, the panel shows the device instance
+        with override_settings(TEMPLATE_RENDERING='legacy'):
+            response = self.client.get(reverse('dcim:device_render-config', kwargs={'pk': device.pk}))
+        self.assertEqual(response.context['context_data']['device'], device)
+
     def test_device_renderconfig_matches_model(self):
         """
         The rendered config exported from the UI matches the output of Device.render_config().

+ 16 - 5
netbox/extras/models/mixins.py

@@ -353,16 +353,27 @@ class RenderTemplateMixin(TemplateRenderingModeMixin, models.Model):
         params = self._resolve_finalize(params)
         return params
 
+    def prepare_render(self, context=None, queryset=None, user=None):
+        """
+        Return the context the template renders with, and the RestrictedRenderState for the render (None in legacy
+        mode). In restricted mode, rendering runs on behalf of the given user.
+        """
+        if not self.uses_restricted_rendering():
+            return self.get_context(context=context, queryset=queryset, user=user), None
+        state = RestrictedRenderState(user)
+        return self.get_restricted_context(state, context=context, queryset=queryset), state
+
     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.
         """
-        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)
+        return self.render_prepared(*self.prepare_render(context=context, queryset=queryset, user=user))
+
+    def render_prepared(self, context, state=None):
+        """
+        Render the template with a context and render state returned by prepare_render().
+        """
         env_params = self.get_environment_params(restricted=state is not None)
         debug = getattr(self, 'debug', False)
         output = render_jinja2(

+ 6 - 1
netbox/extras/views.py

@@ -45,6 +45,7 @@ from utilities.query import count_related
 from utilities.querydict import normalize_querydict
 from utilities.request import copy_safe_request
 from utilities.rqworker import any_workers_for_queue
+from utilities.template_objects import get_template_context_data
 from utilities.templatetags.builtins.filters import render_markdown
 from utilities.views import ContentTypePermissionRequiredMixin, get_action_url, register_model_view
 from virtualization.models import VirtualMachine
@@ -1311,7 +1312,11 @@ class ObjectRenderConfigView(generic.ObjectView):
         rendered_config = None
         if config_template:
             try:
-                rendered_config = config_template.render(context=context_data, user=request.user)
+                render_context, state = config_template.prepare_render(context=context_data, user=request.user)
+                if state is not None:
+                    # Show the restricted context, as the template receives it (before it fetches anything)
+                    context_data = get_template_context_data(render_context)
+                rendered_config = config_template.render_prepared(render_context, state)
             except Exception as e:
                 error_message = config_template.format_render_error(e)
 

+ 17 - 0
netbox/utilities/template_objects.py

@@ -33,6 +33,7 @@ __all__ = (
     'TemplateObject',
     'TemplateObjectList',
     'get_query_function',
+    'get_template_context_data',
     'get_template_object',
     'get_template_objects',
     'template_json_default',
@@ -95,6 +96,22 @@ def get_query_function(state):
     return query
 
 
+def get_template_context_data(value):
+    """
+    Return a copy of a restricted rendering context for display, with each TemplateObject replaced by the
+    representation it holds (fetching nothing) and each TemplateObjectList by its description.
+    """
+    if isinstance(value, TemplateObject):
+        return deepcopy(value._data)
+    if isinstance(value, TemplateObjectList):
+        return repr(value)
+    if isinstance(value, dict):
+        return {key: get_template_context_data(item) for key, item in value.items()}
+    if isinstance(value, list):
+        return [get_template_context_data(item) for item in value]
+    return value
+
+
 def template_json_default(obj):
     """
     JSON encoder hook for restricted rendering: TemplateObjects serialize to their full representation.

+ 28 - 1
netbox/utilities/tests/test_template_objects.py

@@ -17,7 +17,13 @@ from ipam.models import IPAddress
 from tenancy.models import Tenant, TenantGroup
 from users.models import ObjectPermission, User
 from utilities.jinja2 import RestrictedRenderState, render_jinja2
-from utilities.template_objects import _load_objects, get_template_object, get_template_objects, to_template_data
+from utilities.template_objects import (
+    _load_objects,
+    get_template_context_data,
+    get_template_object,
+    get_template_objects,
+    to_template_data,
+)
 from utilities.testing import create_test_device
 
 
@@ -65,6 +71,27 @@ class TemplateObjectTest(TestCase):
             with self.subTest(template_code=template_code):
                 self.assertEqual(self.render(template_code, object=self.device), expected)
 
+    def test_context_data(self):
+        state = RestrictedRenderState(self.superuser)
+        device = get_template_object(self.device, state)
+        context = {
+            'device': device,
+            'interfaces': get_template_objects(Interface.objects.all(), state),
+            'extra': {'items': [device, 1]},
+        }
+        # Resolving a related object doesn't change the representation shown
+        render_jinja2('{{ device.tenant.group.slug }}', context, restricted=state)
+        with self.assertNumQueries(0):
+            data = get_template_context_data(context)
+        self.assertEqual(data['device']['name'], 'Device 1')
+        self.assertNotIn('group', data['device']['tenant'])
+        self.assertEqual(data['interfaces'], '<TemplateObjectList dcim.Interface>')
+        self.assertEqual(data['extra']['items'][1], 1)
+        self.assertEqual(data['extra']['items'][0]['name'], 'Device 1')
+        # The data is a copy
+        data['device']['name'] = 'Changed'
+        self.assertEqual(device['name'], 'Device 1')
+
     def test_urls(self):
         site = self.device.site
         tenant_group = self.tenant.group