ソースを参照

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 19 時間 前
親
コミット
bc91e0b8f7

+ 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.
+```
+
+Context from plugins is included only if it 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

+ 8 - 2
docs/plugins/development/config-templates.md

@@ -124,10 +124,16 @@ 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 passed in `extra_context` (including in lists and dictionaries) are represented in the same way as the rendered object.
+
+```python
+config = device.render_config(extra_context={'deploy_id': 42}, user=request.user)
+```
+
 ```python
 from dcim.models import Device
 
@@ -154,4 +160,4 @@ config = device.render_config(extra_context={'deploy_id': 42})
 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.

+ 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):

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

@@ -3384,6 +3384,22 @@ 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')
+
     def test_render_config_matches_model(self):
         """
         The rendered config returned by the REST API matches the output of Device.render_config().

+ 48 - 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,52 @@ 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):
+                self.assertEqual(self.render(template_code, extra_context={'extra': {'key': 'value'}}), expected)
+                ConfigTemplate.objects.all().delete()
+
+    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':

+ 28 - 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 get_template_object, get_template_objects, to_plain_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 = {key: _get_restricted_value(value, state) for key, value in (context or {}).items()}
+        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
@@ -515,3 +527,19 @@ class ConfigTemplate(
                 parts.append(_("Line: {lineno}").format(lineno=exc.lineno))
             return "\n".join(parts)
         return f"{type(exc).__name__}: {exc}"
+
+
+def _get_restricted_value(value, state):
+    """
+    Represent a context value for restricted rendering: objects as TemplateObjects, querysets as TemplateObjectLists,
+    and anything else as plain data.
+    """
+    if isinstance(value, models.Model):
+        return get_template_object(value, state)
+    if isinstance(value, models.QuerySet):
+        return get_template_objects(value, state)
+    if isinstance(value, dict):
+        return {key: _get_restricted_value(item, state) for key, item in value.items()}
+    if isinstance(value, (list, tuple)):
+        return [_get_restricted_value(item, state) for item in value]
+    return to_plain_data(value)

+ 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)
 

+ 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),

+ 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')