浏览代码

Closes #23875: Add an object proxy for restricted rendering

Add TemplateObject and TemplateObjectList, which represent NetBox
objects in restricted template rendering as their REST API
representations. Related objects not fully represented are fetched on
demand, and reverse relations are exposed as lazy lists, both limited
to the objects the rendering user is permitted to view. Lists are
serialized in a single batch using the REST API's prefetches.
Jeremy Stretch 23 小时之前
父节点
当前提交
0b3533c862
共有 3 个文件被更改,包括 688 次插入 和 0 次删除
  1. 3 0
      netbox/utilities/jinja2.py
  2. 398 0
      netbox/utilities/template_objects.py
  3. 287 0
      netbox/utilities/tests/test_template_objects.py

+ 3 - 0
netbox/utilities/jinja2.py

@@ -22,6 +22,7 @@ from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
 from netbox.config import get_config
 from netbox.constants import TEMPLATE_RENDERING_DEFAULT, TEMPLATE_RENDERING_FEATURES
 from netbox.registry import registry
+from utilities.template_objects import TemplateObject, TemplateObjectList, template_json_default
 
 __all__ = (
     'DEFAULT_JINJA2_FILTERS',
@@ -115,6 +116,7 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
         dict, list, tuple, str, int, float, Decimal, bool, type(None), range,
         ReturnDict, ReturnList,  # Serializer output
         Markup, _GroupTuple,  # Escaped strings and groupby() results
+        TemplateObject, TemplateObjectList,
     )
     # Jinja's own template objects, matched including subclasses (e.g. StrictUndefined)
     allowed_template_types = (
@@ -125,6 +127,7 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
         super().__init__(*args, **kwargs)
         # Jinja's built-in globals (range, dict, namespace, etc.) are the only functions and classes which may be called
         self.allowed_callables = tuple(self.globals.values())
+        self.policies['json.dumps_kwargs'] = {'sort_keys': True, 'default': template_json_default}
 
     def is_allowed(self, obj):
         return type(obj) in self.allowed_types or isinstance(obj, self.allowed_template_types)

+ 398 - 0
netbox/utilities/template_objects.py

@@ -0,0 +1,398 @@
+from collections.abc import Mapping
+from copy import deepcopy
+from decimal import Decimal
+
+from django.apps import apps
+from django.core.exceptions import FieldDoesNotExist
+
+__all__ = (
+    'TemplateObject',
+    'TemplateObjectList',
+    'get_template_object',
+    'get_template_objects',
+    'template_json_default',
+)
+
+# The related objects represented by each model's serializer (see _get_relations()), keyed by model
+_relations = {}
+
+# Marks a field holding generic object references ({object_type, object_id, object}), e.g. cable terminations
+_GENERIC_OBJECTS = object()
+
+
+def get_template_object(instance, state):
+    """
+    Return a TemplateObject representing the given instance. The caller is responsible for ensuring that the rendering
+    user is permitted to view it.
+    """
+    _check_state(state)
+    model = type(instance)
+    if (serializer_class := _get_serializer_class(model)) is None:
+        raise ValueError(f"{model._meta.label} has no REST API serializer.")
+    from utilities.api import _get_base_queryset
+
+    # Reload the object from the REST API viewset's queryset, which may annotate fields the serializer renders
+    queryset = _prepare_queryset(_get_base_queryset(model).filter(pk=instance.pk), serializer_class)
+    data = _serialize(serializer_class, queryset.first() or instance)
+    state.cache[(model, instance.pk)] = data
+    return TemplateObject(data, model, state, full=True)
+
+
+def get_template_objects(queryset, state):
+    """
+    Return a lazy TemplateObjectList representing the objects in the given queryset which the rendering user is
+    permitted to view.
+    """
+    _check_state(state)
+    if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
+        raise ValueError(f"{queryset.model._meta.label} does not support restricted rendering.")
+    return TemplateObjectList(queryset, state)
+
+
+def template_json_default(obj):
+    """
+    JSON encoder hook for restricted rendering: TemplateObjects serialize to their full representation.
+    """
+    if isinstance(obj, TemplateObject):
+        return obj._get_full_data()
+    if isinstance(obj, TemplateObjectList):
+        return [item._get_full_data() for item in obj]
+    if isinstance(obj, Decimal):
+        return float(obj)
+    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
+
+
+class TemplateObject(Mapping):
+    """
+    A read-only representation of a NetBox object for restricted template rendering. Behaves as a dict holding the
+    object's REST API representation. Related objects not fully represented are fetched on demand, limited to those
+    the rendering user is permitted to view.
+    """
+    def __init__(self, data, model, state, full=False):
+        self._data = data
+        self._model = model
+        self._state = state
+        self._full = full
+        self._wrapped = {}
+
+    def __getitem__(self, key):
+        if key in self._wrapped:
+            return self._wrapped[key]
+        if key not in self._data:
+            if (relation := self._get_reverse_relation(key)) is not None:
+                self._wrapped[key] = TemplateObjectList(relation, self._state)
+                return self._wrapped[key]
+            self._resolve()
+        value = self._data[key]
+        if key not in _get_relations(self._model) and isinstance(value, (dict, list)):
+            # Return a copy, so that a template can't alter the cached representation
+            return deepcopy(value)
+        self._wrapped[key] = self._wrap(key, value)
+        return self._wrapped[key]
+
+    def __iter__(self):
+        self._resolve()
+        return iter(self._data)
+
+    def __len__(self):
+        self._resolve()
+        return len(self._data)
+
+    def __bool__(self):
+        # Always represents an object, so avoid resolving it (via __len__) just to test truthiness
+        return True
+
+    def __eq__(self, other):
+        if isinstance(other, TemplateObject):
+            return (self._model, self._data.get('id')) == (other._model, other._data.get('id'))
+        return NotImplemented
+
+    def __hash__(self):
+        return hash((self._model, self._data.get('id')))
+
+    def __str__(self):
+        return str(self._data.get('display', ''))
+
+    def __repr__(self):
+        return f'<TemplateObject {self._data.get("display", "")!r}>'
+
+    def _get_full_data(self):
+        self._resolve()
+        return self._data
+
+    def _resolve(self):
+        """
+        Replace a brief representation with the full one, if the rendering user is permitted to view the object.
+        """
+        if self._full or self._model is None or self._data.get('id') is None:
+            return
+        self._full = True
+        key = (self._model, self._data['id'])
+        cache = self._state.cache
+        if key not in cache:
+            cache[key] = _fetch_full_data(self._model, self._data['id'], self._state.user)
+        if cache[key] is not None:
+            self._data = cache[key]
+            self._wrapped = {}
+
+    def _get_reverse_relation(self, key):
+        """
+        Return a queryset of the related objects for an optional reverse relation (e.g. a device's interfaces).
+        """
+        if self._model is None or self._data.get('id') is None:
+            return None
+        from netbox.api.fields import RelatedObjectsField
+
+        serializer_class = _get_serializer_class(self._model)
+        if serializer_class is None or key not in getattr(serializer_class.Meta, 'optional_fields', ()):
+            return None
+        field = serializer_class._declared_fields.get(key)
+        if not isinstance(field, RelatedObjectsField):
+            return None
+        queryset = _get_related_objects(self._model, self._data['id'], field.relation)
+        if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
+            return None
+        return queryset
+
+    def _wrap(self, key, value):
+        relation = _get_relations(self._model).get(key)
+        if relation is None or value is None:
+            return deepcopy(value)
+        if relation is _GENERIC_OBJECTS:
+            if isinstance(value, list):
+                return [self._wrap_generic_object(item) for item in value]
+            return deepcopy(value)
+        if isinstance(relation, str):
+            # A generic foreign key: the related model is given by its content type field
+            model = _get_model(self._data.get(relation))
+        else:
+            model = relation
+        if model is not None and isinstance(value, list):
+            return [TemplateObject(item, model, self._state) for item in value]
+        if model is not None and isinstance(value, dict):
+            return TemplateObject(value, model, self._state)
+        return deepcopy(value)
+
+    def _wrap_generic_object(self, item):
+        if not isinstance(item, dict) or not isinstance(item.get('object'), dict):
+            return deepcopy(item)
+        if (model := _get_model(item.get('object_type'))) is None:
+            return deepcopy(item)
+        return {**deepcopy(item), 'object': TemplateObject(item['object'], model, self._state)}
+
+
+class TemplateObjectList:
+    """
+    A lazy, read-only list of TemplateObjects, limited to the objects the rendering user is permitted to view.
+    """
+    def __init__(self, queryset, state):
+        self._queryset = queryset.restrict(state.user, 'view')
+        self._state = state
+        self._items = None
+        self._first = None
+
+    def __iter__(self):
+        return iter(self._get_items())
+
+    def __len__(self):
+        return len(self._get_items())
+
+    def __bool__(self):
+        if self._items is None:
+            return self._queryset.exists()
+        return bool(self._items)
+
+    def __getitem__(self, index):
+        # Serialize only the objects a slice needs (e.g. interfaces[:5]), unless the list is already loaded
+        if self._items is None and isinstance(index, slice):
+            start, stop = index.start or 0, index.stop
+            if index.step in (None, 1) and stop is not None and start >= 0 and stop >= 0:
+                return _serialize_queryset(self._queryset, self._state, limit=stop)[start:]
+        return self._get_items()[index]
+
+    def __repr__(self):
+        return f'<TemplateObjectList {self._queryset.model._meta.label}>'
+
+    def all(self):
+        return self
+
+    def count(self):
+        if self._items is None:
+            return self._queryset.count()
+        return len(self._items)
+
+    def first(self):
+        if self._items is None:
+            if self._first is None:
+                self._first = _serialize_queryset(self._queryset, self._state, limit=1)
+            return self._first[0] if self._first else None
+        return self._items[0] if self._items else None
+
+    def _get_items(self):
+        if self._items is None:
+            self._items = _serialize_queryset(self._queryset, self._state)
+        return self._items
+
+
+#
+# Helpers
+#
+
+def _check_state(state):
+    if state.user is None:
+        raise ValueError("Restricted rendering of NetBox objects requires a user.")
+
+
+def _get_serializer_class(model):
+    from netbox.api.exceptions import SerializerNotFound
+    from utilities.api import get_serializer_for_model
+
+    if model is None:
+        return None
+    try:
+        return get_serializer_for_model(model)
+    except SerializerNotFound:
+        return None
+
+
+def _get_model(label):
+    if not isinstance(label, str):
+        return None
+    try:
+        return apps.get_model(label)
+    except (LookupError, ValueError):
+        return None
+
+
+def _get_related_objects(model, pk, relation):
+    """
+    Return a queryset of the objects related to an object through a reverse relation, a many-to-many field, or a
+    GenericRelation.
+    """
+    from django.contrib.contenttypes.fields import GenericRelation
+    from django.contrib.contenttypes.models import ContentType
+
+    from utilities.api import _get_base_queryset
+
+    field = getattr(model, relation).field
+    if isinstance(field, GenericRelation):
+        return _get_base_queryset(field.related_model).filter(**{
+            field.content_type_field_name: ContentType.objects.get_for_model(model),
+            field.object_id_field_name: pk,
+        })
+    if field.model is model and field.many_to_many:
+        # A many-to-many field declared on this model
+        return _get_base_queryset(field.related_model).filter(**{field.related_query_name(): pk})
+    return _get_base_queryset(field.model).filter(**{field.name: pk})
+
+
+def _get_relations(model):
+    """
+    Return the related models of the serializer fields which represent related objects, keyed by field name. A generic
+    foreign key maps to the name of its content type field.
+    """
+    if model in _relations:
+        return _relations[model]
+    from django.contrib.contenttypes.fields import GenericForeignKey
+
+    from netbox.api.gfk_fields import GFKSerializerField
+    from netbox.api.serializers.generic import GenericObjectSerializer
+    from utilities.api import _get_nested_serializer
+
+    relations = {}
+    if serializer_class := _get_serializer_class(model):
+        for name, field in serializer_class._declared_fields.items():
+            if isinstance(field, GFKSerializerField):
+                try:
+                    model_field = model._meta.get_field(field.source or name)
+                except FieldDoesNotExist:
+                    continue
+                if isinstance(model_field, GenericForeignKey):
+                    relations[name] = model_field.ct_field
+            elif isinstance(getattr(field, 'child', field), GenericObjectSerializer):
+                relations[name] = _GENERIC_OBJECTS
+            elif nested_serializer := _get_nested_serializer(field):
+                relations[name] = type(nested_serializer).Meta.model
+    _relations[model] = relations
+    return relations
+
+
+def _prepare_queryset(queryset, serializer_class):
+    """
+    Apply the prefetches and annotations which the REST API uses to serialize the given objects.
+    """
+    from utilities.api import (
+        _get_declared_prefetches,
+        get_annotations_for_serializer,
+        get_fields_for_serializer,
+        get_prefetches_for_serializer,
+    )
+
+    model = queryset.model
+    fields = set(get_fields_for_serializer(serializer_class))
+    annotations = get_annotations_for_serializer(serializer_class)
+    if 'config_context' in fields and hasattr(queryset, 'get_config_context_data_expression'):
+        annotations['config_context_data'] = queryset.get_config_context_data_expression(only_invalidated=True)
+    # Skip any annotations the queryset already carries (e.g. counts applied by a list view)
+    if annotations := {
+        name: annotation for name, annotation in annotations.items() if name not in queryset.query.annotations
+    }:
+        queryset = queryset.annotate(**annotations)
+    if prefetches := [*_get_declared_prefetches(model, fields), *get_prefetches_for_serializer(serializer_class)]:
+        queryset = queryset.prefetch_related(*prefetches)
+    return queryset
+
+
+def _fetch_full_data(model, pk, user):
+    """
+    Return the full representation of an object, or None if the user may not view it.
+    """
+    from utilities.api import _get_base_queryset
+
+    serializer_class = _get_serializer_class(model)
+    # Start from the REST API viewset's queryset, which may annotate fields the serializer renders
+    queryset = _get_base_queryset(model).all()
+    if serializer_class is None or not hasattr(queryset, 'restrict'):
+        return None
+    queryset = _prepare_queryset(queryset.restrict(user, 'view').filter(pk=pk), serializer_class)
+    if (instance := queryset.first()) is None:
+        return None
+    return _serialize(serializer_class, instance)
+
+
+def _serialize_queryset(queryset, state, limit=None):
+    """
+    Serialize the objects in a queryset in one batch, returning a list of full TemplateObjects.
+    """
+    model = queryset.model
+    if (serializer_class := _get_serializer_class(model)) is None:
+        return []
+    queryset = _prepare_queryset(queryset, serializer_class)
+    if limit is not None:
+        # Order an unordered queryset, so that the objects returned are deterministic
+        queryset = queryset[:limit] if queryset.ordered else queryset.order_by('pk')[:limit]
+    items = []
+    for data in _serialize(serializer_class, list(queryset), many=True):
+        key = (model, data['id'])
+        if state.cache.get(key) is None:
+            state.cache[key] = data
+        items.append(TemplateObject(state.cache[key], model, state, full=True))
+    return items
+
+
+def _serialize(serializer_class, instance, many=False):
+    return _to_plain_data(serializer_class(instance, many=many, context={'request': None}).data)
+
+
+def _to_plain_data(value):
+    """
+    Convert serializer output to plain dicts, lists, strings, numbers, booleans, and None.
+    """
+    if isinstance(value, dict):
+        return {key: _to_plain_data(item) for key, item in value.items()}
+    if isinstance(value, (list, tuple)):
+        return [_to_plain_data(item) for item in value]
+    if value is None or type(value) in (str, int, float, Decimal, bool):
+        return value
+    # Anything else (e.g. a lazy translation string) is represented by its string value
+    return str(value)

+ 287 - 0
netbox/utilities/tests/test_template_objects.py

@@ -0,0 +1,287 @@
+import json
+
+from django.contrib.contenttypes.models import ContentType
+from django.db import connection
+from django.test import TestCase
+from django.test.utils import CaptureQueriesContext
+from jinja2 import UndefinedError
+from jinja2.sandbox import SecurityError
+
+from core.models import ObjectType
+from dcim.models import Cable, Device, Interface, Location, Site
+from ipam.models import IPAddress
+from tenancy.models import Tenant, TenantGroup
+from users.models import ObjectPermission, User
+from utilities.jinja2 import RestrictedRenderState, render_jinja2
+from utilities.template_objects import get_template_object, get_template_objects
+from utilities.testing import create_test_device
+
+
+def grant_view(user, model, constraints=None):
+    permission = ObjectPermission.objects.create(
+        name=f'View {model._meta.model_name}', actions=['view'], constraints=constraints
+    )
+    permission.users.add(user)
+    permission.object_types.add(ObjectType.objects.get_for_model(model))
+
+
+class TemplateObjectTest(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        tenant_group = TenantGroup.objects.create(name='Tenant Group 1', slug='corp')
+        cls.tenant = Tenant.objects.create(name='Tenant 1', slug='tenant-1', group=tenant_group)
+        cls.device = create_test_device('Device 1', tenant=cls.tenant)
+        interfaces = (
+            Interface(device=cls.device, name='eth0', type='1000base-t', mtu=1500),
+            Interface(device=cls.device, name='eth1', type='1000base-t', mtu=9000),
+        )
+        Interface.objects.bulk_create(interfaces)
+        cls.ip_address = IPAddress.objects.create(address='192.0.2.1/24', assigned_object=interfaces[0])
+        cls.superuser = User.objects.create_user(username='superuser', is_superuser=True)
+
+    def render(self, template_code, user=None, **objects):
+        state = RestrictedRenderState(user or self.superuser)
+        context = {name: get_template_object(obj, state) for name, obj in objects.items()}
+        return render_jinja2(template_code, context, restricted=state)
+
+    def test_fields(self):
+        cases = (
+            ('{{ object.name }}', 'Device 1'),
+            ('{{ object.status.value }}/{{ object.status.label }}', 'active/Active'),
+            ('{{ object.site.slug }}', 'site-1'),
+            ('{{ object.site }}', 'Site 1'),
+            ('{{ object.custom_fields }}', '{}'),
+            ('{{ object.missing is defined }}', 'False'),
+            ('{{ object.get("name") }}', 'Device 1'),
+            ('{{ "name" in object }}', 'True'),
+            ('{{ object.site == object.site }}', 'True'),
+        )
+        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_urls(self):
+        site = self.device.site
+        tenant_group = self.tenant.group
+        cases = (
+            ('{{ object.url }}', f'/api/dcim/devices/{self.device.pk}/'),
+            ('{{ object.display_url }}', f'/dcim/devices/{self.device.pk}/'),
+            ('{{ object.site.url }}', f'/api/dcim/sites/{site.pk}/'),
+            ('{{ object.tenant.group.display_url }}', f'/tenancy/tenant-groups/{tenant_group.pk}/'),
+            ('{{ object.interfaces.first().url }}', f'/api/dcim/interfaces/{self.ip_address.assigned_object_id}/'),
+            ('{{ object.interfaces.first().ip_addresses.first().assigned_object.url }}',
+             f'/api/dcim/interfaces/{self.ip_address.assigned_object_id}/'),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                self.assertEqual(self.render(template_code, object=self.device), expected)
+        self.assertEqual(
+            type(get_template_object(self.device, RestrictedRenderState(self.superuser))['url']), str
+        )
+
+    def test_related_objects_resolve_lazily(self):
+        self.assertEqual(self.render('{{ object.tenant.group.slug }}', object=self.device), 'corp')
+
+    def test_values_are_read_only(self):
+        output = self.render(
+            '{{ object.custom_fields.update({"a": 1}) }}{{ object.custom_fields }} {{ object | tojson }}',
+            object=self.device,
+        )
+        self.assertTrue(output.startswith('None{} '))
+        self.assertEqual(json.loads(output[len('None{} '):])['custom_fields'], {})
+
+    def test_truthiness_does_not_fetch(self):
+        state = RestrictedRenderState(self.superuser)
+        context = {'object': get_template_object(self.device, state)}
+        with CaptureQueriesContext(connection) as queries:
+            output = render_jinja2(
+                '{% if object.tenant %}{{ object.tenant.name }}{% endif %}', context, restricted=state
+            )
+        self.assertEqual(output, 'Tenant 1')
+        self.assertEqual(len(queries), 0)
+
+    def test_generic_object_references(self):
+        device = create_test_device('Device 2')
+        interface = Interface.objects.create(device=device, name='eth0', type='1000base-t', mtu=1400)
+        cable = Cable(a_terminations=[self.ip_address.assigned_object], b_terminations=[interface])
+        cable.save()
+        self.assertEqual(
+            self.render(
+                '{{ cable.a_terminations[0].object.mtu }} {{ cable.b_terminations[0].object.device.name }}',
+                cable=cable,
+            ),
+            '1500 Device 2'
+        )
+
+        # A template can't alter the cached representation through a wrapped reference
+        output = self.render('{{ cable.a_terminations[0].update({"x": 1}) }}{{ cable | tojson }}', cable=cable)
+        self.assertNotIn('x', json.loads(output.removeprefix('None'))['a_terminations'][0])
+
+    def test_unsupported_models(self):
+        state = RestrictedRenderState(self.superuser)
+        with self.assertRaises(ValueError):
+            get_template_object(ContentType.objects.first(), state)
+        with self.assertRaises(ValueError):
+            get_template_objects(ContentType.objects.all(), state)
+
+    def test_related_objects_are_cached(self):
+        state = RestrictedRenderState(self.superuser)
+        context = {'object': get_template_object(self.device, state)}
+        render_jinja2('{{ object.tenant.group.slug }}', context, restricted=state)
+        with CaptureQueriesContext(connection) as queries:
+            output = render_jinja2('{{ object.tenant.group.slug }}', context, restricted=state)
+        self.assertEqual(output, 'corp')
+        self.assertEqual(len(queries), 0)
+
+    def test_related_objects_are_restricted(self):
+        user = User.objects.create_user(username='user')
+        grant_view(user, Tenant, {'slug': 'other'})
+        grant_view(user, TenantGroup)
+
+        # 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.group is defined }}', user=user, object=self.device), 'False')
+        with self.assertRaises(UndefinedError):
+            self.render('{{ object.tenant.group.slug }}', user=user, object=self.device)
+
+        grant_view(user, Tenant)
+        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')
+
+    def test_viewset_annotations(self):
+        location = Location.objects.create(name='Location 1', slug='location-1', site=self.device.site)
+        Device.objects.filter(pk=self.device.pk).update(location=location)
+        self.device.refresh_from_db()
+        self.assertEqual(
+            self.render(
+                '{{ object.location.device_count }} {{ object.site.locations.first().device_count }}',
+                object=self.device,
+            ),
+            '1 1'
+        )
+        self.assertEqual(self.render('{{ object.device_count }}', object=location), '1')
+
+    def test_generic_foreign_key(self):
+        self.assertEqual(self.render('{{ ip.assigned_object.device.name }}', ip=self.ip_address), 'Device 1')
+
+    def test_reverse_relations(self):
+        cases = (
+            ('{% for i in object.interfaces %}{{ i.name }}:{{ i.mtu }} {% endfor %}', 'eth0:1500 eth1:9000 '),
+            ('{% for i in object.interfaces.all() %}{{ i.name }} {% endfor %}', 'eth0 eth1 '),
+            ('{{ object.interfaces | length }}', '2'),
+            ('{{ object.interfaces.count() }}', '2'),
+            ('{{ object.interfaces.first().name }}', 'eth0'),
+            ('{{ object.interfaces[1].name }}', 'eth1'),
+            ('{{ object.interfaces | map(attribute="name") | join(",") }}', 'eth0,eth1'),
+            ('{{ object.interfaces.first().ip_addresses.first().address }}', '192.0.2.1/24'),
+            ('{{ object.console_ports.first() is none }}', 'True'),
+        )
+        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_reverse_relation_slices(self):
+        cases = (
+            ('{{ object.interfaces[:1] | map(attribute="name") | join(",") }}', 'eth0'),
+            ('{{ object.interfaces[1:2] | map(attribute="name") | join(",") }}', 'eth1'),
+            ('{{ object.interfaces[-1:] | map(attribute="name") | join(",") }}', 'eth1'),
+            ('{{ object.interfaces[::-1] | map(attribute="name") | join(",") }}', 'eth1,eth0'),
+        )
+        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_first_is_cached(self):
+        state = RestrictedRenderState(self.superuser)
+        interfaces = get_template_object(self.device, state)['interfaces']
+        self.assertEqual(interfaces.first()['name'], 'eth0')
+        with CaptureQueriesContext(connection) as queries:
+            self.assertEqual(interfaces.first()['name'], 'eth0')
+        self.assertEqual(len(queries), 0)
+
+    def test_reverse_relations_are_restricted(self):
+        user = User.objects.create_user(username='user')
+        grant_view(user, Interface, {'name': 'eth1'})
+        self.assertEqual(
+            self.render(
+                '{{ object.interfaces | map(attribute="name") | join(",") }} {{ object.interfaces.count() }}',
+                user=user,
+                object=self.device,
+            ),
+            'eth1 1'
+        )
+
+    def test_tojson(self):
+        data = json.loads(self.render('{{ object | tojson }}', object=self.device))
+        self.assertEqual(data['name'], 'Device 1')
+        self.assertEqual(data['site']['slug'], 'site-1')
+
+        # A nested object serializes to its full representation
+        data = json.loads(self.render('{{ object.tenant | tojson }}', object=self.device))
+        self.assertEqual(data['group']['slug'], 'corp')
+
+        data = json.loads(self.render('{{ object.interfaces | tojson }}', object=self.device))
+        self.assertEqual([interface['mtu'] for interface in data], [1500, 9000])
+
+    def test_internals_are_inaccessible(self):
+        for template_code in (
+            '{{ object._model }}',
+            '{{ object._state.user }}',
+            '{{ object.interfaces._queryset }}',
+        ):
+            with self.subTest(template_code=template_code):
+                with self.assertRaises(SecurityError):
+                    self.render(template_code, object=self.device)
+
+    def test_user_required(self):
+        with self.assertRaises(ValueError):
+            get_template_object(self.device, RestrictedRenderState())
+        with self.assertRaises(ValueError):
+            get_template_objects(Device.objects.all(), RestrictedRenderState())
+
+
+class TemplateObjectListTest(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.sites = (
+            Site.objects.create(name='Site 1', slug='site-1'),
+            Site.objects.create(name='Site 2', slug='site-2'),
+        )
+        cls.superuser = User.objects.create_user(username='superuser', is_superuser=True)
+
+    def render(self, template_code, queryset, user=None):
+        state = RestrictedRenderState(user or self.superuser)
+        return render_jinja2(template_code, {'objects': get_template_objects(queryset, state)}, restricted=state)
+
+    def test_objects(self):
+        template_code = '{% for d in objects %}{{ d.name }}/{{ d.site.name }}/{{ d.role.slug }} {% endfor %}'
+        create_test_device('Device 1', site=self.sites[0])
+        create_test_device('Device 2', site=self.sites[1])
+        self.assertEqual(
+            self.render(template_code, Device.objects.order_by('name')),
+            'Device 1/Site 1/device-role-1 Device 2/Site 2/device-role-1 '
+        )
+
+    def test_objects_are_restricted(self):
+        user = User.objects.create_user(username='user')
+        grant_view(user, Site, {'slug': 'site-2'})
+        output = self.render('{{ objects | map(attribute="name") | join(",") }}', Site.objects.all(), user)
+        self.assertEqual(output, 'Site 2')
+
+    def test_batch_serialization(self):
+        """
+        The number of queries does not depend on the number of objects.
+        """
+        template_code = '{% for d in objects %}{{ d.name }}{{ d.site.name }}{{ d.config_context }}{% endfor %}'
+        create_test_device('Device 1', site=self.sites[0])
+        with CaptureQueriesContext(connection) as queries:
+            self.render(template_code, Device.objects.all())
+        query_count = len(queries)
+
+        for i in range(2, 5):
+            create_test_device(f'Device {i}', site=self.sites[i % 2])
+        with CaptureQueriesContext(connection) as queries:
+            self.render(template_code, Device.objects.all())
+        self.assertEqual(len(queries), query_count)