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

Restrict include paths to objects the user may view

An include path can now pass only through optional fields, whose
objects are limited to those the user may view, so it can no longer add
fields to a forward relation's object or repeat a parent's list for
every row. Paths also reject fields only the viewset annotates and
write-only fields, and ObjectTypeViewSet validates them as well.

Included devices and virtual machines defer their stored config context
unless it's rendered, and exports and deletions skip include prefetches.
Jeremy Stretch 1 день назад
Родитель
Сommit
eb2b2fde96

+ 3 - 3
docs/integrations/rest-api.md

@@ -361,7 +361,7 @@ The `include` and `omit` parameters also accept dotted paths, which add fields t
 * `include=interfaces.ip_addresses` includes the IP addresses assigned to each interface
 * `include=interfaces.mtu` adds `mtu` to each interface
 * `omit=interfaces.device` removes the parent device from each interface
-* `include=site.region` adds `region` to a device's site, and `omit=site.slug` removes its slug
+* `omit=site.slug` removes the slug from a device's site
 
 ```no-highlight
 GET /api/dcim/devices/123/?include=interfaces.mtu,interfaces.ip_addresses&omit=interfaces.device
@@ -398,9 +398,9 @@ GET /api/dcim/devices/123/?include=interfaces.mtu,interfaces.ip_addresses&omit=i
 }
 ```
 
-A path also includes the fields along it: `include=interfaces.ip_addresses` includes `interfaces` as well. Paths are limited to three segments (e.g. `interfaces.ip_addresses.vrf`). They can't pass through generic relations (such as an IP address's `assigned_object`) or other fields which don't represent a single type of object. Related object counts (such as a site's `device_count`) aren't available on nested objects.
+A path also includes the fields along it: `include=interfaces.ip_addresses` includes `interfaces` as well. Paths are limited to three segments (e.g. `interfaces.ip_addresses.vrf`). A path passed to `include` can pass only through optional fields (such as `interfaces`), whose objects are limited to those you have permission to view, so it can't add fields to a device's `site`, for example. Paths passed to `omit` can pass through other related objects as well, but not through generic relations (such as an IP address's `assigned_object`) or other fields which don't represent a single type of object. Related object counts and other values calculated for a list (such as a location's `device_count`) aren't available on nested objects.
 
-An invalid path passed to `include`, or a dotted path passed to `omit`, returns a 400 response naming it. (Unrecognized field names passed to `fields` or `omit` are ignored.)
+An invalid path passed to `include` or `omit` returns a 400 response naming it. (Unrecognized field names passed to `fields` or `omit` are ignored.)
 
 !!! note
     `include` applies to the REST API responses for listing, retrieving, creating, and updating objects, including the results stored for [background requests](#background-processing). It doesn't affect export templates, the data sent by event rules and webhooks, or change records.

+ 1 - 1
docs/plugins/development/rest-api.md

@@ -76,7 +76,7 @@ class MyModelSerializer(NetBoxModelSerializer):
         optional_fields = ('widgets',)
 ```
 
-`RelatedObjectsField` renders each related object in its brief format, using the serializer for the related model. It lists only the objects the requesting user is permitted to view, and the viewset prefetches them automatically.
+`RelatedObjectsField` renders each related object in its brief format, using the serializer for the related model. It lists only the objects the requesting user is permitted to view, and the viewset prefetches them automatically. (A serializer instantiated without a request in its context, such as in a script, lists every related object.)
 
 ## Viewsets
 

+ 1 - 0
netbox/core/api/views.py

@@ -114,6 +114,7 @@ class ObjectTypeViewSet(NetBoxReadOnlyModelViewSet):
         # which would try to call restrict() on the queryset
         from rest_framework.viewsets import GenericViewSet
         GenericViewSet.initial(self, request, *args, **kwargs)
+        self.validate_field_paths()
 
 
 class BaseRQViewSet(viewsets.ViewSet):

+ 15 - 10
netbox/dcim/tests/test_api.py

@@ -2,6 +2,7 @@ import copy
 import json
 import os
 import tempfile
+from collections import Counter
 from contextlib import contextmanager
 from unittest.mock import patch
 
@@ -168,28 +169,32 @@ class Mixins:
             get_queryset = viewset.get_queryset
 
             def spy(view):
-                querysets.append(get_queryset(view))
-                return querysets[-1]
+                queryset = get_queryset(view)
+                # Record the declared lookups applied, and those the queryset would carry without any
+                queryset.declared_lookups = view.get_field_prefetches()
+                with patch.object(view, 'field_prefetches', {}):
+                    queryset.undeclared_lookups = get_queryset(view)._prefetch_related_lookups
+                querysets.append(queryset)
+                return queryset
 
             with patch.object(viewset, 'get_queryset', spy):
                 yield querysets
 
         def assert_lookups(self, querysets, expected):
             """Assert each queryset leads with exactly these lookups, as these objects, and no other declared one."""
-            declared = [lookup for lookups in self.viewset.field_prefetches.values() for lookup in lookups]
             self.assertTrue(querysets)
             for queryset in querysets:
                 lookups = queryset._prefetch_related_lookups
                 paths = [self.lookup_path(lookup) for lookup in lookups]
                 self.assertEqual(paths[:len(expected)], [self.lookup_path(lookup) for lookup in expected], paths)
                 self.assertTrue(all(a is b for a, b in zip(lookups, expected)), paths)
-                # A declared string can be the very object a dynamic lookup names (Python interns identifier-like
-                # strings, e.g. 'virtual_chassis'), so only Prefetch objects can be told apart by identity
-                tail = [
-                    lookup for lookup in lookups[len(expected):]
-                    if not isinstance(lookup, str) and any(lookup is d for d in declared)
-                ]
-                self.assertFalse(tail, paths)
+                self.assertTrue(all(any(d is e for e in expected) for d in queryset.declared_lookups), paths)
+                # Each declared lookup is applied once, beside those the queryset carries without them
+                self.assertEqual(
+                    Counter(paths),
+                    Counter(map(self.lookup_path, (*queryset.declared_lookups, *queryset.undeclared_lookups))),
+                    paths,
+                )
 
         def test_list_objects_field_prefetches(self):
             """Narrowed responses keep the reference content within its queries, and brief ones skip unread lookups."""

+ 1 - 1
netbox/netbox/api/fields.py

@@ -217,7 +217,7 @@ class RelatedObjectsField(FieldSelectionMixin, serializers.Field):
     """
     Represents the objects of a reverse relation (e.g. the interfaces of a device) as a read-only list of their nested
     representations. Declare it in the serializer's Meta.optional_fields, so that it is rendered only when requested.
-    The list includes only the objects the requesting user is permitted to view.
+    The list includes only the objects the requesting user is permitted to view (or all, without a request).
 
     :param relation: The name of a reverse relation, a many-to-many field, or a GenericRelation
     """

+ 5 - 0
netbox/netbox/api/serializers/base.py

@@ -1,5 +1,6 @@
 from functools import cached_property
 
+from django.utils.translation import gettext_lazy as _
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import extend_schema_field
 from rest_framework import serializers
@@ -135,6 +136,10 @@ class BaseModelSerializer(serializers.ModelSerializer):
             if include or omit:
                 field = fields[field_name]
                 field = getattr(field, 'child', None) or getattr(field, 'child_relation', None) or field
+                if not hasattr(field, 'select_fields'):
+                    raise serializers.ValidationError(
+                        _("Cannot select fields beneath {name}.").format(name=field_name)
+                    )
                 field.select_fields(include=include, omit=omit)
 
         return fields

+ 8 - 3
netbox/netbox/api/viewsets/__init__.py

@@ -130,13 +130,18 @@ class BaseViewSet(GenericViewSet):
         if prefetch := self.get_field_prefetches():
             qs = qs.prefetch_related(*prefetch)
 
+        # Exports and deletions don't render any optional fields requested
+        field_kwargs = self.field_kwargs
+        if 'export' in self.request.query_params or self.request.method == 'DELETE':
+            field_kwargs = {name: value for name, value in field_kwargs.items() if name != 'include'}
+
         # Dynamically resolve prefetches for included serializer fields and attach them to the queryset
-        if prefetch := get_prefetches_for_serializer(serializer_class, **self.field_kwargs, user=self.request.user):
+        if prefetch := get_prefetches_for_serializer(serializer_class, **field_kwargs, user=self.request.user):
             qs = qs.prefetch_related(*prefetch)
 
         # Dynamically resolve annotations for RelatedObjectCountFields on the serializer and attach them to the queryset
         exclude = self.fallback_count_fields if self.renders_whole_objects else ()
-        if annotations := get_annotations_for_serializer(serializer_class, **self.field_kwargs, exclude=exclude):
+        if annotations := get_annotations_for_serializer(serializer_class, **field_kwargs, exclude=exclude):
             qs = qs.annotate(**annotations)
 
         return qs
@@ -206,7 +211,7 @@ class BaseViewSet(GenericViewSet):
             ('omit', [path for path in self.field_kwargs.get('omit', ()) if '.' in path]),
         ):
             for path in paths:
-                if error := get_field_path_error(serializer_class, path):
+                if error := get_field_path_error(serializer_class, path, omit=param == 'omit'):
                     errors.setdefault(param, []).append(f'{path}: {error}')
         if errors:
             raise APIValidationError(errors)

+ 69 - 10
netbox/netbox/tests/test_api.py

@@ -860,12 +860,9 @@ class IncludeFieldsTestCase(APITestCase):
         self.assertEqual(sorted(interface['ip_addresses'][0]), sorted(IPAddressSerializer.Meta.brief_fields))
         self.assertEqual(interface['ip_addresses'][0]['address'], '10.0.0.1/24')
 
-        # Paths traverse forward relations too
-        data = self.get(f'{self.url}?fields=id,site&include=site.region&omit=site.slug')
-        self.assertEqual(
-            sorted(data['site']), sorted({*SiteSerializer.Meta.brief_fields, 'region'} - {'slug'})
-        )
-        self.assertEqual(data['site']['region']['name'], 'Region 1')
+        # Paths to omit traverse forward relations too
+        data = self.get(f'{self.url}?fields=id,site&omit=site.slug')
+        self.assertEqual(sorted(data['site']), sorted(set(SiteSerializer.Meta.brief_fields) - {'slug'}))
 
         # Omitting a field supersedes omitting the fields beneath it
         data = self.get(f'{self.url}?include=interfaces&omit=interfaces,interfaces.device')
@@ -883,11 +880,9 @@ class IncludeFieldsTestCase(APITestCase):
         self.assertEqual([interface['name'] for interface in data['interfaces']], ['eth1'])
         self.assertEqual(data['interfaces'][0]['ip_addresses'], [])
 
-        # Likewise when named in fields, or beneath a forward relation
+        # Likewise when named in fields
         data = self.get(f'{self.url}?fields=id,interfaces')
         self.assertEqual([interface['name'] for interface in data['interfaces']], ['eth1'])
-        data = self.get(f'{self.url}?include=site.devices')
-        self.assertEqual([device['name'] for device in data['site']['devices']], ['Device 0'])
 
         # Likewise when the objects were not prefetched
         request = RequestFactory().get('/')
@@ -986,8 +981,12 @@ class IncludeFieldsTestCase(APITestCase):
             ('include=interfaces.ip_addresses.vrf.rd', 'include', 'interfaces.ip_addresses.vrf.rd'),
             ('include=services.parent.name', 'include', 'services.parent.name'),
             ('include=config_context.foo', 'include', 'config_context.foo'),
-            ('include=site.device_count', 'include', 'site.device_count'),
             ('include=replicate_components', 'include', 'replicate_components'),
+            # Fields can't be added to objects which aren't restricted to those the user may view
+            ('include=site.region', 'include', 'site.region'),
+            ('include=site.devices.interfaces', 'include', 'site.devices.interfaces'),
+            ('include=config_template.template_code', 'include', 'config_template.template_code'),
+            ('include=tags.color', 'include', 'tags.color'),
             ('omit=site.foo', 'omit', 'site.foo'),
         ):
             with self.subTest(params=params):
@@ -997,3 +996,63 @@ class IncludeFieldsTestCase(APITestCase):
 
         # Unrecognized top-level names to omit are ignored, as before
         self.assertIn('name', self.get(f'{self.url}?omit=foo'))
+
+        # Values which the viewset annotates aren't available on nested objects
+        self.add_permissions('dcim.view_site')
+        url = reverse('dcim-api:site-list')
+        data = self.get(f'{url}?include=locations.device_count', status_code=status.HTTP_400_BAD_REQUEST)
+        self.assertTrue(data['include'][0].startswith('locations.device_count: '), data)
+
+        # A viewset which overrides initial() validates the paths too
+        url = reverse('core-api:objecttype-list')
+        data = self.get(f'{url}?include=display.foo', status_code=status.HTTP_400_BAD_REQUEST)
+        self.assertTrue(data['include'][0].startswith('display.foo: '), data)
+
+    def test_serializer_rejects_unselectable_path(self):
+        request = RequestFactory().get('/')
+        request.user = self.user
+        serializer = DeviceSerializer(self.devices[0], include=['config_context.foo'], context={'request': request})
+        with self.assertRaises(ValidationError):
+            serializer.data
+
+    def test_included_config_context(self):
+        """
+        Included devices load their config context only where rendered, in a fixed number of queries.
+        """
+        self.add_permissions('dcim.view_site', 'dcim.view_device')
+        sites = []
+        for i, count in enumerate((1, 3)):
+            site = Site.objects.create(name=f'Config Context Site {i}', slug=f'config-context-site-{i}')
+            for _ in range(count):
+                Device.objects.create(site=site, device_type=self.device_type, role=self.role)
+            sites.append(site)
+        Device.objects.update(_config_context_data=None)
+
+        def get_queries(site, include):
+            url = reverse('dcim-api:site-detail', kwargs={'pk': site.pk})
+            with CaptureQueriesContext(connection) as queries:
+                data = self.get(f'{url}?include={include}')
+            self.assertEqual(len(data['devices']), site.devices.count())
+            # Token authentication refreshes last_used once a minute
+            return [query['sql'] for query in queries.captured_queries if '"users_token"' not in query['sql']]
+
+        queries = get_queries(sites[1], 'devices')
+        self.assertFalse(any('"dcim_device"."_config_context_data"' in query for query in queries), queries)
+
+        get_queries(sites[1], 'devices.config_context')
+        self.assertEqual(
+            len(get_queries(sites[0], 'devices.config_context')), len(get_queries(sites[1], 'devices.config_context'))
+        )
+
+    def test_export_skips_included_fields(self):
+        self.add_permissions('dcim.view_device', 'dcim.view_interface', 'extras.view_exporttemplate')
+        export_template = ExportTemplate.objects.create(
+            name='Device Names', template_code='{% for device in queryset %}{{ device.name }}\n{% endfor %}'
+        )
+        export_template.object_types.set([ObjectType.objects.get_for_model(Device)])
+
+        url = f'{reverse("dcim-api:device-list")}?export=Device Names&include=interfaces'
+        with CaptureQueriesContext(connection) as queries:
+            response = self.client.get(url, **self.header)
+        self.assertHttpStatus(response, status.HTTP_200_OK)
+        self.assertFalse(any('"dcim_interface"' in query['sql'] for query in queries.captured_queries))

+ 39 - 10
netbox/utilities/api.py

@@ -17,7 +17,7 @@ from django.utils.module_loading import import_string
 from django.utils.translation import gettext_lazy as _
 from rest_framework.permissions import BasePermission
 from rest_framework.relations import ManyRelatedField
-from rest_framework.serializers import ALL_FIELDS, ListSerializer, Serializer
+from rest_framework.serializers import ALL_FIELDS, ListSerializer, Serializer, SerializerMethodField
 from rest_framework.views import get_view_name as drf_get_view_name
 
 from extras.constants import HTTP_CONTENT_TYPE_JSON
@@ -239,10 +239,22 @@ def _get_serializer_fields(serializer: Serializer):
     return [field_name for field_name in fields if field_name not in omit]
 
 
-def get_field_path_error(serializer_class, path):
+def _is_annotated_field(field, name, model):
     """
-    Return the reason a dotted field path (e.g. "interfaces.ip_addresses") can't be selected on a serializer, or None
-    if it can.
+    Return True if a declared serializer field reads an attribute which only the model's viewset annotates.
+    """
+    if isinstance(field, RelatedObjectCountField):
+        return not field.fallback_source
+    if not field.read_only or isinstance(field, (SerializerMethodField, RelatedObjectsField)):
+        return False
+    source = field.source or name
+    return source != '*' and not hasattr(model, source.split('.')[0])
+
+
+def get_field_path_error(serializer_class, path, omit=False):
+    """
+    Return the reason a dotted field path (e.g. "interfaces.ip_addresses") can't be included in a serializer (or with
+    omit, omitted from it), or None if it can.
     """
     segments = path.split('.')
     if len(segments) > MAX_FIELD_PATH_DEPTH:
@@ -255,11 +267,14 @@ def get_field_path_error(serializer_class, path):
         if (
             name not in (*_get_default_field_names(serializer_class), *getattr(meta, 'optional_fields', ())) or
             getattr(field, 'write_only', False) or
-            # Related object counts are not annotated on nested objects
-            (nested and isinstance(field, RelatedObjectCountField) and not field.fallback_source)
+            getattr(meta, 'extra_kwargs', {}).get(name, {}).get('write_only') or
+            (nested and field is not None and _is_annotated_field(field, name, meta.model))
         ):
             return _("Unknown field: {name}").format(name=name or '""')
         if i < len(segments) - 1:
+            # Only the objects of a RelatedObjectsField are restricted to those the user may view
+            if not omit and not isinstance(field, RelatedObjectsField):
+                return _("Cannot include fields beneath {name}.").format(name=name)
             if (nested_serializer := _get_nested_serializer(field, meta.model)) is None:
                 return _("Cannot select fields beneath {name}.").format(name=name)
             serializer_class = type(nested_serializer)
@@ -314,6 +329,19 @@ def _get_declared_prefetches(model, fields):
     ]
 
 
+def _get_included_queryset(model, user, fields):
+    """
+    Return the objects of a model which the user may view, for a RelatedObjectsField rendering the given fields.
+    """
+    queryset = model._default_manager.restrict(user, 'view')
+    # Load the config context of config context models only where rendered, as their viewsets do
+    if hasattr(queryset, 'annotate_config_context_data'):
+        if 'config_context' in fields:
+            return queryset.annotate_config_context_data(only_invalidated=True)
+        return queryset.defer('_config_context_data')
+    return queryset
+
+
 def get_prefetches_for_serializer(
     serializer_class, fields=None, omit=None, include=None, user=None, _serializer_states=None
 ):
@@ -344,10 +372,6 @@ def get_prefetches_for_serializer(
             if user is None:
                 continue
             nested_serializer = _get_nested_serializer(serializer_field, model)
-            queryset = nested_serializer.Meta.model._default_manager.restrict(user, 'view')
-            prefetch_fields.append(
-                Prefetch(serializer_field.relation, queryset=queryset, to_attr=serializer_field.to_attr)
-            )
             prefix = serializer_field.to_attr
 
         else:
@@ -389,6 +413,11 @@ def get_prefetches_for_serializer(
             if nested_include or isinstance(serializer_field, RelatedObjectsField):
                 rendered = set(get_fields_for_serializer(nested_class, nested_fields, nested_omit, nested_include))
                 lookups = [*_get_declared_prefetches(nested_class.Meta.model, rendered), *lookups]
+            if isinstance(serializer_field, RelatedObjectsField):
+                queryset = _get_included_queryset(nested_class.Meta.model, user, rendered)
+                prefetch_fields.append(
+                    Prefetch(serializer_field.relation, queryset=queryset, to_attr=serializer_field.to_attr)
+                )
             prefetch_fields.extend(_prefix_lookup(prefix, lookup) for lookup in lookups)
 
     return prefetch_fields

+ 37 - 9
netbox/utilities/tests/test_api.py

@@ -20,6 +20,7 @@ from netbox.api.serializers import BaseModelSerializer
 from netbox.config import get_config
 from netbox.plugins import register_serializer_resolver
 from netbox.registry import registry
+from users.api.serializers import UserSerializer
 from users.models import Group, ObjectPermission, User
 from utilities.api import (
     get_field_path_error,
@@ -544,13 +545,15 @@ class GetFieldPathErrorTestCase(TestCase):
             'interfaces.mtu',
             'interfaces.ip_addresses',
             'interfaces.ip_addresses.vrf',
-            'site.region',
-            'site.slug',
-            'primary_ip4.vrf',
-            'tags.color',
         ):
             with self.subTest(path=path):
                 self.assertIsNone(get_field_path_error(DeviceSerializer, path))
+                self.assertIsNone(get_field_path_error(DeviceSerializer, path, omit=True))
+
+    def test_valid_paths_to_omit(self):
+        for path in ('site.slug', 'primary_ip4.vrf', 'tags.color', 'interfaces.device.name'):
+            with self.subTest(path=path):
+                self.assertIsNone(get_field_path_error(DeviceSerializer, path, omit=True))
 
     def test_invalid_paths(self):
         for path, error in (
@@ -558,17 +561,42 @@ class GetFieldPathErrorTestCase(TestCase):
             ('interfaces.foo', 'Unknown field: foo'),
             ('interfaces..mtu', 'Unknown field: ""'),
             ('interfaces.ip_addresses.vrf.rd', 'Field paths may not exceed 3 segments.'),
+            # Write-only fields are never rendered
+            ('replicate_components', 'Unknown field: replicate_components'),
+            # Only the objects of optional fields are restricted to those the user may view
+            ('site.region', 'Cannot include fields beneath site.'),
+            ('tags.color', 'Cannot include fields beneath tags.'),
+            ('interfaces.device.name', 'Cannot include fields beneath device.'),
+            ('config_context.foo', 'Cannot include fields beneath config_context.'),
+        ):
+            with self.subTest(path=path):
+                self.assertEqual(get_field_path_error(DeviceSerializer, path), error)
+
+    def test_invalid_paths_to_omit(self):
+        for path, error in (
+            ('site.foo', 'Unknown field: foo'),
             # Generic foreign keys and method fields have no fixed serializer
             ('services.parent.name', 'Cannot select fields beneath parent.'),
             ('config_context.foo', 'Cannot select fields beneath config_context.'),
             ('name.foo', 'Cannot select fields beneath name.'),
-            # Related object counts are not annotated on nested objects
-            ('site.device_count', 'Unknown field: device_count'),
-            # Write-only fields are never rendered
-            ('replicate_components', 'Unknown field: replicate_components'),
         ):
             with self.subTest(path=path):
-                self.assertEqual(get_field_path_error(DeviceSerializer, path), error)
+                self.assertEqual(get_field_path_error(DeviceSerializer, path, omit=True), error)
+
+    def test_annotated_fields_on_nested_objects(self):
+        # Values which the viewset annotates (whether as related object counts or plain fields) are unavailable
+        for path in ('locations.device_count', 'locations.rack_count'):
+            with self.subTest(path=path):
+                self.assertEqual(
+                    get_field_path_error(SiteSerializer, path), f'Unknown field: {path.split(".")[1]}'
+                )
+        self.assertEqual(
+            get_field_path_error(DeviceSerializer, 'site.circuit_count', omit=True), 'Unknown field: circuit_count'
+        )
+
+    def test_write_only_fields(self):
+        # Declared write-only, or made so in Meta.extra_kwargs
+        self.assertEqual(get_field_path_error(UserSerializer, 'password'), 'Unknown field: password')
 
 
 class AllFieldsSerializerTestCase(TestCase):