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

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 as plain data,
and query() available. perms is unchanged, but can only be read by
item. Table columns serialize the records on a page (or chunks of an
export) at once.
Jeremy Stretch 17 часов назад
Родитель
Сommit
2adb6c3765

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

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

@@ -39,6 +39,28 @@ 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`                                                              |
+| `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. A query matching more than `MAX_PAGE_SIZE` objects (1,000 if it's 0) raises an error, unless a smaller `limit` is passed. |
+
+`debug`, `perms`, 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` and `user` 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

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

@@ -4,6 +4,8 @@ import urllib.parse
 from pathlib import Path
 
 from django.conf import settings
+from django.contrib.auth.context_processors import PermWrapper
+from django.contrib.auth.models import AnonymousUser
 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.contrib.postgres.fields import ArrayField
 from django.core.exceptions import ValidationError
@@ -51,7 +53,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 +507,52 @@ 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
+        # Render on behalf of the request's user, or an anonymous user if it has none
+        user = None if request is None else getattr(request, 'user', None) or AnonymousUser()
+        # Links render for every row of a table, so cap the objects a query() can return
+        return RestrictedRenderState(
+            user,
+            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 by plain data.
+        """
+        context = {
+            'object': obj if isinstance(obj, TemplateObject) else get_template_object(obj, state),
+            'debug': debug,
+        }
+        if request is not None:
+            user = state.user or AnonymousUser()
+            context.update({
+                'request': to_plain_data(get_safe_request_context(request)),
+                'user': {'id': user.pk, 'username': user.get_username()},
+                'perms': PermWrapper(user),
+            })
+        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

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

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

@@ -1,13 +1,19 @@
+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.contrib.auth.models import AnonymousUser
+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, get_template_objects
 
 User = get_user_model()
 
@@ -226,3 +232,189 @@ 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 }}', 'True False'),
+            ("{{ perms['dcim']['view_site'] }} {{ 'dcim.view_site' in perms }}", 'True True'),
+            ('{{ 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_permission_in_unpermitted_app(self):
+        output = self.render_link('{% if perms.circuits.view_circuit %}yes{% else %}no{% endif %}')
+        self.assertIn('>no</a>', output)
+
+    def test_permission_attributes_not_reachable(self):
+        # Attributes are looked up as permissions, so the wrapped user can't be reached
+        self.assertIn('>False</a>', self.render_link('{{ perms.dcim.app_label }}'))
+        CustomLink.objects.all().delete()
+        output = self.render_link('{{ perms.dcim.user.username }}')
+        self.assertIn('mdi-alert', output)
+        self.assertNotIn('user1', output)
+
+    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_render_state_follows_request(self):
+        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 = {}
+        table.paginate(per_page=3)
+        self.assertIn('requires a user', table.page.object_list[0].get_cell('cl_Link 1'))
+        # The render state created without a request isn't retained
+        table.context = {'request': self.get_request()}
+        self.assertIn('>Site 1</a>', table.page.object_list[0].get_cell('cl_Link 1'))
+
+    @patch('netbox.tables.columns.TEMPLATE_OBJECTS_CHUNK_SIZE', 2)
+    def test_table_export_from_list(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(list(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'])
+        # A table built from a list is also serialized in chunks
+        self.assertEqual([len(call.args[1]) for call in load_objects.call_args_list], [2, 1])
+
+    @override_settings(EXEMPT_VIEW_PERMISSIONS=['*'])
+    def test_table_anonymous_user(self):
+        custom_link = CustomLink.objects.create(
+            name='Link 1', enabled=True, link_text='{{ user.username }}|{{ object.tenant.name }}', link_url='/'
+        )
+        custom_link.object_types.set([ObjectType.objects.get_for_model(Site)])
+        table = SiteTable(Site.objects.order_by('name'))
+        request = RequestFactory().get('/dcim/sites/')
+        request.user = AnonymousUser()
+        table.context = {'request': request}
+        table.paginate(per_page=3)
+        # The link renders on behalf of the anonymous user
+        self.assertIn('>|Tenant 1</a>', table.page.object_list[0].get_cell('cl_Link 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_table_load_failure(self):
+        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)
+        calls = []
+
+        def fail_once(*args, **kwargs):
+            calls.append(args)
+            if len(calls) == 1:
+                raise RuntimeError('Load failed')
+            return get_template_objects(*args, **kwargs)
+
+        with patch('netbox.tables.columns.get_template_objects', side_effect=fail_once):
+            cells = [row.get_cell('cl_Link 1') for row in table.page.object_list]
+        self.assertIn('Load failed', cells[0])
+        # A failed load isn't retained, so the next record loads the batch again rather than reporting it as hidden
+        self.assertIn('>Site 2</a>', cells[1])
+        self.assertIn('>Site 3</a>', cells[2])
+        self.assertEqual(len(calls), 2)
+
+    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),
 }

+ 68 - 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,83 @@ class CustomLinkColumn(tables.Column):
         super().__init__(*args, **kwargs)
 
     def _render_customlink(self, record, table):
+        request = getattr(table, 'context', {}).get('request')
+        # Share the render state, and the objects serialized for it, among all of the table's custom link columns.
+        # Retain them only for the request they were created for.
+        cached_request, state, objects = getattr(table, '_custom_link_render_state', (None, None, None))
+        if request is None or cached_request is not request:
+            state, objects = self.customlink.get_render_state(request), {}
+            if request is not None:
+                table._custom_link_render_state = (request, state, objects)
+        if state is not None:
+            obj = self._get_template_object(record, table, state, objects)
+            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, objects):
+        """
+        Return the TemplateObject for a record, retaining the objects serialized in the given dict. 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.
+        """
+        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, and the related objects fetched for it
+                objects.clear()
+                state.cache.clear()
+                pks = CustomLinkColumn._get_chunk(record, table)
+            # Records which aren't returned aren't viewable by the user. Retain the batch only once it has loaded, so
+            # that a failure is raised again for the next record rather than reported as a permission error.
+            batch = dict.fromkeys(pks)
+            for obj in get_template_objects(type(record)._default_manager.filter(pk__in=pks), state):
+                batch[obj['id']] = obj
+            objects.update(batch)
+        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'):
+            data = getattr(table.data, 'data', None)
+            if hasattr(data, 'values_list'):
+                pks = list(data.values_list('pk', flat=True))
+            else:
+                # A table built from a list of records
+                pks = [getattr(item, 'pk', None) for item in data or ()]
+            table._custom_link_pks = pks
+            table._custom_link_next = 0
+        pks = table._custom_link_pks
+        # Records are normally rendered in order, so expect the record following the previous chunk
+        start = table._custom_link_next
+        if start >= len(pks) or pks[start] != record.pk:
+            try:
+                start = pks.index(record.pk)
+            except ValueError:
+                return [record.pk]
+        table._custom_link_next = start + TEMPLATE_OBJECTS_CHUNK_SIZE
+        return pks[start:table._custom_link_next]
+
     def render(self, record, table, **kwargs):
         try:
             if rendered := self._render_customlink(record, table):

+ 6 - 1
netbox/utilities/jinja2.py

@@ -6,6 +6,7 @@ from types import FunctionType
 
 from django.apps import apps
 from django.conf import settings
+from django.contrib.auth.context_processors import PermLookupDict, PermWrapper
 from django.core.exceptions import ValidationError
 from django.utils.translation import gettext_lazy as _
 from jinja2 import BaseLoader, TemplateNotFound
@@ -127,6 +128,8 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
     allowed_template_types = (
         BlockReference, Cycler, Joiner, LoopContext, Macro, Namespace, TemplateModule, TemplateReference, Undefined,
     )
+    # Accessed only by item (e.g. perms.dcim.view_site), so that their attributes (such as the user) aren't reachable
+    item_only_types = (PermWrapper, PermLookupDict)
 
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
@@ -151,12 +154,14 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
         return self.is_allowed(getattr(obj, '__self__', obj))
 
     def getattr(self, obj, attribute):
+        if type(obj) in self.item_only_types:
+            return super().getitem(obj, attribute)
         if not self.is_allowed(obj):
             return self.unsafe_undefined(obj, attribute)
         return super().getattr(obj, attribute)
 
     def getitem(self, obj, argument):
-        if not self.is_allowed(obj):
+        if not (self.is_allowed(obj) or type(obj) in self.item_only_types):
             return self.unsafe_undefined(obj, argument)
         return super().getitem(obj, argument)
 

+ 9 - 6
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,18 @@ 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, limited to those the rendering user is permitted to view. If cache is True, add their
+    representations to the render's cache.
     """
-    model = queryset.model
-    if not pks or (serializer_class := _get_serializer_class(model)) is None:
+    queryset = _get_base_queryset(model)
+    if not pks or (serializer_class := _get_serializer_class(model)) is None or not hasattr(queryset, 'restrict'):
         return []
-    instances = _prepare_queryset(queryset.filter(pk__in=pks), serializer_class)
+    # Load the objects from the REST API viewset's queryset, which may annotate fields the serializer renders
+    queryset = queryset.restrict(state.user, 'view').filter(pk__in=pks)
+    instances = _prepare_queryset(queryset, serializer_class)
     data = {item['id']: item for item in _serialize(serializer_class, list(instances), many=True)}
     if cache:
         for pk, item in data.items():