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

Closes #23739: Add restricted rendering mode for custom links

Support the restricted mode of TEMPLATE_RENDERING for custom links.
Links are rendered in the restricted environment, with the object
represented by its REST API representation, the user and their
permissions as plain data, and query() available. Table columns
serialize the records on a page (or chunks of an export) at once.
Jeremy Stretch 18 часов назад
Родитель
Сommit
262a9fb1e4

+ 1 - 1
docs/configuration/system.md

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

+ 23 - 0
docs/customization/custom-links.md

@@ -39,6 +39,29 @@ While most of the context variables listed above will have consistent attributes
 
 Checking the REST API representation of an object is generally a convenient way to determine what attributes are available. You can also reference the NetBox source code directly for a comprehensive list.
 
+### Restricted Rendering
+
+When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for custom links, links are rendered in a restricted environment which permits access only to plain data, and the context changes as follows:
+
+| Variable  | Description                                                                                                       |
+|-----------|-------------------------------------------------------------------------------------------------------------------|
+| `object`  | The object's REST API representation. Related objects are fetched as they're accessed (e.g. `object.device.tenant.group.slug`), limited to those the user is permitted to view. |
+| `user`    | A dictionary holding the user's `id` and `username`                                                              |
+| `perms`   | A nested dictionary of the user's model permissions, so checks such as `{% if perms.dcim.change_device %}` keep working |
+| `query()` | A function which returns objects matching the given REST API filters (e.g. `query('ipam.ipaddress', device_id=object.id)`), limited to those the user is permitted to view and to `MAX_PAGE_SIZE` objects |
+
+`debug` and `request` are unchanged, except that `request.GET` holds the last value of each query parameter. In a table column, the objects on the current page are represented in a single batch.
+
+Most links work the same in both modes. Common changes needed when migrating a link:
+
+| Legacy                                  | Restricted                                    |
+|-----------------------------------------|-----------------------------------------------|
+| `{{ object.cf.foo }}`                   | `{{ object.custom_fields.foo }}`              |
+| `{{ object.get_absolute_url() }}`       | `{{ object.display_url }}`                    |
+| `{% if object.status == 'active' %}`    | `{% if object.status.value == 'active' %}`    |
+| `{{ object.get_status_display() }}`     | `{{ object.status.label }}`                   |
+| `{{ object.get_config_context() }}`     | `{{ object.config_context }}`                 |
+
 ## Conditional Rendering
 
 Only links which render with non-empty text are included on the page. You can employ conditional Jinja2 logic to control the conditions under which a link gets rendered.

+ 2 - 0
docs/models/extras/customlink.md

@@ -54,3 +54,5 @@ The following context variables are available in to the text and link templates.
 | `request` | The current WSGI request                                                    |
 | `user`    | The current user (if authenticated)                                         |
 | `perms`   | The [permissions](../../administration/permissions.md) assigned to the user |
+
+In [restricted mode](../../customization/custom-links.md#restricted-rendering), `object`, `user`, and `perms` hold plain data, and a `query()` function is available.

+ 3 - 0
netbox/extras/constants.py

@@ -226,3 +226,6 @@ CC_FIELDS_BY_MODEL = {
         'site_id', 'cluster_id', 'tenant_id', 'platform_id', 'role_id', 'local_context_data',
     ),
 }
+
+# The maximum number of objects a custom link's query() may return, if MAX_PAGE_SIZE is 0 (unlimited)
+CUSTOM_LINK_QUERY_MAX_RESULTS = 1000

+ 64 - 3
netbox/extras/models/models.py

@@ -4,6 +4,7 @@ import urllib.parse
 from pathlib import Path
 
 from django.conf import settings
+from django.contrib.auth.models import AnonymousUser, Permission
 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.contrib.postgres.fields import ArrayField
 from django.core.exceptions import ValidationError
@@ -51,7 +52,9 @@ from utilities.jinja2 import (
 )
 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, to_plain_data
 
 __all__ = (
     'Bookmark',
@@ -503,16 +506,50 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMod
     def docs_url(self):
         return f'{settings.STATIC_URL}docs/models/extras/customlink/'
 
-    def render(self, context):
+    @staticmethod
+    def get_render_state(request):
+        """
+        Return the state for rendering custom links in restricted mode on behalf of the request's user, or None if
+        restricted mode isn't selected.
+        """
+        if get_template_rendering_mode('custom_links') != TEMPLATE_RENDERING_RESTRICTED:
+            return None
+        # Links render for every row of a table, so cap the objects a query() can return
+        return RestrictedRenderState(
+            getattr(request, 'user', None),
+            max_results=get_config().MAX_PAGE_SIZE or CUSTOM_LINK_QUERY_MAX_RESULTS,
+        )
+
+    @staticmethod
+    def get_restricted_context(obj, state, request=None, debug=False):
+        """
+        Return the context for rendering custom links for the given object in restricted mode. The object is
+        represented by a TemplateObject, and the user and their permissions by plain data.
+        """
+        context = {
+            'object': obj if isinstance(obj, TemplateObject) else get_template_object(obj, state),
+            'debug': debug,
+        }
+        if request is not None:
+            user = getattr(request, 'user', None) or AnonymousUser()
+            context.update({
+                'request': to_plain_data(get_safe_request_context(request)),
+                'user': {'id': user.pk, 'username': user.get_username()},
+                'perms': _get_model_permissions(user, state),
+            })
+        return context
+
+    def render(self, context, restricted=None):
         """
         Render the CustomLink given the provided context, and return the text, link, and link_target.
 
         :param context: The context passed to Jinja2
+        :param restricted: A RestrictedRenderState, to render in restricted mode
         """
-        text = render_jinja2(self.link_text, context).strip()
+        text = render_jinja2(self.link_text, context, restricted=restricted).strip()
         if not text:
             return {}
-        link = render_jinja2(self.link_url, context).strip()
+        link = render_jinja2(self.link_url, context, restricted=restricted).strip()
         link_target = ' target="_blank"' if self.new_window else ''
 
         # Sanitize link text
@@ -534,6 +571,30 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMod
         }
 
 
+def _get_model_permissions(user, state):
+    """
+    Return the user's model-level permissions as a nested dict (e.g. perms['dcim']['change_device']), cached for the
+    render.
+    """
+    key = ('model_permissions', user.pk)
+    if key not in state.cache:
+        perms = {}
+        for app_label, codename in Permission.objects.values_list('content_type__app_label', 'codename'):
+            try:
+                permitted = user.has_perm(f'{app_label}.{codename}')
+            except ValueError:
+                # Not a model permission which NetBox can evaluate (e.g. core.sync)
+                continue
+            if permitted:
+                perms.setdefault(app_label, {})[codename] = True
+        # Add any permissions granted for custom actions (e.g. dcim.render_config_device)
+        for name in user.get_all_permissions():
+            app_label, _, codename = name.partition('.')
+            perms.setdefault(app_label, {})[codename] = True
+        state.cache[key] = perms
+    return state.cache[key]
+
+
 class ExportTemplate(
     SyncedDataMixin,
     CloningMixin,

+ 25 - 9
netbox/extras/templatetags/custom_links.py

@@ -41,13 +41,29 @@ def custom_links(context, obj):
         return ''
 
     # Pass select context data when rendering the CustomLink
-    link_context = {
-        'object': obj,
-        'debug': context.get('debug', False),  # django.template.context_processors.debug
-        'request': get_safe_request_context(context['request']),  # Sanitized subset of the request
-        'user': context['user'],  # django.contrib.auth.context_processors.auth
-        'perms': context['perms'],  # django.contrib.auth.context_processors.auth
-    }
+    render_state = CustomLink.get_render_state(context['request'])
+    context_error = None
+    if render_state is None:
+        link_context = {
+            'object': obj,
+            'debug': context.get('debug', False),  # django.template.context_processors.debug
+            'request': get_safe_request_context(context['request']),  # Sanitized subset of the request
+            'user': context['user'],  # django.contrib.auth.context_processors.auth
+            'perms': context['perms'],  # django.contrib.auth.context_processors.auth
+        }
+    else:
+        try:
+            link_context = CustomLink.get_restricted_context(
+                obj, render_state, context['request'], debug=context.get('debug', False)
+            )
+        except Exception as e:
+            link_context, context_error = None, e
+
+    def render_link(cl):
+        if context_error is not None:
+            raise context_error
+        return cl.render(link_context, restricted=render_state)
+
     template_code = ''
     group_names = {}
 
@@ -63,7 +79,7 @@ def custom_links(context, obj):
         else:
             button_class = 'outline-secondary' if cl.button_class == ButtonColorChoices.DEFAULT else cl.button_class
             try:
-                if rendered := cl.render(link_context):
+                if rendered := render_link(cl):
                     template_code += LINK_BUTTON.format(
                         rendered['link'], rendered['link_target'], button_class, rendered['text']
                     )
@@ -78,7 +94,7 @@ def custom_links(context, obj):
 
         for cl in links:
             try:
-                if rendered := cl.render(link_context):
+                if rendered := render_link(cl):
                     links_rendered.append(
                         GROUP_LINK.format(rendered['link'], rendered['link_target'], rendered['text'])
                     )

+ 113 - 1
netbox/extras/tests/test_templatetags.py

@@ -1,13 +1,18 @@
+from unittest.mock import patch
+
 from django.contrib.auth import get_user_model
 from django.contrib.auth.context_processors import PermWrapper
-from django.test import RequestFactory, TestCase
+from django.test import RequestFactory, TestCase, override_settings
 from django.utils.html import escape
 
 from core.models import ObjectType
 from dcim.models import Site
+from dcim.tables import SiteTable
 from extras.models import CustomLink
 from extras.templatetags.custom_links import custom_links
+from tenancy.models import Tenant, TenantGroup
 from users.models import ObjectPermission
+from utilities.template_objects import _load_objects
 
 User = get_user_model()
 
@@ -226,3 +231,110 @@ class CustomLinkRenderErrorEscapingTest(TestCase):
         rendered = self.render(self.make_user_with_view_permission('user4'))
         self.assertNotIn(self.XSS_PAYLOAD, rendered)
         self.assertIn(escape(self.XSS_PAYLOAD), rendered)
+
+
+@override_settings(TEMPLATE_RENDERING={'custom_links': 'restricted'})
+class CustomLinkRestrictedRenderingTest(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        tenant_group = TenantGroup.objects.create(name='Tenant Group 1', slug='corp')
+        tenant = Tenant.objects.create(name='Tenant 1', slug='tenant-1', group=tenant_group)
+        cls.sites = (
+            Site.objects.create(name='Site 1', slug='site-1', tenant=tenant),
+            Site.objects.create(name='Site 2', slug='site-2'),
+            Site.objects.create(name='Site 3', slug='site-3'),
+        )
+        cls.user = User.objects.create_user(username='user1')
+        for model, actions in ((Site, ['view']), (CustomLink, ['view']), (Tenant, ['view']), (TenantGroup, ['view'])):
+            permission = ObjectPermission.objects.create(name=f'{model.__name__} permission', actions=actions)
+            permission.object_types.set([ObjectType.objects.get_for_model(model)])
+            permission.users.set([cls.user])
+
+    def get_request(self):
+        request = RequestFactory().get('/dcim/sites/', {'foo': 'bar'})
+        request.user = User.objects.get(pk=self.user.pk)
+        return request
+
+    def render_link(self, link_text):
+        custom_link = CustomLink.objects.create(
+            name='Custom Link 1', enabled=True, link_text=link_text, link_url='http://example.com/'
+        )
+        custom_link.object_types.set([ObjectType.objects.get_for_model(Site)])
+        request = self.get_request()
+        context = {'request': request, 'user': request.user, 'perms': PermWrapper(request.user)}
+        return custom_links(context, self.sites[0])
+
+    def test_context(self):
+        cases = (
+            ('{{ object.name }} {{ object.status.value }}', 'Site 1 active'),
+            ('{{ object.tenant.group.slug }}', 'corp'),
+            ('{{ user.username }}', 'user1'),
+            ('{{ perms.dcim.view_site }} {{ perms.dcim.change_site is defined }}', 'True False'),
+            ('{{ request.path }} {{ request.GET.foo }}', '/dcim/sites/ bar'),
+            ('{{ query("dcim.site").count() }}', '3'),
+        )
+        for link_text, expected in cases:
+            with self.subTest(link_text=link_text):
+                try:
+                    self.assertIn(f'>{expected}</a>', self.render_link(link_text))
+                finally:
+                    CustomLink.objects.all().delete()
+
+    def test_restricted_access(self):
+        output = self.render_link('{{ object._model }}')
+        self.assertIn('mdi-alert', output)
+        self.assertIn('not permitted', output)
+
+    def test_table_column(self):
+        custom_link_type = ObjectType.objects.get_for_model(Site)
+        for name, link_text in (('Link 1', '{{ object.name }}'), ('Link 2', '{{ object.tenant.name }}')):
+            custom_link = CustomLink.objects.create(name=name, enabled=True, link_text=link_text, link_url='/')
+            custom_link.object_types.set([custom_link_type])
+        table = SiteTable(Site.objects.order_by('name'))
+        table.context = {'request': self.get_request()}
+        table.paginate(per_page=2)
+
+        with patch('utilities.template_objects._load_objects', wraps=_load_objects) as load_objects:
+            cells = [
+                (row.get_cell('cl_Link 1'), row.get_cell('cl_Link 2')) for row in table.page.object_list
+            ]
+        self.assertIn('>Site 1</a>', cells[0][0])
+        self.assertIn('>Tenant 1</a>', cells[0][1])
+        self.assertIn('>Site 2</a>', cells[1][0])
+        # The records on the page are serialized at once, for both columns
+        self.assertEqual([len(call.args[1]) for call in load_objects.call_args_list], [2])
+
+    @patch('netbox.tables.columns.TEMPLATE_OBJECTS_CHUNK_SIZE', 2)
+    def test_table_export(self):
+        custom_link = CustomLink.objects.create(
+            name='Link 1', enabled=True, link_text='x', link_url='/{{ object.slug }}'
+        )
+        custom_link.object_types.set([ObjectType.objects.get_for_model(Site)])
+        table = SiteTable(Site.objects.order_by('name'))
+        table.context = {'request': self.get_request()}
+
+        with patch('utilities.template_objects._load_objects', wraps=_load_objects) as load_objects:
+            values = [row.get_cell_value('cl_Link 1') for row in table.rows]
+        self.assertEqual(values, ['/site-1', '/site-2', '/site-3'])
+        # An unpaginated table is serialized in chunks
+        self.assertEqual([len(call.args[1]) for call in load_objects.call_args_list], [2, 1])
+
+    def test_table_record_not_permitted(self):
+        ObjectPermission.objects.filter(name='Site permission').update(constraints={'slug': 'site-2'})
+        custom_link = CustomLink.objects.create(
+            name='Link 1', enabled=True, link_text='{{ object.name }}', link_url='/'
+        )
+        custom_link.object_types.set([ObjectType.objects.get_for_model(Site)])
+        table = SiteTable(Site.objects.order_by('name'))
+        table.context = {'request': self.get_request()}
+        table.paginate(per_page=3)
+        cells = [row.get_cell('cl_Link 1') for row in table.page.object_list]
+        self.assertIn('permission', cells[0])
+        self.assertIn('>Site 2</a>', cells[1])
+
+    def test_custom_action_permissions(self):
+        permission = ObjectPermission.objects.create(name='Render config', actions=['render_config'])
+        permission.object_types.set([ObjectType.objects.get_for_model(Site)])
+        permission.users.set([self.user])
+        self.assertIn('>True</a>', self.render_link('{{ perms.dcim.render_config_site }}'))

+ 1 - 1
netbox/netbox/constants.py

@@ -28,7 +28,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,),
-    'custom_links': (TEMPLATE_RENDERING_LEGACY,),
+    'custom_links': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
     'export_templates': (TEMPLATE_RENDERING_LEGACY,),
     'webhooks': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
 }

+ 50 - 2
netbox/netbox/tables/columns.py

@@ -7,6 +7,7 @@ import django_tables2 as tables
 from django.conf import settings
 from django.contrib.auth.context_processors import auth
 from django.contrib.auth.models import AnonymousUser
+from django.core.exceptions import PermissionDenied
 from django.db.models import Case, DateField, DateTimeField, IntegerField, Q, Value, When
 from django.db.models.fields.json import KeyTextTransform
 from django.template import Context, Template
@@ -23,6 +24,7 @@ from extras.choices import CustomFieldTypeChoices
 from utilities.object_types import object_type_identifier, object_type_name
 from utilities.permissions import get_permission_for_model
 from utilities.request import get_safe_request_context
+from utilities.template_objects import TEMPLATE_OBJECTS_CHUNK_SIZE, get_template_objects
 from utilities.templatetags.builtins.filters import isodatetime, render_markdown
 from utilities.validators import url_scheme_is_allowed
 from utilities.views import get_action_url
@@ -719,19 +721,65 @@ class CustomLinkColumn(tables.Column):
         super().__init__(*args, **kwargs)
 
     def _render_customlink(self, record, table):
+        request = getattr(table, 'context', {}).get('request')
+        # Share the render state among all of the table's custom link columns
+        if not hasattr(table, '_custom_link_render_state'):
+            table._custom_link_render_state = self.customlink.get_render_state(request)
+        if (state := table._custom_link_render_state) is not None:
+            obj = self._get_template_object(record, table, state)
+            context = self.customlink.get_restricted_context(obj, state, request, debug=settings.DEBUG)
+            return self.customlink.render(context, restricted=state)
+
         context = {
             'object': record,
             'debug': settings.DEBUG,
         }
-        if request := getattr(table, 'context', {}).get('request'):
+        if request:
             # If the request is available, include a sanitized subset of it as context
             context.update({
                 'request': get_safe_request_context(request),
                 **auth(request),
             })
-
         return self.customlink.render(context)
 
+    @staticmethod
+    def _get_template_object(record, table, state):
+        """
+        Return the TemplateObject for a record. The records on the table's current page are serialized at once, or
+        for an unpaginated table (e.g. an export), the records in chunks following this one.
+        """
+        objects = table.__dict__.setdefault('_custom_link_objects', {})
+        if record.pk not in objects:
+            if page := getattr(table, 'page', None):
+                pks = [row.record.pk for row in page.object_list]
+                if record.pk not in pks:
+                    pks.append(record.pk)
+            else:
+                # Retain only the current chunk of an unpaginated table
+                objects.clear()
+                pks = CustomLinkColumn._get_chunk(record, table)
+            for pk in pks:
+                objects.setdefault(pk, None)
+            for obj in get_template_objects(type(record)._default_manager.filter(pk__in=pks), state):
+                objects[obj['id']] = obj
+        if (obj := objects.get(record.pk)) is None:
+            raise PermissionDenied(_('You do not have permission to view this object.'))
+        return obj
+
+    @staticmethod
+    def _get_chunk(record, table):
+        """
+        Return the primary keys of the records in an unpaginated table, starting from the given record.
+        """
+        if not hasattr(table, '_custom_link_pks'):
+            queryset = getattr(table.data, 'data', None)
+            pks = list(queryset.values_list('pk', flat=True)) if hasattr(queryset, 'values_list') else []
+            table._custom_link_pks = (pks, {pk: i for i, pk in enumerate(pks)})
+        pks, positions = table._custom_link_pks
+        if (start := positions.get(record.pk)) is None:
+            return [record.pk]
+        return pks[start:start + TEMPLATE_OBJECTS_CHUNK_SIZE]
+
     def render(self, record, table, **kwargs):
         try:
             if rendered := self._render_customlink(record, table):

+ 7 - 5
netbox/utilities/template_objects.py

@@ -339,7 +339,7 @@ class TemplateObjectList:
         return list(dict.fromkeys(queryset))
 
     def _load(self, pks, cache=False):
-        return _load_objects(self._queryset, pks, self._state, cache=cache)
+        return _load_objects(self._queryset.model, pks, self._state, cache=cache)
 
 
 #
@@ -521,15 +521,17 @@ def _fetch_full_data(model, pk, user):
     return _serialize(serializer_class, instance)
 
 
-def _load_objects(queryset, pks, state, cache=False):
+def _load_objects(model, pks, state, cache=False):
     """
     Serialize the objects with the given primary keys in one batch, returning a list of full TemplateObjects in the
-    order of the keys. If cache is True, add their representations to the render's cache.
+    order of the keys. If cache is True, add their representations to the render's cache. The keys must come from a
+    list restricted to the objects the rendering user is permitted to view.
     """
-    model = queryset.model
     if not pks or (serializer_class := _get_serializer_class(model)) is None:
         return []
-    instances = _prepare_queryset(queryset.filter(pk__in=pks), serializer_class)
+    # The keys come from the (restricted) list, so load the objects from the REST API viewset's queryset, which may
+    # annotate fields the serializer renders
+    instances = _prepare_queryset(_get_base_queryset(model).filter(pk__in=pks), serializer_class)
     data = {item['id']: item for item in _serialize(serializer_class, list(instances), many=True)}
     if cache:
         for pk, item in data.items():