Преглед изворни кода

Closes #23875: Address restricted rendering follow-ups

Restricted rendering now fails on undefined names and attributes,
except attributes of None, rather than rendering an empty string.
Choice fields render and compare as their values, and lists of related
objects provide all(), count() and first().

Overrides of RenderTemplateMixin methods written for earlier
signatures keep working, and only RestrictedRenderingMixin's field
opts an object into restricted rendering. render_config() without a
user in restricted mode now names the cause.
Jeremy Stretch пре 17 часа
родитељ
комит
50cb9a2240

+ 1 - 1
docs/configuration/system.md

@@ -424,7 +424,7 @@ Default: `'legacy'`
 Selects how each feature that renders user-authored Jinja templates builds its rendering context. Two modes are available:
 
 * `legacy`: Templates have access to live objects and, in some cases, model classes. Permission to author these templates should be granted only to fully trusted users.
-* `restricted`: Templates receive only static data. They are rendered in a stricter sandbox that permits attribute access and method calls only on basic data types (dicts, lists, strings, numbers, booleans, and `None`), IP addresses and prefixes (netaddr objects), and dates and times. These keep the same attributes and methods as in legacy mode, such as `.netmask` or `.strftime()`. Any other object renders as its string value, and accessing its attributes or methods raises an error. Filters remain available, including those defined in [`JINJA_FILTERS`](#jinja_filters) and by plugins.
+* `restricted`: Templates receive only static data. They are rendered in a stricter sandbox that permits attribute access and method calls only on basic data types (dicts, lists, strings, numbers, booleans, and `None`), IP addresses and prefixes (netaddr objects), and dates and times. These keep the same attributes and methods as in legacy mode, such as `.netmask` or `.strftime()`. Any other object renders as its string value, and accessing its attributes or methods raises an error. An undefined variable or attribute (e.g. a misspelled field name) raises an error rather than rendering an empty string, unless a template's `undefined` environment parameter is set. An attribute of `None` (e.g. `object.tenant.name` where no tenant is assigned) renders empty, as in legacy mode. Filters remain available, including those defined in [`JINJA_FILTERS`](#jinja_filters) and by plugins.
 
 Set a single mode for all features, or a mode per feature. A feature omitted from the dictionary uses the default mode.
 

+ 2 - 1
docs/customization/custom-links.md

@@ -49,6 +49,8 @@ When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) c
 | `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. |
 
+A choice field (e.g. `object.status`) renders and compares as its value, as in legacy mode, and holds its label as `.label`. A list of related objects (e.g. `object.tags`) provides `all()`, `count()`, and `first()`.
+
 `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:
@@ -57,7 +59,6 @@ Most links work the same in both modes. Common changes needed when migrating a l
 |-----------------------------------------|-----------------------------------------------|
 | `{{ 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 }}`                 |
 

+ 2 - 0
docs/customization/export-templates.md

@@ -47,6 +47,8 @@ When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) c
 | `user`    | A dictionary holding the `id` and `username` of the user exporting the objects |
 | `query()` | A function which returns the objects matching the given REST API filters (e.g. `query('ipam.ipaddress', parent=prefix.prefix)`), limited to those the user is permitted to view |
 
+A choice field (e.g. `site.status`) renders and compares as its value, as in legacy mode, and holds its label as `.label`. A list of related objects (e.g. `site.tags`) provides `all()`, `count()`, and `first()`.
+
 Model classes (e.g. `dcim.Site`) aren't available, and each variable provided by a plugin is included only if its value can be serialized to JSON. A stored `finalize` environment parameter is ignored. Content which isn't served as an attachment is sent with a `Content-Security-Policy: sandbox; default-src 'none'` header, as image attachments are. Any scripts it contains don't run, and inline HTML output can't load images, stylesheets, or fonts.
 
 In legacy mode, `objects` and `user` are also provided, so templates can be migrated one at a time before switching modes. Common changes needed when migrating a template:

+ 1 - 0
docs/features/configuration-rendering.md

@@ -54,6 +54,7 @@ There are {{ dcim.Site.objects.count() }} sites.
 When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for config templates, or a template has restricted rendering enabled, templates are rendered in a restricted environment which permits access only to plain data, IP addresses, and dates and times:
 
 * `device` and `virtualmachine` hold the object's REST API representation. Related objects and reverse relations (e.g. `device.interfaces`) are fetched as they're accessed, limited to those the requesting user is permitted to view.
+* A choice field (e.g. `device.status`) renders and compares as its value, as in legacy mode, and holds its label as `.label`. A list of related objects (e.g. `device.tags`) provides `all()`, `count()`, and `first()`.
 * Config context data and REST API request data are unchanged.
 * Model classes aren't available. Use the `query()` function instead, which returns the objects matching the given REST API filters, limited to those the user is permitted to view. For example:
 

+ 1 - 1
docs/plugins/development/config-templates.md

@@ -131,7 +131,7 @@ Devices and virtual machines provide two methods for rendering their configurati
 
 Renders and returns the object's configuration as text. If `config_template` is not given, the template is resolved from the object, its role, or its platform (in that order). Returns `None` if no template applies. Rendering errors are raised to the caller.
 
-When config templates are rendered in [restricted mode](../../features/configuration-rendering.md#restricted-rendering), the template runs on behalf of `user`, which is required: related objects and `query()` results are limited to those the user is permitted to view. Objects, querysets, and related managers passed in `extra_context` (including in lists and dictionaries) are represented in the same way as the rendered object and its related objects. A sliced queryset (e.g. `device.interfaces.all()[:5]`) takes the same slice of the objects the user is permitted to view. IP addresses, dates and times are passed as they are, and other values are converted to plain data.
+When config templates are rendered in [restricted mode](../../features/configuration-rendering.md#restricted-rendering), the template runs on behalf of `user`, which is required (calling `render_config()` without it raises a `ValueError`): related objects and `query()` results are limited to those the user is permitted to view. Objects, querysets, and related managers passed in `extra_context` (including in lists and dictionaries) are represented in the same way as the rendered object and its related objects. A sliced queryset (e.g. `device.interfaces.all()[:5]`) takes the same slice of the objects the user is permitted to view. IP addresses, dates and times are passed as they are, and other values are converted to plain data.
 
 ```python
 from dcim.models import Device

+ 5 - 0
netbox/dcim/models/mixins.py

@@ -83,6 +83,11 @@ class RenderConfigMixin(models.Model):
         config_template = config_template or self.get_config_template()
         if config_template is None:
             return None
+        if user is None and config_template.uses_restricted_rendering():
+            raise ValueError(
+                f"Config template {config_template} renders in restricted mode, which requires a user. Pass the user "
+                f"on whose behalf to render the configuration, e.g. render_config(user=user)."
+            )
         return config_template.render(context=self.get_render_context(extra_context), user=user)
 
 

+ 5 - 0
netbox/dcim/tests/test_models.py

@@ -1710,6 +1710,11 @@ class DeviceRestrictedRenderConfigTestCase(TestCase):
         config_template = ConfigTemplate.objects.create(name='Template 1', template_code=template_code)
         return self.device.render_config(config_template, user=user or self.superuser, **kwargs)
 
+    def test_user_required(self):
+        config_template = ConfigTemplate.objects.create(name='Template 1', template_code='{{ device.name }}')
+        with self.assertRaisesMessage(ValueError, 'renders in restricted mode, which requires a user'):
+            self.device.render_config(config_template)
+
     def test_context(self):
         cases = (
             ('{{ device.name }} {{ device.status.value }} {{ device.site.slug }}', 'Device 1 active site-1'),

+ 17 - 4
netbox/extras/models/mixins.py

@@ -13,6 +13,7 @@ from django.core.files.storage import storages
 from django.db import models
 from django.http import HttpResponse
 from django.utils.http import content_disposition_header
+from django.utils.inspect import func_accepts_kwargs, func_supports_parameter
 from django.utils.module_loading import import_string
 from django.utils.translation import gettext_lazy as _
 from jinja2 import TemplateError
@@ -40,6 +41,16 @@ _stored_finalize_warned = set()
 _plugin_context_warned = set()
 
 
+def _call_with_supported_kwargs(method, **kwargs):
+    """
+    Call a method with only the keyword arguments it accepts, so that an override written before an argument was added
+    (e.g. a plugin's get_context() without user) keeps working.
+    """
+    if not func_accepts_kwargs(method):
+        kwargs = {name: value for name, value in kwargs.items() if func_supports_parameter(method, name)}
+    return method(**kwargs)
+
+
 class CustomStoragesLoader(importlib.abc.Loader):
     """
     Custom loader for exec_module to use django-storages instead of the file system.
@@ -114,7 +125,8 @@ class TemplateRenderingModeMixin:
         Return True if this object renders in restricted mode: either it's opted in (see RestrictedRenderingMixin), or
         TEMPLATE_RENDERING selects restricted mode for its feature.
         """
-        return getattr(self, 'restricted', False) or (
+        # Test for the mixin, since a model may have an unrelated attribute named "restricted"
+        return (isinstance(self, RestrictedRenderingMixin) and self.restricted) or (
             self.template_rendering_feature is not None and
             get_template_rendering_mode(self.template_rendering_feature) == TEMPLATE_RENDERING_RESTRICTED
         )
@@ -359,7 +371,8 @@ class RenderTemplateMixin(TemplateRenderingModeMixin, models.Model):
         mode). In restricted mode, rendering runs on behalf of the given user.
         """
         if not self.uses_restricted_rendering():
-            return self.get_context(context=context, queryset=queryset, user=user), None
+            context = _call_with_supported_kwargs(self.get_context, context=context, queryset=queryset, user=user)
+            return context, None
         state = RestrictedRenderState(user)
         return self.get_restricted_context(state, context=context, queryset=queryset), state
 
@@ -374,7 +387,7 @@ class RenderTemplateMixin(TemplateRenderingModeMixin, models.Model):
         """
         Render the template with a context and render state returned by prepare_render().
         """
-        env_params = self.get_environment_params(restricted=state is not None)
+        env_params = _call_with_supported_kwargs(self.get_environment_params, restricted=state is not None)
         debug = getattr(self, 'debug', False)
         output = render_jinja2(
             self.template_code,
@@ -391,7 +404,7 @@ class RenderTemplateMixin(TemplateRenderingModeMixin, models.Model):
         return output
 
     def render_to_response(self, context=None, queryset=None, user=None):
-        output = self.render(context=context, queryset=queryset, user=user)
+        output = _call_with_supported_kwargs(self.render, context=context, queryset=queryset, user=user)
         mime_type = self.mime_type or DEFAULT_MIME_TYPE
 
         # Build the response

+ 50 - 2
netbox/extras/tests/test_models.py

@@ -4,7 +4,7 @@ import sys
 import tempfile
 import warnings
 from pathlib import Path
-from types import SimpleNamespace
+from types import MethodType, SimpleNamespace
 from unittest.mock import patch
 
 from django.conf import settings
@@ -39,7 +39,7 @@ from extras.models import (
     TaggedItem,
     Webhook,
 )
-from extras.models.mixins import RenderTemplateMixin
+from extras.models.mixins import RenderTemplateMixin, TemplateRenderingModeMixin
 from tenancy.models import Tenant, TenantGroup
 from users.models import User
 from utilities.exceptions import AbortRequest
@@ -1477,6 +1477,54 @@ class RenderTemplateMixinRenderTestCase(TestCase):
         self.assertEqual(t.environment_params, {'undefined': 'jinja2.StrictUndefined'})
 
 
+class RenderTemplateMixinCompatibilityTestCase(TestCase):
+    """
+    Overrides written for the signatures of earlier releases (e.g. in plugins) keep working.
+    """
+
+    @classmethod
+    def setUpTestData(cls):
+        Site.objects.create(name='Site 1', slug='site-1')
+        cls.user = User.objects.create_user(username='admin', is_superuser=True)
+
+    def test_overrides_without_new_arguments(self):
+        template = ExportTemplate(name='Template 1', template_code='{{ queryset.count() }} {{ extra }}')
+
+        def get_context(self, context=None, queryset=None):
+            return {'queryset': queryset, 'extra': 'x'}
+
+        def get_environment_params(self):
+            return {}
+
+        template.get_context = MethodType(get_context, template)
+        template.get_environment_params = MethodType(get_environment_params, template)
+        self.assertEqual(template.render(queryset=Site.objects.all(), user=self.user), '1 x')
+        response = template.render_to_response(queryset=Site.objects.all(), user=self.user)
+        self.assertEqual(response.content, b'1 x')
+
+    def test_render_override_without_user(self):
+        template = ExportTemplate(name='Template 1', template_code='')
+
+        def render(self, context=None, queryset=None):
+            return 'rendered'
+
+        template.render = MethodType(render, template)
+        response = template.render_to_response(queryset=Site.objects.all(), user=self.user)
+        self.assertEqual(response.content, b'rendered')
+
+    @override_settings(TEMPLATE_RENDERING='legacy')
+    def test_unrelated_restricted_attribute(self):
+        """
+        Only RestrictedRenderingMixin's restricted field opts an object into restricted rendering.
+        """
+        class Thing(TemplateRenderingModeMixin):
+            template_rendering_feature = 'export_templates'
+            restricted = True
+
+        self.assertFalse(Thing().uses_restricted_rendering())
+        self.assertTrue(ExportTemplate(restricted=True).uses_restricted_rendering())
+
+
 class RenderTemplateMixinResponseTestCase(TestCase):
     """
     Tests for RenderTemplateMixin.render_to_response() HTTP behavior.

+ 18 - 4
netbox/utilities/jinja2.py

@@ -14,7 +14,7 @@ from jinja2.environment import TemplateModule
 from jinja2.exceptions import TemplateSyntaxError
 from jinja2.filters import _GroupTuple
 from jinja2.meta import find_referenced_templates
-from jinja2.runtime import BlockReference, LoopContext, Macro, TemplateReference, Undefined
+from jinja2.runtime import BlockReference, LoopContext, Macro, StrictUndefined, TemplateReference, Undefined
 from jinja2.sandbox import SandboxedEnvironment, SecurityError
 from jinja2.utils import Cycler, Joiner, Namespace
 from markupsafe import Markup
@@ -25,6 +25,8 @@ from netbox.constants import TEMPLATE_RENDERING_DEFAULT, TEMPLATE_RENDERING_FEAT
 from netbox.registry import registry
 from utilities.template_objects import (
     NATIVE_VALUE_TYPES,
+    ChoiceValue,
+    RelatedObjectList,
     TemplateObject,
     TemplateObjectList,
     get_query_function,
@@ -124,7 +126,7 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
         ReturnDict, ReturnList,  # Serializer output
         Markup, _GroupTuple,  # Escaped strings and groupby() results
         *NATIVE_VALUE_TYPES,  # IP addresses, dates and times
-        TemplateObject, TemplateObjectList,
+        TemplateObject, TemplateObjectList, ChoiceValue, RelatedObjectList,
     )
     # Jinja's own template objects, matched including subclasses (e.g. StrictUndefined)
     allowed_template_types = (
@@ -156,6 +158,8 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
         return self.is_allowed(getattr(obj, '__self__', obj))
 
     def getattr(self, obj, attribute):
+        if obj is None:
+            return self.none_undefined(attribute)
         if type(obj) in self.item_only_types:
             return super().getitem(obj, attribute)
         if not self.is_allowed(obj):
@@ -163,10 +167,18 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
         return super().getattr(obj, attribute)
 
     def getitem(self, obj, argument):
+        if obj is None:
+            return self.none_undefined(argument)
         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)
 
+    def none_undefined(self, name):
+        # An attribute of None (e.g. object.tenant.name for a null tenant) renders empty, as in legacy mode, even where
+        # undefined names and attributes are otherwise strict
+        undefined = Undefined if self.undefined is StrictUndefined else self.undefined
+        return undefined(obj=None, name=name)
+
     def unsafe_undefined(self, obj, attribute):
         # Fail rather than rendering an empty string
         raise SecurityError(f"Access to attribute {attribute!r} of {type(obj).__name__!r} object is not permitted.")
@@ -226,14 +238,16 @@ def render_jinja2(template_code, context, environment_params=None, data_file=Non
     The optional `filters` argument is a mapping of additional Jinja2 filters to make available for this render only
     (e.g. context-specific sanitization filters). These take precedence over the default and user-configured filters.
 
-    Pass a RestrictedRenderState as `restricted` to render in the restricted environment. If it has a user, the
-    query() function is available.
+    Pass a RestrictedRenderState as `restricted` to render in the restricted environment, which uses StrictUndefined
+    unless `environment_params` sets `undefined`. If the state has a user, the query() function is available.
     """
     if restricted is not None and not isinstance(restricted, RestrictedRenderState):
         raise TypeError(f"restricted must be a RestrictedRenderState or None (found {type(restricted).__name__})")
     environment_params = dict(environment_params or {})
     if restricted is not None:
         environment_params.pop('finalize', None)
+        # Fail on undefined names and attributes (e.g. a misspelled field) rather than rendering an empty string
+        environment_params.setdefault('undefined', StrictUndefined)
 
     if debug:
         extensions = list(environment_params.get('extensions', []))

+ 57 - 2
netbox/utilities/template_objects.py

@@ -19,7 +19,7 @@ from rest_framework.relations import PKOnlyObject
 from rest_framework.serializers import Serializer
 
 from netbox.api.exceptions import SerializerNotFound
-from netbox.api.fields import RelatedObjectsField
+from netbox.api.fields import ChoiceField, RelatedObjectsField
 from netbox.api.filters import OrderingFilter
 from netbox.api.gfk_fields import GFKSerializerField
 from netbox.models.features import model_is_public
@@ -37,6 +37,8 @@ from utilities.json import render_native_values
 
 __all__ = (
     'NATIVE_VALUE_TYPES',
+    'ChoiceValue',
+    'RelatedObjectList',
     'TemplateObject',
     'TemplateObjectList',
     'get_query_function',
@@ -59,6 +61,9 @@ TEMPLATE_OBJECTS_CHUNK_SIZE = 1000
 # The related objects represented by each model's serializer (see _get_relations()), keyed by model
 _relations = {}
 
+# The names of the choice fields of each model's serializer (see _get_choice_fields()), keyed by model
+_choice_fields = {}
+
 # Marks a field holding generic object references ({object_type, object_id, object}), e.g. cable terminations
 _GENERIC_OBJECTS = object()
 
@@ -145,6 +150,41 @@ def template_json_default(obj):
     raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
 
 
+class ChoiceValue(dict):
+    """
+    The {value, label} representation of a choice field, which renders and compares as its value (e.g. so that
+    {{ x.status }} renders "active" and x.status == 'active' is true).
+    """
+    def __str__(self):
+        return str(self.get('value'))
+
+    def __eq__(self, other):
+        if isinstance(other, Mapping):
+            return super().__eq__(other)
+        return self.get('value') == other
+
+    def __ne__(self, other):
+        return not self == other
+
+    __hash__ = None
+
+
+class RelatedObjectList(list):
+    """
+    A list of related objects (e.g. an object's tags), which provides the all(), count() and first() methods of a
+    TemplateObjectList.
+    """
+    def all(self):
+        return self
+
+    def count(self, *args):
+        # Without arguments, the number of objects, as for a TemplateObjectList (rather than list.count())
+        return super().count(*args) if args else len(self)
+
+    def first(self):
+        return self[0] if self else None
+
+
 class TemplateObject(Mapping):
     """
     A read-only representation of a NetBox object for restricted template rendering. Behaves as a dict holding the
@@ -172,6 +212,8 @@ class TemplateObject(Mapping):
                 return value
         if key not in _get_relations(self._model) and isinstance(value, (dict, list)):
             # Return a copy, so that a template can't alter the retained representation
+            if isinstance(value, dict) and key in _get_choice_fields(self._model):
+                return ChoiceValue(deepcopy(value))
             return deepcopy(value)
         self._wrapped[key] = self._wrap(key, value)
         return self._wrapped[key]
@@ -243,7 +285,7 @@ class TemplateObject(Mapping):
         else:
             model = relation
         if model is not None and isinstance(value, list):
-            return [self._wrap_object(item, model) for item in value]
+            return RelatedObjectList(self._wrap_object(item, model) for item in value)
         if model is not None and isinstance(value, dict):
             return self._wrap_object(value, model)
         return deepcopy(value)
@@ -727,6 +769,19 @@ def _get_relations(model):
     return relations
 
 
+def _get_choice_fields(model):
+    """
+    Return the names of the serializer fields which represent choices (as {value, label}).
+    """
+    if model not in _choice_fields:
+        serializer_class = _get_serializer_class(model)
+        _choice_fields[model] = frozenset(
+            name for name, field in getattr(serializer_class, '_declared_fields', {}).items()
+            if isinstance(field, ChoiceField)
+        )
+    return _choice_fields[model]
+
+
 def _find_related_objects(model, data, found):
     """
     Add the primary keys of the related objects represented within an object's (possibly partial) representation to

+ 28 - 1
netbox/utilities/tests/test_jinja2.py

@@ -1,7 +1,7 @@
 from decimal import Decimal
 
 from django.test import SimpleTestCase, TestCase, override_settings
-from jinja2 import ChainableUndefined, StrictUndefined, UndefinedError
+from jinja2 import ChainableUndefined, StrictUndefined, Undefined, UndefinedError
 from jinja2.sandbox import SecurityError
 from rest_framework.utils.serializer_helpers import ReturnDict
 
@@ -144,6 +144,33 @@ class RestrictedSandboxedEnvironmentTest(TestCase):
     def test_undefined(self):
         with self.assertRaises(UndefinedError):
             render('{{ missing.attr }}')
+        # Undefined names and attributes fail by default
+        for template_code, context in (
+            ('{{ missing }}', {}),
+            ('{{ data.missing }}', {'data': {'name': 'x'}}),
+            ('{% if data.missing %}x{% endif %}', {'data': {'name': 'x'}}),
+        ):
+            with self.subTest(template_code=template_code):
+                with self.assertRaises(UndefinedError):
+                    render(template_code, **context)
+        # Except where tested for, and for attributes of None (as in legacy mode)
+        for template_code, expected in (
+            ('{{ data.missing is defined }}', 'False'),
+            ('{{ data.missing | default("x") }}', 'x'),
+            ('{{ data.tenant.name }}', ''),
+            ('{{ data.tenant["name"] }}', ''),
+            ('{% if data.tenant.name %}x{% endif %}', ''),
+        ):
+            with self.subTest(template_code=template_code):
+                self.assertEqual(render(template_code, data={'name': 'x', 'tenant': None}), expected)
+        # Unless the environment parameters set the undefined type
+        self.assertEqual(
+            render_jinja2(
+                '{{ missing }}', {}, environment_params={'undefined': Undefined}, restricted=RestrictedRenderState()
+            ),
+            ''
+        )
+        self.assertEqual(render_jinja2('{{ missing }}', {}), '')
         with self.assertRaises(UndefinedError):
             render_jinja2(
                 '{{ missing }}',

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

@@ -15,7 +15,7 @@ from jinja2.sandbox import SecurityError
 from core.models import ObjectType
 from dcim.models import Cable, Device, Interface, Location, Site
 from extras.choices import CustomFieldTypeChoices
-from extras.models import CustomField, SavedFilter
+from extras.models import CustomField, SavedFilter, Tag
 from ipam.models import VLAN, IPAddress
 from tenancy.models import Tenant, TenantGroup
 from users.models import ObjectPermission, User
@@ -81,6 +81,45 @@ class TemplateObjectTest(TestCase):
             with self.subTest(template_code=template_code):
                 self.assertEqual(self.render(template_code, object=self.device), expected)
 
+    def test_choice_fields(self):
+        """
+        A choice field renders and compares as its value.
+        """
+        self.device.primary_ip4 = self.ip_address
+        self.device.save()
+        cases = (
+            ('{{ object.status }}', 'active'),
+            ('{{ object.status == "active" }} {{ object.status != "active" }}', 'True False'),
+            ('{{ "active" == object.status }} {{ object.status in ["planned", "active"] }}', 'True True'),
+            ('{{ object.status.value }}/{{ object.status.label }}', 'active/Active'),
+            ('{{ object.status | upper }}', 'ACTIVE'),
+            ('{{ object.status | tojson }}', '{"label": "Active", "value": "active"}'),
+            ('{{ object.status == {"value": "active", "label": "Active"} }}', 'True'),
+            # In a related object's brief representation
+            ('{{ object.primary_ip4.family }} {{ object.primary_ip4.family == 4 }}', '4 True'),
+            ('{{ object.get("status") }}', 'active'),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                self.assertEqual(self.render(template_code, object=self.device), expected)
+
+    def test_related_object_lists(self):
+        """
+        A list of related objects provides all(), count() and first(), as a reverse relation does.
+        """
+        tags = (Tag.objects.create(name='Tag 1', slug='tag-1'), Tag.objects.create(name='Tag 2', slug='tag-2'))
+        self.device.tags.set(tags)
+        cases = (
+            ('{% for t in object.tags.all() %}{{ t.slug }} {% endfor %}', 'tag-1 tag-2 '),
+            ('{{ object.tags.count() }} {{ object.tags | length }}', '2 2'),
+            ('{{ object.tags.first().name }}', 'Tag 1'),
+            ('{{ object.tags.count(object.tags.first()) }}', '1'),
+            ('{{ object.interfaces.first().tags.first() }}', 'None'),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                self.assertEqual(self.render(template_code, object=self.device), expected)
+
     def test_native_values(self):
         """
         IP addresses, dates and times are native objects, whose attributes and methods are available.