Explorar el Código

Closes #23909: Pass native IP, date and time values to restricted rendering

Restricted templates now receive IP addresses and prefixes as netaddr
objects, and dates and times as native objects, so attributes and
methods such as .netmask and .strftime() work as in legacy mode. These
values are also accepted as query() filter values and rendered by
tojson as in the REST API. Plugin context values and webhook callback
data holding them are now rendered as strings rather than omitted.
Jeremy Stretch hace 10 horas
padre
commit
fe9b5d4b4d

+ 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:
 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.
 * `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`). 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. 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.
 Set a single mode for all features, or a mode per feature. A feature omitted from the dictionary uses the default mode.
 
 

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

@@ -41,7 +41,7 @@ Checking the REST API representation of an object is generally a convenient way
 
 
 ### Restricted Rendering
 ### Restricted Rendering
 
 
-When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for custom links, or a link has restricted rendering enabled, links are rendered in a restricted environment which permits access only to plain data, and the context changes as follows:
+When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for custom links, or a link has restricted rendering enabled, links are rendered in a restricted environment which permits access only to plain data, IP addresses, and dates and times, and the context changes as follows:
 
 
 | Variable  | Description                                                                                                       |
 | Variable  | Description                                                                                                       |
 |-----------|-------------------------------------------------------------------------------------------------------------------|
 |-----------|-------------------------------------------------------------------------------------------------------------------|

+ 1 - 1
docs/customization/export-templates.md

@@ -39,7 +39,7 @@ A MIME type and file extension can optionally be defined for each export templat
 
 
 ## Restricted Rendering
 ## Restricted Rendering
 
 
-When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for export templates, or a template has restricted rendering enabled, templates are rendered in a restricted environment which permits access only to plain data, with the following context:
+When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for export 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, with the following context:
 
 
 | Variable  | Description |
 | Variable  | Description |
 |-----------|-------------|
 |-----------|-------------|

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

@@ -51,7 +51,7 @@ There are {{ dcim.Site.objects.count() }} sites.
 
 
 #### Restricted Rendering
 #### Restricted Rendering
 
 
-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:
+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.
 * `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.
 * Config context data and REST API request data are unchanged.
 * Config context data and REST API request data are unchanged.

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

@@ -117,7 +117,7 @@ The returned dict is merged into the template context, so `my_plugin` becomes av
     `get_jinja_context()` receives no arguments — it has no access to the object being rendered or the caller-supplied context. It is intended for plugin-global namespaces (e.g. a lazily-evaluated query helper). Per-object logic belongs in the template itself or in a custom filter.
     `get_jinja_context()` receives no arguments — it has no access to the object being rendered or the caller-supplied context. It is intended for plugin-global namespaces (e.g. a lazily-evaluated query helper). Per-object logic belongs in the template itself or in a custom filter.
 
 
 !!! note "Restricted rendering"
 !!! note "Restricted rendering"
-    When templates are rendered in [restricted mode](../../configuration/system.md#template_rendering), only values which can be serialized to JSON (e.g. strings, numbers, lists, and dictionaries) are included. Others, such as the namespace object above, are omitted, and a warning is logged.
+    When templates are rendered in [restricted mode](../../configuration/system.md#template_rendering), only values which can be serialized to JSON (e.g. strings, numbers, lists, and dictionaries) are included. Values are converted as if serialized to JSON, so IP addresses and dates are received as strings. Others, such as the namespace object above, are omitted, and a warning is logged.
 
 
 ---
 ---
 
 
@@ -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.
 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. Other values are converted to plain data: for example, dates become ISO 8601 strings.
+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.
 
 
 ```python
 ```python
 from dcim.models import Device
 from dcim.models import Device

+ 2 - 2
netbox/extras/models/mixins.py

@@ -16,7 +16,6 @@ from django.utils.http import content_disposition_header
 from django.utils.module_loading import import_string
 from django.utils.module_loading import import_string
 from django.utils.translation import gettext_lazy as _
 from django.utils.translation import gettext_lazy as _
 from jinja2 import TemplateError
 from jinja2 import TemplateError
-from rest_framework.utils.encoders import JSONEncoder
 
 
 from core.models import ObjectType
 from core.models import ObjectType
 from extras.constants import DEFAULT_MIME_TYPE, JINJA_ENV_PARAMS_ALLOWED, SCRIPT_MODULE_NAME_PREFIX
 from extras.constants import DEFAULT_MIME_TYPE, JINJA_ENV_PARAMS_ALLOWED, SCRIPT_MODULE_NAME_PREFIX
@@ -24,6 +23,7 @@ from extras.utils import filename_from_model, filename_from_object
 from netbox.constants import TEMPLATE_RENDERING_RESTRICTED
 from netbox.constants import TEMPLATE_RENDERING_RESTRICTED
 from netbox.plugins import PluginConfig
 from netbox.plugins import PluginConfig
 from utilities.jinja2 import RestrictedRenderState, get_template_rendering_mode, render_jinja2
 from utilities.jinja2 import RestrictedRenderState, get_template_rendering_mode, render_jinja2
+from utilities.json import APIJSONEncoder
 
 
 __all__ = (
 __all__ = (
     'PythonModuleMixin',
     'PythonModuleMixin',
@@ -214,7 +214,7 @@ class RenderTemplateMixin(TemplateRenderingModeMixin, models.Model):
                 omitted = []
                 omitted = []
                 for key, value in plugin_context.items():
                 for key, value in plugin_context.items():
                     try:
                     try:
-                        _context[key] = json.loads(json.dumps(value, cls=JSONEncoder))
+                        _context[key] = json.loads(json.dumps(value, cls=APIJSONEncoder))
                     except Exception:
                     except Exception:
                         # Besides TypeError, a value can raise anything from its own methods (e.g. a RecursionError)
                         # Besides TypeError, a value can raise anything from its own methods (e.g. a RecursionError)
                         if (app_config.name, key) not in _plugin_context_warned:
                         if (app_config.name, key) not in _plugin_context_warned:

+ 6 - 3
netbox/extras/tests/test_event_rules.py

@@ -2093,7 +2093,10 @@ class WebhookRestrictedRenderingTest(TestCase):
             name='Webhook 1',
             name='Webhook 1',
             payload_url='http://localhost:9000/{{ data.slug }}/',
             payload_url='http://localhost:9000/{{ data.slug }}/',
             additional_headers='X-Object: {{ data.name | header_safe }}',
             additional_headers='X-Object: {{ data.name | header_safe }}',
-            body_template='{{ data.status.label.upper() }} {{ request.GET.q }} {{ context.plugin.foo }}',
+            body_template=(
+                '{{ data.status.label.upper() }} {{ request.GET.q }} '
+                '{{ context.plugin.foo }} {{ context.plugin.prefix }}'
+            ),
         )
         )
         cls.event_rule = EventRule.objects.create(
         cls.event_rule = EventRule.objects.create(
             name='Event Rule 1',
             name='Event Rule 1',
@@ -2137,7 +2140,7 @@ class WebhookRestrictedRenderingTest(TestCase):
 
 
     def assert_send_webhook(self, event_rule):
     def assert_send_webhook(self, event_rule):
         def plain_callback(object_type, event_type, data, request):
         def plain_callback(object_type, event_type, data, request):
-            return {'plugin': {'foo': 'bar'}}
+            return {'plugin': {'foo': 'bar', 'prefix': IPNetwork('192.0.2.0/24')}}
 
 
         def object_callback(object_type, event_type, data, request):
         def object_callback(object_type, event_type, data, request):
             return {'site': Site.objects.first()}
             return {'site': Site.objects.first()}
@@ -2146,7 +2149,7 @@ class WebhookRestrictedRenderingTest(TestCase):
             # Lazy choice labels and the request's query parameters are plain data
             # Lazy choice labels and the request's query parameters are plain data
             self.assertEqual(request.url, 'http://localhost:9000/site-1/')
             self.assertEqual(request.url, 'http://localhost:9000/site-1/')
             self.assertEqual(request.headers['X-Object'], 'Site 1')
             self.assertEqual(request.headers['X-Object'], 'Site 1')
-            self.assertEqual(request.body, b'ACTIVE foo bar')
+            self.assertEqual(request.body, b'ACTIVE foo bar 192.0.2.0/24')
             return HttpResponse()
             return HttpResponse()
 
 
         request = RequestFactory().get('/dcim/sites/', {'q': 'foo'})
         request = RequestFactory().get('/dcim/sites/', {'q': 'foo'})

+ 6 - 0
netbox/extras/tests/test_models.py

@@ -19,6 +19,7 @@ from django.test import TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from django.test.utils import CaptureQueriesContext
 from jinja2 import DebugUndefined, StrictUndefined, TemplateError, TemplateSyntaxError, UndefinedError
 from jinja2 import DebugUndefined, StrictUndefined, TemplateError, TemplateSyntaxError, UndefinedError
 from jinja2.sandbox import SecurityError
 from jinja2.sandbox import SecurityError
+from netaddr import IPNetwork
 from PIL import Image
 from PIL import Image
 from rq.queue import Queue
 from rq.queue import Queue
 
 
@@ -1673,6 +1674,11 @@ class ExportTemplateRestrictedRenderTestCase(TestCase):
             with self.assertNoLogs('extras.models.mixins', level='WARNING'):
             with self.assertNoLogs('extras.models.mixins', level='WARNING'):
                 self.render('{{ name }}')
                 self.render('{{ name }}')
 
 
+    def test_plugin_context_native_values(self):
+        plugin_context = {'network': IPNetwork('192.0.2.0/24')}
+        with patch('netbox.tests.dummy_plugin.DummyPluginConfig.get_jinja_context', return_value=plugin_context):
+            self.assertEqual(self.render('{{ network }}'), '192.0.2.0/24')
+
     @patch('extras.models.mixins._plugin_context_warned', set())
     @patch('extras.models.mixins._plugin_context_warned', set())
     def test_plugin_context_serialization_error(self):
     def test_plugin_context_serialization_error(self):
         class LazyHelper:
         class LazyHelper:

+ 2 - 2
netbox/extras/webhooks.py

@@ -7,10 +7,10 @@ import requests
 from django.conf import settings
 from django.conf import settings
 from django_rq import job
 from django_rq import job
 from jinja2.exceptions import TemplateError
 from jinja2.exceptions import TemplateError
-from rest_framework.utils.encoders import JSONEncoder
 
 
 from netbox.registry import registry
 from netbox.registry import registry
 from netbox.settings_utils import parse_job_timeout
 from netbox.settings_utils import parse_job_timeout
+from utilities.json import APIJSONEncoder
 from utilities.proxy import resolve_proxies
 from utilities.proxy import resolve_proxies
 from utilities.request import get_safe_request_context
 from utilities.request import get_safe_request_context
 from utilities.template_objects import to_template_data
 from utilities.template_objects import to_template_data
@@ -79,7 +79,7 @@ def send_webhook(
                 if restricted:
                 if restricted:
                     # Reduce the data to plain values, as for the default request body
                     # Reduce the data to plain values, as for the default request body
                     try:
                     try:
-                        ret = json.loads(json.dumps(ret, cls=JSONEncoder))
+                        ret = json.loads(json.dumps(ret, cls=APIJSONEncoder))
                     except (TypeError, ValueError) as e:
                     except (TypeError, ValueError) as e:
                         logger.warning(f"Omitting data from callback {callback}, which can't be serialized: {e}")
                         logger.warning(f"Omitting data from callback {callback}, which can't be serialized: {e}")
                         continue
                         continue

+ 2 - 0
netbox/utilities/jinja2.py

@@ -24,6 +24,7 @@ from netbox.config import get_config
 from netbox.constants import TEMPLATE_RENDERING_DEFAULT, TEMPLATE_RENDERING_FEATURES
 from netbox.constants import TEMPLATE_RENDERING_DEFAULT, TEMPLATE_RENDERING_FEATURES
 from netbox.registry import registry
 from netbox.registry import registry
 from utilities.template_objects import (
 from utilities.template_objects import (
+    NATIVE_VALUE_TYPES,
     TemplateObject,
     TemplateObject,
     TemplateObjectList,
     TemplateObjectList,
     get_query_function,
     get_query_function,
@@ -122,6 +123,7 @@ class RestrictedSandboxedEnvironment(SandboxedEnvironment):
         dict, list, tuple, str, int, float, Decimal, bool, type(None), range,
         dict, list, tuple, str, int, float, Decimal, bool, type(None), range,
         ReturnDict, ReturnList,  # Serializer output
         ReturnDict, ReturnList,  # Serializer output
         Markup, _GroupTuple,  # Escaped strings and groupby() results
         Markup, _GroupTuple,  # Escaped strings and groupby() results
+        *NATIVE_VALUE_TYPES,  # IP addresses, dates and times
         TemplateObject, TemplateObjectList,
         TemplateObject, TemplateObjectList,
     )
     )
     # Jinja's own template objects, matched including subclasses (e.g. StrictUndefined)
     # Jinja's own template objects, matched including subclasses (e.g. StrictUndefined)

+ 25 - 9
netbox/utilities/template_objects.py

@@ -1,6 +1,6 @@
 from collections.abc import Mapping
 from collections.abc import Mapping
 from copy import deepcopy
 from copy import deepcopy
-from datetime import date, time
+from datetime import date, datetime, time, timedelta
 from decimal import Decimal
 from decimal import Decimal
 from importlib import import_module
 from importlib import import_module
 from types import SimpleNamespace
 from types import SimpleNamespace
@@ -12,6 +12,7 @@ from django.core.exceptions import FieldDoesNotExist
 from django.db import models
 from django.db import models
 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 netbox.api.exceptions import SerializerNotFound
 from netbox.api.exceptions import SerializerNotFound
 from netbox.api.fields import RelatedObjectsField
 from netbox.api.fields import RelatedObjectsField
@@ -28,8 +29,10 @@ from utilities.api import (
     get_prefetches_for_serializer,
     get_prefetches_for_serializer,
     get_serializer_for_model,
     get_serializer_for_model,
 )
 )
+from utilities.json import render_native_values
 
 
 __all__ = (
 __all__ = (
+    'NATIVE_VALUE_TYPES',
     'TemplateObject',
     'TemplateObject',
     'TemplateObjectList',
     'TemplateObjectList',
     'get_query_function',
     'get_query_function',
@@ -40,6 +43,12 @@ __all__ = (
     'to_template_data',
     'to_template_data',
 )
 )
 
 
+# Native values which templates receive as they are (e.g. an IPAddress' address), matched by exact type
+NATIVE_VALUE_TYPES = (IPAddress, IPNetwork, date, datetime, time, timedelta)
+
+# Values which to_template_data() passes through unchanged, matched by exact type
+_PLAIN_VALUE_TYPES = (str, int, float, Decimal, bool, *NATIVE_VALUE_TYPES)
+
 # The number of objects a TemplateObjectList loads at a time
 # The number of objects a TemplateObjectList loads at a time
 TEMPLATE_OBJECTS_CHUNK_SIZE = 1000
 TEMPLATE_OBJECTS_CHUNK_SIZE = 1000
 
 
@@ -122,6 +131,12 @@ def template_json_default(obj):
         return [item._get_full_data() for item in obj]
         return [item._get_full_data() for item in obj]
     if isinstance(obj, Decimal):
     if isinstance(obj, Decimal):
         return float(obj)
         return float(obj)
+    if type(obj) is timedelta:
+        # As REST framework's JSON encoder renders it
+        return str(obj.total_seconds())
+    if type(obj) in NATIVE_VALUE_TYPES:
+        # Rendered as in REST API responses
+        return render_native_values(obj)
     raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
     raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
 
 
 
 
@@ -460,9 +475,12 @@ def _get_filter_value(name, value):
         raise TemplateRuntimeError(f"query(): the {name} filter was given an empty string.")
         raise TemplateRuntimeError(f"query(): the {name} filter was given an empty string.")
     if isinstance(value, (str, int, float, Decimal)):
     if isinstance(value, (str, int, float, Decimal)):
         return str(value)
         return str(value)
+    if type(value) in NATIVE_VALUE_TYPES and type(value) is not timedelta:
+        # Rendered as in REST API responses (e.g. a prefix as 192.0.2.0/24)
+        return render_native_values(value)
     raise TemplateRuntimeError(
     raise TemplateRuntimeError(
-        f"query(): the {name} filter takes strings and numbers (found {type(value).__name__}). For a related object, "
-        f"pass its ID or slug."
+        f"query(): the {name} filter takes strings, numbers, IP addresses, dates and times (found "
+        f"{type(value).__name__}). For a related object, pass its ID or slug."
     )
     )
 
 
 
 
@@ -571,9 +589,9 @@ def _serialize(serializer_class, instance, many=False):
 
 
 def to_template_data(value, state=None):
 def to_template_data(value, state=None):
     """
     """
-    Convert a value for restricted rendering to plain dicts, lists, strings, numbers, booleans, and None. Given a
-    render state, model instances are represented by TemplateObjects, and querysets and related managers by
-    TemplateObjectLists.
+    Convert a value for restricted rendering to plain dicts, lists, strings, numbers, booleans, and None, keeping IP
+    addresses, dates and times as they are. Given a render state, model instances are represented by TemplateObjects,
+    and querysets and related managers by TemplateObjectLists.
     """
     """
     if isinstance(value, (TemplateObject, TemplateObjectList)):
     if isinstance(value, (TemplateObject, TemplateObjectList)):
         return value
         return value
@@ -589,9 +607,7 @@ def to_template_data(value, state=None):
         return {key: to_template_data(item, state) for key, item in value.items()}
         return {key: to_template_data(item, state) for key, item in value.items()}
     if isinstance(value, (list, tuple, set, frozenset)):
     if isinstance(value, (list, tuple, set, frozenset)):
         return [to_template_data(item, state) for item in value]
         return [to_template_data(item, state) for item in value]
-    if isinstance(value, (date, time)):
-        return value.isoformat()
-    if value is None or type(value) in (str, int, float, Decimal, bool):
+    if value is None or type(value) in _PLAIN_VALUE_TYPES:
         return value
         return value
     if isinstance(value, str):
     if isinstance(value, str):
         # A str subclass (e.g. a SafeString) may return itself from str()
         # A str subclass (e.g. a SafeString) may return itself from str()

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

@@ -1,7 +1,9 @@
+import datetime
 import json
 import json
 from enum import Enum
 from enum import Enum
 from unittest.mock import patch
 from unittest.mock import patch
 
 
+import netaddr
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes.models import ContentType
 from django.db import connection
 from django.db import connection
 from django.test import SimpleTestCase, TestCase
 from django.test import SimpleTestCase, TestCase
@@ -71,6 +73,32 @@ class TemplateObjectTest(TestCase):
             with self.subTest(template_code=template_code):
             with self.subTest(template_code=template_code):
                 self.assertEqual(self.render(template_code, object=self.device), expected)
                 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.
+        """
+        created = self.ip_address.created
+        cases = (
+            ('{{ object.address }}', '192.0.2.1/24'),
+            ('{{ object.address.ip }} {{ object.address.netmask }}', '192.0.2.1 255.255.255.0'),
+            ('{{ object.address.prefixlen }} {{ object.address.version }}', '24 4'),
+            ('{{ object.address.ip + 1 }} {{ object.address.ip in object.address }}', '192.0.2.2 True'),
+            ('{{ object.created.year }}', str(created.year)),
+            ("{{ object.created.strftime('%Y-%m-%d') }}", f'{created:%Y-%m-%d}'),
+            ('{{ (object.created - object.created).days }}', '0'),
+            ('{{ (object.created - object.created) | tojson }}', '"0.0"'),
+            ('{{ object.address | tojson }}', '"192.0.2.1/24"'),
+            ('{{ object.created | tojson }}', f'"{created.isoformat().replace("+00:00", "Z")}"'),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                self.assertEqual(self.render(template_code, object=self.ip_address), expected)
+
+        # Class methods, and objects returned which aren't of an allowed type, remain inaccessible
+        for template_code in ('{{ object.created.now() }}', '{{ object.address.info.IPv4 }}'):
+            with self.subTest(template_code=template_code), self.assertRaises(SecurityError):
+                self.render(template_code, object=self.ip_address)
+
     def test_context_data(self):
     def test_context_data(self):
         state = RestrictedRenderState(self.superuser)
         state = RestrictedRenderState(self.superuser)
         device = get_template_object(self.device, state)
         device = get_template_object(self.device, state)
@@ -385,6 +413,9 @@ class QueryTest(TestCase):
             ('{{ query("ipam.ipaddress", parent="192.0.2.0/24", interface="Bu1").first().address }}', '192.0.2.1/24'),
             ('{{ query("ipam.ipaddress", parent="192.0.2.0/24", interface="Bu1").first().address }}', '192.0.2.1/24'),
             ('{{ query("ipam.ipaddress", parent="192.0.2.0/24").count() }}', '2'),
             ('{{ query("ipam.ipaddress", parent="192.0.2.0/24").count() }}', '2'),
             ('{{ query("ipam.ipaddress", assigned_to_interface=False).first().address }}', '192.0.2.2/24'),
             ('{{ query("ipam.ipaddress", assigned_to_interface=False).first().address }}', '192.0.2.2/24'),
+            # IP addresses and dates are passed as they appear in a REST API query string
+            ('{{ query("ipam.ipaddress", parent=query("ipam.ipaddress").first().address.cidr).count() }}', '2'),
+            ('{{ query("ipam.ipaddress", created__gte=query("ipam.ipaddress").first().created).count() }}', '2'),
             ('{{ query("dcim.device").first().site.name }}', 'Site 1'),
             ('{{ query("dcim.device").first().site.name }}', 'Site 1'),
             ('{{ query("dcim.site", slug="none") | length }}', '0'),
             ('{{ query("dcim.site", slug="none") | length }}', '0'),
             ('{{ query("dcim.site", slug=[]) | length }}/{{ query("dcim.site", slug=[]).count() }}', '0/0'),
             ('{{ query("dcim.site", slug=[]) | length }}/{{ query("dcim.site", slug=[]).count() }}', '0/0'),
@@ -506,6 +537,19 @@ class QueryTest(TestCase):
 
 
 class ToTemplateDataTest(SimpleTestCase):
 class ToTemplateDataTest(SimpleTestCase):
 
 
+    def test_native_values(self):
+        values = (
+            netaddr.IPNetwork('192.0.2.1/24'),
+            netaddr.IPAddress('192.0.2.1'),
+            datetime.datetime(2026, 12, 5, 14, 30, tzinfo=datetime.UTC),
+            datetime.date(2026, 12, 5),
+            datetime.time(14, 30),
+            datetime.timedelta(days=1),
+        )
+        for value in values:
+            with self.subTest(value=value):
+                self.assertIs(to_template_data(value), value)
+
     def test_str_subclasses(self):
     def test_str_subclasses(self):
         # Unlike a StrEnum, str() of this member gives 'Status.ACTIVE'
         # Unlike a StrEnum, str() of this member gives 'Status.ACTIVE'
         class Status(str, Enum):  # noqa: UP042
         class Status(str, Enum):  # noqa: UP042