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

Closes #23875: Explain missing fields in restricted rendering

A field a restricted template can't find on an object now raises an
error naming the model and the cause: an object the rendering user
can't view, a common legacy name (with its replacement), a model
method or reverse relation, or a likely misspelling. A missing
attribute of a list of objects names the methods lists provide.
Jeremy Stretch 3 часов назад
Родитель
Сommit
da62bcabb0

+ 9 - 2
netbox/utilities/jinja2.py

@@ -29,6 +29,7 @@ from utilities.template_objects import (
     RelatedObjectList,
     RelatedObjectList,
     TemplateObject,
     TemplateObject,
     TemplateObjectList,
     TemplateObjectList,
+    get_missing_field_hint,
     get_query_function,
     get_query_function,
     template_json_default,
     template_json_default,
 )
 )
@@ -178,12 +179,18 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
             return super().getitem(obj, attribute)
             return super().getitem(obj, attribute)
         if not self.is_allowed(obj):
         if not self.is_allowed(obj):
             return self.unsafe_undefined(obj, attribute)
             return self.unsafe_undefined(obj, attribute)
-        return super().getattr(obj, attribute)
+        return self._explain_undefined(obj, attribute, super().getattr(obj, attribute))
 
 
     def getitem(self, obj, argument):
     def getitem(self, obj, argument):
         if not (self.is_allowed(obj) or type(obj) in self.item_only_types):
         if not (self.is_allowed(obj) or type(obj) in self.item_only_types):
             return self.unsafe_undefined(obj, argument)
             return self.unsafe_undefined(obj, argument)
-        return super().getitem(obj, argument)
+        return self._explain_undefined(obj, argument, super().getitem(obj, argument))
+
+    def _explain_undefined(self, obj, name, value):
+        # Explain why a field of an object (or an attribute of a list of objects) is missing, e.g. a legacy name
+        if isinstance(value, Undefined) and isinstance(name, str) and (hint := get_missing_field_hint(obj, name)):
+            return self.undefined(hint=hint, obj=obj, name=name)
+        return value
 
 
     def unsafe_undefined(self, obj, attribute):
     def unsafe_undefined(self, obj, attribute):
         # Fail rather than rendering an empty string
         # Fail rather than rendering an empty string

+ 79 - 0
netbox/utilities/template_objects.py

@@ -1,3 +1,5 @@
+import difflib
+import re
 from collections.abc import Mapping
 from collections.abc import Mapping
 from copy import deepcopy
 from copy import deepcopy
 from datetime import date, datetime, time, timedelta
 from datetime import date, datetime, time, timedelta
@@ -11,6 +13,7 @@ from django.contrib.contenttypes.models import ContentType
 from django.core.exceptions import FieldDoesNotExist
 from django.core.exceptions import FieldDoesNotExist
 from django.db import models
 from django.db import models
 from django.db.models import prefetch_related_objects
 from django.db.models import prefetch_related_objects
+from django.db.models.fields.related_descriptors import ManyToManyDescriptor, ReverseManyToOneDescriptor
 from django.utils.datastructures import MultiValueDict
 from django.utils.datastructures import MultiValueDict
 from jinja2.exceptions import TemplateRuntimeError
 from jinja2.exceptions import TemplateRuntimeError
 from netaddr import IPAddress, IPNetwork
 from netaddr import IPAddress, IPNetwork
@@ -41,6 +44,7 @@ __all__ = (
     'RelatedObjectList',
     'RelatedObjectList',
     'TemplateObject',
     'TemplateObject',
     'TemplateObjectList',
     'TemplateObjectList',
+    'get_missing_field_hint',
     'get_query_function',
     'get_query_function',
     'get_template_context_data',
     'get_template_context_data',
     'get_template_object',
     'get_template_object',
@@ -70,6 +74,13 @@ _GENERIC_OBJECTS = object()
 # Marks a field for which an object has no value (e.g. an object the rendering user may not view)
 # Marks a field for which an object has no value (e.g. an object the rendering user may not view)
 _MISSING = object()
 _MISSING = object()
 
 
+# Replacements for names which legacy templates commonly use, but objects don't provide in restricted rendering
+_LEGACY_NAME_HINTS = {
+    'cf': "Custom field values are under custom_fields (e.g. custom_fields.name).",
+    'get_absolute_url': "Use display_url for the object's URL.",
+    'get_config_context': "Use config_context.",
+}
+
 
 
 def get_template_object(instance, state):
 def get_template_object(instance, state):
     """
     """
@@ -131,6 +142,21 @@ def get_template_context_data(value):
     return value
     return value
 
 
 
 
+def get_missing_field_hint(obj, name):
+    """
+    Return a message explaining why a TemplateObject or list of objects has no attribute with the given name, or None
+    for any other object.
+    """
+    if type(obj) is TemplateObject:
+        return obj._describe_missing(name)
+    if type(obj) in (TemplateObjectList, RelatedObjectList):
+        return (
+            f"A list of objects has no attribute {name!r}. Lists provide all(), count() and first(). Filter them with "
+            f"selectattr() or rejectattr(), or fetch objects with query()."
+        )
+    return None
+
+
 def template_json_default(obj):
 def template_json_default(obj):
     """
     """
     JSON encoder hook for restricted rendering: TemplateObjects serialize to their full representation.
     JSON encoder hook for restricted rendering: TemplateObjects serialize to their full representation.
@@ -244,6 +270,26 @@ class TemplateObject(Mapping):
         label = self._model._meta.label if self._model is not None else None
         label = self._model._meta.label if self._model is not None else None
         return f'<TemplateObject {label} id={self._data.get("id")!r}>'
         return f'<TemplateObject {label} id={self._data.get("id")!r}>'
 
 
+    def _describe_missing(self, name):
+        """
+        Return a message explaining why the object has no field with the given name.
+        """
+        if self._model is None:
+            return None
+        label = self._model._meta.label_lower
+        pk = self._data.get('id')
+        if (batch := self._get_batch()) is not None and pk not in batch.get_instances():
+            return (
+                f"{label} {pk} has no field {name!r}: the rendering user isn't permitted to view this object, so only "
+                f"the fields of its brief representation are available ({', '.join(self._data)})."
+            )
+        message = f"{label} has no field {name!r}."
+        if hint := _get_legacy_name_hint(self._model, name):
+            return f'{message} {hint}'
+        if matches := difflib.get_close_matches(name, _get_field_names(self._model, self._state), n=1):
+            return f'{message} Did you mean {matches[0]!r}?'
+        return message
+
     def _get_batch(self):
     def _get_batch(self):
         if self._batch is None and self._model is not None and (pk := self._data.get('id')) is not None:
         if self._batch is None and self._model is not None and (pk := self._data.get('id')) is not None:
             self._batch = _get_batch(self._model, pk, self._state, self._batches)
             self._batch = _get_batch(self._model, pk, self._state, self._batches)
@@ -780,6 +826,39 @@ def _get_relations(model):
     return relations
     return relations
 
 
 
 
+def _get_field_names(model, state):
+    """
+    Return the names of the fields a model's objects provide, including optional reverse relations.
+    """
+    if (serializer_class := _get_serializer_class(model)) is None:
+        return []
+    serializer, fields = _get_serializer(model, state)
+    names = set(fields if fields is not None else serializer.fields)
+    names.update(getattr(serializer_class.Meta, 'optional_fields', ()))
+    return sorted(names)
+
+
+def _get_legacy_name_hint(model, name):
+    """
+    Return a hint for a name which a legacy template might use (e.g. a model method), or None.
+    """
+    if name in _LEGACY_NAME_HINTS:
+        return _LEGACY_NAME_HINTS[name]
+    if match := re.fullmatch(r'get_(\w+)_display', name):
+        return f"Use {match[1]}.label for a choice's label."
+    attribute = getattr(model, name, None)
+    if isinstance(attribute, ReverseManyToOneDescriptor):
+        field = attribute.field
+        related_model = field.related_model if isinstance(field, GenericRelation) else field.model
+        return f"Fetch the related {related_model._meta.label_lower} objects with query()."
+    if isinstance(attribute, ManyToManyDescriptor):
+        related_model = attribute.rel.related_model if attribute.reverse else attribute.rel.model
+        return f"Fetch the related {related_model._meta.label_lower} objects with query()."
+    if callable(attribute) or isinstance(attribute, property):
+        return "Model methods and properties aren't available in restricted rendering."
+    return None
+
+
 def _get_choice_fields(model):
 def _get_choice_fields(model):
     """
     """
     Return the names of the serializer fields which represent choices (as {value, label}).
     Return the names of the serializer fields which represent choices (as {value, label}).

+ 24 - 1
netbox/utilities/tests/test_template_objects.py

@@ -283,13 +283,36 @@ class TemplateObjectTest(TestCase):
         # The brief representation remains available
         # The brief representation remains available
         self.assertEqual(self.render('{{ object.tenant.name }}', user=user, object=self.device), 'Tenant 1')
         self.assertEqual(self.render('{{ object.tenant.name }}', user=user, object=self.device), 'Tenant 1')
         self.assertEqual(self.render('{{ object.tenant.group is defined }}', user=user, object=self.device), 'False')
         self.assertEqual(self.render('{{ object.tenant.group is defined }}', user=user, object=self.device), 'False')
-        with self.assertRaises(UndefinedError):
+        with self.assertRaisesMessage(UndefinedError, "isn't permitted to view this object"):
             self.render('{{ object.tenant.group.slug }}', user=user, object=self.device)
             self.render('{{ object.tenant.group.slug }}', user=user, object=self.device)
 
 
         grant_view(user, Tenant)
         grant_view(user, Tenant)
         user = User.objects.get(pk=user.pk)  # Clear the cached permissions
         user = User.objects.get(pk=user.pk)  # Clear the cached permissions
         self.assertEqual(self.render('{{ object.tenant.group.slug }}', user=user, object=self.device), 'corp')
         self.assertEqual(self.render('{{ object.tenant.group.slug }}', user=user, object=self.device), 'corp')
 
 
+    def test_missing_field_messages(self):
+        cases = (
+            ('{{ object.cf.foo }}', "dcim.device has no field 'cf'. Custom field values are under custom_fields"),
+            ('{{ object.get_status_display() }}', 'Use status.label'),
+            ('{{ object.get_absolute_url() }}', 'Use display_url'),
+            ('{{ object.get_config_context() }}', 'Use config_context'),
+            ('{{ object.consoleports }}', 'Fetch the related dcim.consoleport objects with query()'),
+            ('{{ object.images }}', 'Fetch the related extras.imageattachment objects with query()'),
+            ('{{ object.get_vc_master() }}', "Model methods and properties aren't available"),
+            ('{{ object.seriall }}', "Did you mean 'serial'?"),
+            ('{{ object["cf"] }}', "dcim.device has no field 'cf'"),
+            ('{{ object.interfaces.filter(name="eth0") }}', "A list of objects has no attribute 'filter'"),
+            ('{{ object.tags.filter() }}', "A list of objects has no attribute 'filter'"),
+        )
+        for template_code, message in cases:
+            with self.subTest(template_code=template_code):
+                with self.assertRaisesMessage(UndefinedError, message):
+                    self.render(template_code, object=self.device)
+        # A missing field can still be tested for
+        self.assertEqual(
+            self.render('{{ object.cf is defined }} {{ object.cf | default("-") }}', object=self.device), 'False -'
+        )
+
     def test_viewset_annotations(self):
     def test_viewset_annotations(self):
         location = Location.objects.create(name='Location 1', slug='location-1', site=self.device.site)
         location = Location.objects.create(name='Location 1', slug='location-1', site=self.device.site)
         Device.objects.filter(pk=self.device.pk).update(location=location)
         Device.objects.filter(pk=self.device.pk).update(location=location)