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

Closes #23878: Pass string subclasses as plain strings

A str subclass in a config template's extra context, such as a
SafeString or a str-based Enum member, kept its type, so the restricted
sandbox blocked its string methods. Such values are now converted to
plain strings holding their value.
Jeremy Stretch 2 часов назад
Родитель
Сommit
3fd78d32f4

+ 4 - 2
netbox/dcim/tests/test_models.py

@@ -11,6 +11,7 @@ from django.db.models import ProtectedError
 from django.db.models.signals import post_save
 from django.test import RequestFactory, TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
+from django.utils.safestring import mark_safe
 from django.utils.text import slugify
 from jinja2 import TemplateSyntaxError
 from jinja2.sandbox import SecurityError
@@ -1730,13 +1731,14 @@ class DeviceRestrictedRenderConfigTestCase(TestCase):
             'interfaces': self.device.interfaces,
             'devices': [self.device],
             'sites': {self.device.site},
+            'banner': mark_safe('Banner'),
         }
         output = self.render(
             '{{ site.slug }} {{ interfaces | map(attribute="name") | join(",") }} {{ devices[0].name }} '
-            '{{ sites[0].slug }}',
+            '{{ sites[0].slug }} {{ banner.upper() }}',
             extra_context=extra_context,
         )
-        self.assertEqual(output, 'site-1 eth0,eth1 Device 1 site-1')
+        self.assertEqual(output, 'site-1 eth0,eth1 Device 1 site-1 BANNER')
 
     def test_extra_context_sliced_queryset(self):
         template_code = '{{ interfaces | map(attribute="name") | join(",") }}'

+ 3 - 0
netbox/utilities/template_objects.py

@@ -576,5 +576,8 @@ def to_template_data(value, state=None):
         return value.isoformat()
     if value is None or type(value) in (str, int, float, Decimal, bool):
         return value
+    if isinstance(value, str):
+        # A str subclass (e.g. a SafeString) may return itself from str()
+        return str.__str__(value)
     # Anything else (e.g. a lazy translation string) is represented by its string value
     return str(value)

+ 18 - 2
netbox/utilities/tests/test_template_objects.py

@@ -1,10 +1,12 @@
 import json
+from enum import Enum
 from unittest.mock import patch
 
 from django.contrib.contenttypes.models import ContentType
 from django.db import connection
-from django.test import TestCase
+from django.test import SimpleTestCase, TestCase
 from django.test.utils import CaptureQueriesContext
+from django.utils.safestring import mark_safe
 from jinja2 import TemplateRuntimeError, UndefinedError
 from jinja2.sandbox import SecurityError
 
@@ -15,7 +17,7 @@ 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 _load_objects, get_template_object, get_template_objects
+from utilities.template_objects import _load_objects, get_template_object, get_template_objects, to_template_data
 from utilities.testing import create_test_device
 
 
@@ -473,3 +475,17 @@ class QueryTest(TestCase):
     def test_internals_are_inaccessible(self):
         with self.assertRaises(SecurityError):
             self.render('{{ query.__closure__ }}')
+
+
+class ToTemplateDataTest(SimpleTestCase):
+
+    def test_str_subclasses(self):
+        # Unlike a StrEnum, str() of this member gives 'Status.ACTIVE'
+        class Status(str, Enum):  # noqa: UP042
+            ACTIVE = 'active'
+
+        for value, expected in ((mark_safe('safe'), 'safe'), (Status.ACTIVE, 'active')):
+            with self.subTest(value=value):
+                result = to_template_data(value)
+                self.assertIs(type(result), str)
+                self.assertEqual(result, expected)