Просмотр исходного кода

Closes #23878: Add restricted rendering mode for config templates

Support the restricted mode of TEMPLATE_RENDERING for config templates.
The rendered device or virtual machine is represented by its REST API
representation, with related objects resolved lazily and limited to
what the user is permitted to view. Model classes are replaced by
query(), and render_config() takes the user on whose behalf it runs.
Jeremy Stretch 17 часов назад
Родитель
Сommit
3652248ddf

+ 1 - 1
docs/configuration/system.md

@@ -440,7 +440,7 @@ TEMPLATE_RENDERING = {
 
 | Feature | Key | Supports `restricted` |
 |---|---|---|
-| Config templates | `config_templates` | No |
+| Config templates | `config_templates` | Yes |
 | Custom links | `custom_links` | Yes |
 | Export templates | `export_templates` | Yes |
 | Webhooks | `webhooks` | Yes |

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

@@ -39,12 +39,37 @@ When rendered for a specific NetBox device, the template's `device` variable wil
 
 ### Context Data
 
-The object for which the configuration is being rendered is made available as template context as `device` or `virtualmachine` for devices and virtual machines, respectively. Additionally, NetBox model classes can be accessed by the app or plugin in which they reside. For example:
+The object for which the configuration is being rendered is made available as template context as `device` or `virtualmachine` for devices and virtual machines, respectively. The object's [config context](./context-data.md) data is merged into the top level of the context, along with any data passed when rendering through the REST API.
+
+#### Legacy Rendering
+
+By default, `device` and `virtualmachine` are live object instances, and NetBox model classes can be accessed by the app or plugin in which they reside. For example:
 
 ```
 There are {{ dcim.Site.objects.count() }} sites.
 ```
 
+#### Restricted Rendering
+
+When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for config templates, templates are rendered in a restricted environment which permits access only to plain data:
+
+* `device` and `virtualmachine` hold the object's REST API representation. Related objects and reverse relations (e.g. `device.interfaces`) are fetched as they're accessed, limited to those the requesting user is permitted to view.
+* Config context data and REST API request data are unchanged.
+* Model classes aren't available. Use the `query()` function instead, which returns the objects matching the given REST API filters, limited to those the user is permitted to view. For example:
+
+```
+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:
+
+| Legacy                                   | Restricted                                        |
+|------------------------------------------|---------------------------------------------------|
+| `{% for i in device.interfaces.all() %}` | Unchanged (or `{% for i in device.interfaces %}`) |
+| `{{ device.cf.foo }}`                    | `{{ device.custom_fields.foo }}`                  |
+| `{{ device.get_status_display() }}`      | `{{ device.status.label }}`                       |
+| `{{ dcim.Site.objects.count() }}`        | `{{ query('dcim.site').count() }}`                |
+
 ## Rendering Templates
 
 ### Device Configurations

+ 14 - 4
docs/plugins/development/config-templates.md

@@ -116,6 +116,9 @@ The returned dict is merged into the template context, so `my_plugin` becomes av
 !!! note "No per-render context"
     `get_jinja_context()` receives no arguments — it has no access to the object being rendered or the caller-supplied context. It is intended for plugin-global namespaces (e.g. a lazily-evaluated query helper). Per-object logic belongs in the template itself or in a custom filter.
 
+!!! note "Restricted rendering"
+    When templates are rendered in [restricted mode](../../configuration/system.md#template_rendering), only values which can be serialized to JSON (e.g. strings, numbers, lists, and dictionaries) are included. Others, such as the namespace object above, are omitted, and a warning is logged.
+
 ---
 
 ## Rendering Configurations
@@ -124,15 +127,19 @@ The returned dict is merged into the template context, so `my_plugin` becomes av
 
 Devices and virtual machines provide two methods for rendering their configuration outside of a web request, for example from a background job, a custom script, or a management command. For the same template and extra context, these produce the same output as the "Render Config" tab in the UI and the `render-config` REST API endpoint.
 
-### `render_config(config_template=None, extra_context=None)`
+### `render_config(config_template=None, extra_context=None, user=None)`
 
 Renders and returns the object's configuration as text. If `config_template` is not given, the template is resolved from the object, its role, or its platform (in that order). Returns `None` if no template applies. Rendering errors are raised to the caller.
 
+When config templates are rendered in [restricted mode](../../features/configuration-rendering.md#restricted-rendering), the template runs on behalf of `user`, which is required: related objects and `query()` results are limited to those the user is permitted to view. Objects, querysets, and related managers passed in `extra_context` (including in lists and dictionaries) are represented in the same way as the rendered object and its related objects. A sliced queryset (e.g. `device.interfaces.all()[:5]`) takes the same slice of the objects the user is permitted to view. Other values are converted to plain data: for example, dates become ISO 8601 strings.
+
 ```python
 from dcim.models import Device
+from users.models import User
 
 device = Device.objects.get(name='router1')
-config = device.render_config(extra_context={'deploy_id': 42})
+user = User.objects.get(username='automation')
+config = device.render_config(extra_context={'deploy_id': 42}, user=user)
 ```
 
 !!! tip "Rendering many objects"
@@ -145,13 +152,16 @@ config = device.render_config(extra_context={'deploy_id': 42})
         .annotate_config_context_data(only_invalidated=True)
     )
 
+    user = User.objects.get(username='automation')
     for device in devices:
-        config = device.render_config()
+        config = device.render_config(user=user)
     ```
 
+    In restricted mode, each object is also loaded and serialized to its REST API representation for the template, which preloading doesn't avoid.
+
 ### `get_render_context(extra_context=None)`
 
 Returns the context used to render the object's config template: its [config context](../../features/context-data.md) data, then any extra context, then the object itself under its model name (`device` or `virtualmachine`). The object always takes precedence, so extra context can't replace it.
 
 !!! note "Permissions"
-    Neither method checks permissions. If you render a configuration on behalf of a user, confirm that the user has the `render_config` and `view` permissions for the object, as the UI and REST API do. If you pass a `config_template` the user selected, also confirm that they have `view` permission for that template.
+    Neither method checks permissions on the object being rendered, even in restricted mode. If you render a configuration on behalf of a user, confirm that the user has the `render_config` and `view` permissions for the object, as the UI and REST API do. If you pass a `config_template` the user selected, also confirm that they have `view` permission for that template. Likewise, confirm that the user has `view` permission for any objects you pass in `extra_context`. In restricted mode, querysets are limited to the objects the user may view, but individual objects aren't checked.

+ 4 - 3
netbox/dcim/models/mixins.py

@@ -74,15 +74,16 @@ class RenderConfigMixin(models.Model):
         context[self._meta.model_name] = self
         return context
 
-    def render_config(self, config_template=None, extra_context=None):
+    def render_config(self, config_template=None, extra_context=None, user=None):
         """
         Render this object's configuration using the given ConfigTemplate, or the one resolved by
-        get_config_template(). Returns None if no template applies; rendering errors propagate to the caller.
+        get_config_template(). Returns None if no template applies; rendering errors propagate to the caller. In
+        restricted mode, rendering runs on behalf of the given user, which is required.
         """
         config_template = config_template or self.get_config_template()
         if config_template is None:
             return None
-        return config_template.render(context=self.get_render_context(extra_context))
+        return config_template.render(context=self.get_render_context(extra_context), user=user)
 
 
 class CachedScopeMixin(models.Model):

+ 24 - 0
netbox/dcim/tests/test_api.py

@@ -3384,6 +3384,30 @@ class DeviceTestCase(Mixins.FieldPrefetchMixin, APIViewTestCases.APIViewTestCase
         self.assertHttpStatus(response, status.HTTP_200_OK)
         self.assertEqual(response.data['content'], f'Config for device {device.name}')
 
+    @override_settings(TEMPLATE_RENDERING={'config_templates': 'restricted'})
+    def test_render_config_restricted(self):
+        configtemplate = ConfigTemplate.objects.create(
+            name='Config Template 1',
+            template_code='{{ device.name }} {{ device.site.slug }} {{ extra }}'
+        )
+        device = Device.objects.first()
+        device.config_template = configtemplate
+        device.save()
+
+        self.add_permissions('dcim.render_config_device', 'dcim.view_device', 'dcim.view_site')
+        url = reverse('dcim-api:device-render-config', kwargs={'pk': device.pk})
+        response = self.client.post(url, {'extra': 'abc'}, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['content'], f'{device.name} {device.site.slug} abc')
+
+        # The template sees only the objects the user is permitted to view
+        self.assertTrue(Manufacturer.objects.exists())
+        configtemplate.template_code = '{{ query("dcim.device").count() }} {{ query("dcim.manufacturer").count() }}'
+        configtemplate.save()
+        response = self.client.post(url, {}, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['content'], f'{Device.objects.count()} 0')
+
     def test_render_config_matches_model(self):
         """
         The rendered config returned by the REST API matches the output of Device.render_config().

+ 81 - 1
netbox/dcim/tests/test_models.py

@@ -13,6 +13,7 @@ from django.test import RequestFactory, TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.utils.text import slugify
 from jinja2 import TemplateSyntaxError
+from jinja2.sandbox import SecurityError
 from netaddr import EUI
 
 from circuits.models import *
@@ -27,7 +28,7 @@ from ipam.models import IPAddress, Prefix
 from netbox.choices import DiameterUnitChoices, FlowRateUnitChoices, WeightUnitChoices
 from netbox.context_managers import event_tracking
 from tenancy.models import Tenant
-from users.models import User
+from users.models import ObjectPermission, User
 from utilities.data import drange
 from utilities.exceptions import AbortRequest
 from utilities.testing import create_test_device, create_test_image
@@ -1692,6 +1693,85 @@ class DeviceRenderConfigTestCase(TestCase):
             self.device.render_config(config_template)
 
 
+@override_settings(TEMPLATE_RENDERING={'config_templates': 'restricted'})
+class DeviceRestrictedRenderConfigTestCase(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.device = create_test_device('Device 1', local_context_data={'ntp': '192.0.2.1'})
+        Interface.objects.bulk_create([
+            Interface(device=cls.device, name='eth0', type='1000base-t'),
+            Interface(device=cls.device, name='eth1', type='1000base-t'),
+        ])
+        cls.superuser = User.objects.create_user(username='admin', is_superuser=True)
+
+    def render(self, template_code, user=None, **kwargs):
+        config_template = ConfigTemplate.objects.create(name='Template 1', template_code=template_code)
+        return self.device.render_config(config_template, user=user or self.superuser, **kwargs)
+
+    def test_context(self):
+        cases = (
+            ('{{ device.name }} {{ device.status.value }} {{ device.site.slug }}', 'Device 1 active site-1'),
+            ('{% for i in device.interfaces.all() %}{{ i.name }} {% endfor %}', 'eth0 eth1 '),
+            ('{{ ntp }} {{ device.config_context.ntp }}', '192.0.2.1 192.0.2.1'),
+            ('{{ query("dcim.device").count() }} {{ dcim is defined }}', '1 False'),
+            ('{{ extra.key }}', 'value'),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                try:
+                    self.assertEqual(self.render(template_code, extra_context={'extra': {'key': 'value'}}), expected)
+                finally:
+                    ConfigTemplate.objects.all().delete()
+
+    def test_extra_context_objects(self):
+        extra_context = {
+            'site': self.device.site,
+            'interfaces': self.device.interfaces,
+            'devices': [self.device],
+            'sites': {self.device.site},
+        }
+        output = self.render(
+            '{{ site.slug }} {{ interfaces | map(attribute="name") | join(",") }} {{ devices[0].name }} '
+            '{{ sites[0].slug }}',
+            extra_context=extra_context,
+        )
+        self.assertEqual(output, 'site-1 eth0,eth1 Device 1 site-1')
+
+    def test_extra_context_sliced_queryset(self):
+        template_code = '{{ interfaces | map(attribute="name") | join(",") }}'
+        interfaces = self.device.interfaces.order_by('name')
+        self.assertEqual(self.render(template_code, extra_context={'interfaces': interfaces[1:]}), 'eth1')
+        ConfigTemplate.objects.all().delete()
+
+        # The slice is taken of the objects the user is permitted to view
+        user = User.objects.create_user(username='user')
+        permission = ObjectPermission.objects.create(name='Interfaces', actions=['view'], constraints={'name': 'eth1'})
+        permission.object_types.set([ObjectType.objects.get_for_model(Interface)])
+        permission.users.set([user])
+        self.assertEqual(self.render(template_code, user=user, extra_context={'interfaces': interfaces[:1]}), 'eth1')
+
+    def test_extra_context_unsupported_model(self):
+        with self.assertRaises(ValueError):
+            self.render('{{ paths | length }}', extra_context={'paths': CablePath.objects.all()})
+
+    def test_related_objects_are_restricted(self):
+        user = User.objects.create_user(username='user')
+        permission = ObjectPermission.objects.create(name='Interfaces', actions=['view'], constraints={'name': 'eth1'})
+        permission.object_types.set([ObjectType.objects.get_for_model(Interface)])
+        permission.users.set([user])
+        self.assertEqual(self.render('{{ device.interfaces | map(attribute="name") | join }}', user=user), 'eth1')
+
+    def test_restricted_access(self):
+        with self.assertRaises(SecurityError):
+            self.render('{{ device._model }}')
+
+    def test_requires_user(self):
+        config_template = ConfigTemplate.objects.create(name='Template 1', template_code='{{ device.name }}')
+        with self.assertRaises(ValueError):
+            self.device.render_config(config_template)
+
+
 class DeviceBayTestCase(TestCase):
 
     @classmethod

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

@@ -3426,6 +3426,19 @@ class DeviceTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         self.remove_permissions('dcim.view_device')
         self.assertHttpStatus(self.client.get(url), 403)
 
+    @override_settings(TEMPLATE_RENDERING={'config_templates': 'restricted'})
+    def test_device_renderconfig_restricted(self):
+        device = Device.objects.first()
+        device.config_template = ConfigTemplate.objects.create(
+            name='Test Config Template',
+            template_code='Config for device {{ device.name }} at {{ device.site.slug }}'
+        )
+        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)
+        self.assertIn(f'Config for device {device.name} at {device.site.slug}', response.content.decode())
+
     def test_device_renderconfig_matches_model(self):
         """
         The rendered config exported from the UI matches the output of Device.render_config().

+ 1 - 1
netbox/extras/api/mixins.py

@@ -61,7 +61,7 @@ class ConfigTemplateRenderMixin:
     """
     def render_configtemplate(self, request, configtemplate, context):
         try:
-            output = configtemplate.render(context=context)
+            output = configtemplate.render(context=context, user=request.user)
         except Exception as e:
             detail = configtemplate.format_render_error(e)
             if request.accepted_renderer.format == 'txt':

+ 12 - 0
netbox/extras/models/configs.py

@@ -21,6 +21,7 @@ from netbox.models.features import CloningMixin, CustomLinksMixin, ExportTemplat
 from netbox.models.mixins import OwnerMixin
 from utilities.data import deepmerge
 from utilities.jsonschema import validate_schema
+from utilities.template_objects import to_template_data
 
 __all__ = (
     'ConfigContext',
@@ -452,6 +453,8 @@ class ConfigTemplate(
         )
     )
 
+    template_rendering_feature = 'config_templates'
+
     class Meta:
         ordering = ('name',)
         indexes = (
@@ -473,6 +476,15 @@ class ConfigTemplate(
         self.template_code = self.validate_synced_value('template_code', self.data_file.data_as_string)
     sync_data.alters_data = True
 
+    def get_restricted_context(self, state, context=None, queryset=None):
+        """
+        In restricted mode, objects in the context (e.g. the device being rendered) are represented by TemplateObjects,
+        and everything else (e.g. config context data) by plain data. The caller is responsible for ensuring that the
+        user is permitted to view the objects.
+        """
+        context = to_template_data(context or {}, state)
+        return super().get_restricted_context(state, context=context, queryset=queryset)
+
     def get_environment_params(self, restricted=False):
         """
         Config templates render plain text (network configs, scripts), not HTML. Force

+ 2 - 2
netbox/extras/models/models.py

@@ -55,7 +55,7 @@ from utilities.querydict import dict_to_querydict
 from utilities.querysets import RestrictedQuerySet
 from utilities.request import get_safe_request_context
 from utilities.tables import get_table_for_model
-from utilities.template_objects import TemplateObject, get_template_object, get_template_objects, to_plain_data
+from utilities.template_objects import TemplateObject, get_template_object, get_template_objects, to_template_data
 
 __all__ = (
     'Bookmark',
@@ -536,7 +536,7 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMod
         if request is not None:
             user = state.user or AnonymousUser()
             context.update({
-                'request': to_plain_data(get_safe_request_context(request)),
+                'request': to_template_data(get_safe_request_context(request)),
                 'user': _get_user_data(user),
                 'perms': PermWrapper(user),
             })

+ 12 - 0
netbox/extras/tests/test_api.py

@@ -2146,6 +2146,18 @@ class ConfigTemplateTestCase(APIViewTestCases.APIViewTestCase):
         self.assertHttpStatus(response, status.HTTP_200_OK)
         self.assertEqual(response.data['content'], 'Foo: bar')
 
+    @override_settings(TEMPLATE_RENDERING={'config_templates': 'restricted'})
+    def test_render_restricted(self):
+        configtemplate = ConfigTemplate.objects.first()
+        configtemplate.template_code = 'Foo: {{ foo.upper() }} {{ query("extras.configtemplate").count() }}'
+        configtemplate.save()
+
+        self.add_permissions('extras.render_configtemplate', 'extras.view_configtemplate')
+        url = reverse('extras-api:configtemplate-render', kwargs={'pk': configtemplate.pk})
+        response = self.client.post(url, {'foo': 'bar'}, format='json', **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertEqual(response.data['content'], f'Foo: BAR {ConfigTemplate.objects.count()}')
+
     def test_render_without_permission(self):
         configtemplate = ConfigTemplate.objects.first()
 

+ 1 - 1
netbox/extras/views.py

@@ -1311,7 +1311,7 @@ class ObjectRenderConfigView(generic.ObjectView):
         rendered_config = None
         if config_template:
             try:
-                rendered_config = config_template.render(context=context_data)
+                rendered_config = config_template.render(context=context_data, user=request.user)
             except Exception as e:
                 error_message = config_template.format_render_error(e)
 

+ 2 - 2
netbox/extras/webhooks.py

@@ -15,7 +15,7 @@ from netbox.settings_utils import parse_job_timeout
 from utilities.jinja2 import get_template_rendering_mode
 from utilities.proxy import resolve_proxies
 from utilities.request import get_safe_request_context
-from utilities.template_objects import to_plain_data
+from utilities.template_objects import to_template_data
 
 from .constants import WEBHOOK_EVENT_TYPES
 
@@ -94,7 +94,7 @@ def send_webhook(
 
     # Restricted rendering permits access only to plain data (e.g. not lazy translation strings or QueryDicts)
     if restricted:
-        context = to_plain_data(context)
+        context = to_template_data(context)
 
     # Build the headers for the HTTP request
     headers = {

+ 1 - 1
netbox/netbox/constants.py

@@ -27,7 +27,7 @@ TEMPLATE_RENDERING_DEFAULT = TEMPLATE_RENDERING_LEGACY
 
 # Features which render user-authored templates, mapped to the rendering modes each supports
 TEMPLATE_RENDERING_FEATURES = {
-    'config_templates': (TEMPLATE_RENDERING_LEGACY,),
+    'config_templates': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
     'custom_links': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
     'export_templates': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
     'webhooks': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),

+ 26 - 7
netbox/utilities/template_objects.py

@@ -9,6 +9,7 @@ from django.apps import apps
 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import FieldDoesNotExist
+from django.db import models
 from django.utils.datastructures import MultiValueDict
 from jinja2.exceptions import TemplateRuntimeError
 
@@ -35,7 +36,7 @@ __all__ = (
     'get_template_object',
     'get_template_objects',
     'template_json_default',
-    'to_plain_data',
+    'to_template_data',
 )
 
 # The number of objects a TemplateObjectList loads at a time
@@ -67,11 +68,17 @@ def get_template_object(instance, state):
 def get_template_objects(queryset, state):
     """
     Return a lazy TemplateObjectList representing the objects in the given queryset which the rendering user is
-    permitted to view.
+    permitted to view. A sliced queryset is represented by the same slice of those objects.
     """
     _check_state(state)
     if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
         raise ValueError(f"{queryset.model._meta.label} does not support restricted rendering.")
+    if queryset.query.is_sliced:
+        # A sliced queryset (e.g. interfaces[:5]) can't be restricted, so take the same slice of the permitted objects
+        start, stop = queryset.query.low_mark, queryset.query.high_mark
+        queryset = queryset.all()
+        queryset.query.clear_limits()
+        return TemplateObjectList(queryset, state)[start:stop]
     return TemplateObjectList(queryset, state)
 
 
@@ -542,17 +549,29 @@ def _load_objects(model, pks, state, cache=False):
 
 
 def _serialize(serializer_class, instance, many=False):
-    return to_plain_data(serializer_class(instance, many=many, context={'request': None}).data)
+    return to_template_data(serializer_class(instance, many=many, context={'request': None}).data)
 
 
-def to_plain_data(value):
+def to_template_data(value, state=None):
     """
-    Convert serializer output to plain dicts, lists, strings, numbers, booleans, and None, for rendering.
+    Convert a value for restricted rendering to plain dicts, lists, strings, numbers, booleans, and None. Given a
+    render state, model instances are represented by TemplateObjects, and querysets and related managers by
+    TemplateObjectLists.
     """
+    if isinstance(value, (TemplateObject, TemplateObjectList)):
+        return value
+    if state is not None:
+        if isinstance(value, models.Model):
+            return get_template_object(value, state)
+        if isinstance(value, models.Manager):
+            # A related manager (e.g. device.interfaces) is represented by its objects
+            value = value.all()
+        if isinstance(value, models.QuerySet):
+            return get_template_objects(value, state)
     if isinstance(value, dict):
-        return {key: to_plain_data(item) for key, item in value.items()}
+        return {key: to_template_data(item, state) for key, item in value.items()}
     if isinstance(value, (list, tuple, set, frozenset)):
-        return [to_plain_data(item) for item in value]
+        return [to_template_data(item, state) for item in value]
     if isinstance(value, (date, time)):
         return value.isoformat()
     if value is None or type(value) in (str, int, float, Decimal, bool):

+ 18 - 1
netbox/virtualization/tests/test_models.py

@@ -1,13 +1,14 @@
 from decimal import Decimal
 
 from django.core.exceptions import ValidationError
-from django.test import TestCase, tag
+from django.test import TestCase, override_settings, tag
 from netaddr import IPNetwork
 
 from dcim.models import Platform, Region, Site, SiteGroup
 from extras.models import ConfigTemplate
 from ipam.models import IPAddress
 from tenancy.models import Tenant
+from users.models import User
 from utilities.testing import create_test_device, create_test_virtualmachine
 from virtualization.models import *
 
@@ -766,3 +767,19 @@ class VirtualMachineRenderConfigTestCase(TestCase):
         vm.save()
         self.assertEqual(vm.render_config(extra_context={'bar': 'extra'}), 'VM 1 context extra')
         self.assertEqual(vm.get_render_context({'virtualmachine': 'spoofed'})['virtualmachine'], vm)
+
+    @override_settings(TEMPLATE_RENDERING={'config_templates': 'restricted'})
+    def test_render_config_restricted(self):
+        vm = create_test_virtualmachine('VM 1')
+        VMInterface.objects.create(virtual_machine=vm, name='eth0')
+        user = User.objects.create_user(username='admin', is_superuser=True)
+        config_template = ConfigTemplate.objects.create(
+            name='Template 1',
+            template_code=(
+                '{{ virtualmachine.name }} {{ virtualmachine.cluster.name }} '
+                '{{ virtualmachine.interfaces | map(attribute="name") | join }} '
+                '{{ peers | map(attribute="name") | join }}'
+            ),
+        )
+        output = vm.render_config(config_template, extra_context={'peers': [vm]}, user=user)
+        self.assertEqual(output, f'VM 1 {vm.cluster.name} eth0 VM 1')