Sfoglia il codice sorgente

Closes #23874: Introduce restricted template rendering

Add the TEMPLATE_RENDERING configuration parameter, which selects a
legacy or restricted rendering mode for each feature that renders
user-authored templates, along with the restricted sandbox and render
state that restricted mode builds on. No feature supports restricted
mode yet; each will opt in as its own issue is completed.
Jeremy Stretch 1 giorno fa
parent
commit
023d2d096f

+ 35 - 0
docs/configuration/system.md

@@ -417,6 +417,41 @@ This approach works because the environment variables are resolved during NetBox
 
 ---
 
+## TEMPLATE_RENDERING
+
+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`). 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.
+
+```python
+TEMPLATE_RENDERING = 'restricted'
+
+# or
+TEMPLATE_RENDERING = {
+    'custom_links': 'restricted',
+    'export_templates': 'legacy',
+}
+```
+
+| Feature | Key | Supports `restricted` |
+|---|---|---|
+| Config templates | `config_templates` | No |
+| Custom links | `custom_links` | No |
+| Export templates | `export_templates` | No |
+| Webhooks | `webhooks` | No |
+
+NetBox will fail to start if this parameter names an unknown feature or mode, or selects `restricted` for a feature that doesn't support it.
+
+!!! warning "Default changes in NetBox v5.0"
+    The default mode will change to `restricted` in NetBox v5.0.
+
+---
+
 ## TIME_ZONE
 
 Default: `"UTC"`

+ 4 - 0
netbox/netbox/configuration_example.py

@@ -237,6 +237,10 @@ SESSION_COOKIE_NAME = 'sessionid'
 # database access.) Note that the user as which NetBox runs must have read and write permissions to this path.
 SESSION_FILE_PATH = None
 
+# Select how user-authored templates (config templates, custom links, export templates, and webhooks) are rendered:
+# 'legacy' or 'restricted'. This may also be a dictionary mapping each feature to a mode.
+# TEMPLATE_RENDERING = 'legacy'
+
 # By default the memory and disk sizes are displayed using base 10 (e.g. 1000 MB = 1 GB).
 # If you would like to use base 2 (e.g. 1024 MB = 1 GB) set this to 1024.
 # DISK_BASE_UNIT = 1024

+ 14 - 0
netbox/netbox/constants.py

@@ -19,6 +19,20 @@ RQ_QUEUE_DEFAULT = 'default'
 RQ_QUEUE_HIGH = 'high'
 RQ_QUEUE_LOW = 'low'
 
+# Template rendering modes (TEMPLATE_RENDERING)
+TEMPLATE_RENDERING_LEGACY = 'legacy'
+TEMPLATE_RENDERING_RESTRICTED = 'restricted'
+TEMPLATE_RENDERING_MODES = (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED)
+TEMPLATE_RENDERING_DEFAULT = TEMPLATE_RENDERING_LEGACY
+
+# Features which render user-authored templates, mapped to the rendering modes each supports
+TEMPLATE_RENDERING_FEATURES = {
+    'config_templates': (TEMPLATE_RENDERING_LEGACY,),
+    'custom_links': (TEMPLATE_RENDERING_LEGACY,),
+    'export_templates': (TEMPLATE_RENDERING_LEGACY,),
+    'webhooks': (TEMPLATE_RENDERING_LEGACY,),
+}
+
 # Keys for PostgreSQL advisory locks. These are arbitrary bigints used by the advisory_lock
 # context manager. When a lock is acquired, one of these keys will be used to identify said lock.
 # When adding a new key, pick something arbitrary and unique so that it is easily searchable in

+ 5 - 1
netbox/netbox/settings.py

@@ -16,7 +16,7 @@ from django.utils.translation import gettext_lazy as _
 
 from core.exceptions import IncompatiblePluginError
 from netbox.config import PARAMS as CONFIG_PARAMS
-from netbox.constants import RQ_QUEUE_DEFAULT, RQ_QUEUE_HIGH, RQ_QUEUE_LOW
+from netbox.constants import RQ_QUEUE_DEFAULT, RQ_QUEUE_HIGH, RQ_QUEUE_LOW, TEMPLATE_RENDERING_DEFAULT
 from netbox.plugins import PluginConfig
 from netbox.registry import registry
 from netbox.settings_utils import (
@@ -27,6 +27,7 @@ from netbox.settings_utils import (
     resolve_install_paths,
     secret_key_hint,
     validate_permissions_policy,
+    validate_template_rendering,
     validate_webhook_default_timeout,
 )
 from utilities.release import load_release_data
@@ -245,6 +246,9 @@ SESSION_FILE_PATH = param('SESSION_FILE_PATH', None, types=(str, os.PathLike), a
 STORAGE_BACKEND = param('STORAGE_BACKEND', None, types=str, allow_none=True)
 STORAGE_CONFIG = param('STORAGE_CONFIG', None, types=dict, allow_none=True)
 STORAGES = param('STORAGES', {}, types=dict)
+TEMPLATE_RENDERING = param(
+    'TEMPLATE_RENDERING', TEMPLATE_RENDERING_DEFAULT, types=(str, dict), validators=[validate_template_rendering]
+)
 TIME_ZONE = param('TIME_ZONE', 'UTC', types=str)
 TRANSLATION_ENABLED = param('TRANSLATION_ENABLED', True, types=bool)
 WEBHOOK_DEFAULT_TIMEOUT = param('WEBHOOK_DEFAULT_TIMEOUT', 60)

+ 30 - 0
netbox/netbox/settings_utils.py

@@ -15,6 +15,8 @@ from rq.exceptions import TimeoutFormatError
 from rq.queue import Queue
 from rq.utils import parse_timeout
 
+from netbox.constants import TEMPLATE_RENDERING_FEATURES, TEMPLATE_RENDERING_MODES
+
 __all__ = (
     'InstallPaths',
     'get_configuration_dir',
@@ -25,6 +27,7 @@ __all__ = (
     'resolve_install_paths',
     'secret_key_hint',
     'validate_permissions_policy',
+    'validate_template_rendering',
     'validate_webhook_default_timeout',
 )
 
@@ -124,6 +127,33 @@ def validate_webhook_default_timeout(timeout, job_timeout):
         )
 
 
+def validate_template_rendering(name, value):
+    """Validate TEMPLATE_RENDERING, which is either a single mode or a dict mapping features to modes."""
+    if isinstance(value, str):
+        if value not in TEMPLATE_RENDERING_MODES:
+            raise ImproperlyConfigured(
+                f"{name} contains the unknown mode {value!r} (valid modes: {', '.join(TEMPLATE_RENDERING_MODES)})"
+            )
+        if unsupported := [f for f, modes in TEMPLATE_RENDERING_FEATURES.items() if value not in modes]:
+            raise ImproperlyConfigured(
+                f"{name}: the {value!r} mode is not supported by {', '.join(unsupported)}. "
+                "Set a mode per feature instead."
+            )
+        return
+    for feature, mode in value.items():
+        if feature not in TEMPLATE_RENDERING_FEATURES:
+            raise ImproperlyConfigured(
+                f"{name} contains the unknown feature {feature!r} "
+                f"(valid features: {', '.join(TEMPLATE_RENDERING_FEATURES)})"
+            )
+        if mode not in TEMPLATE_RENDERING_MODES:
+            raise ImproperlyConfigured(
+                f"{name} contains the unknown mode {mode!r} (valid modes: {', '.join(TEMPLATE_RENDERING_MODES)})"
+            )
+        if mode not in TEMPLATE_RENDERING_FEATURES[feature]:
+            raise ImproperlyConfigured(f"{name}: {feature} does not support the {mode!r} mode")
+
+
 _LABEL = r'[A-Za-z0-9_]([A-Za-z0-9_-]*[A-Za-z0-9_])?'
 ORIGIN_NETLOC_RE = re.compile(rf'(\*\.)?{_LABEL}(\.{_LABEL})*(:[0-9]+)?|\[[0-9A-Fa-f:.]+\](:[0-9]+)?')
 

+ 36 - 0
netbox/netbox/tests/test_settings_utils.py

@@ -464,6 +464,42 @@ class ValidatePermissionsPolicyTest(SimpleTestCase):
                     settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': [entry]})
 
 
+@patch.dict('netbox.constants.TEMPLATE_RENDERING_FEATURES', {
+    'custom_links': ('legacy',),
+    'webhooks': ('legacy', 'restricted'),
+}, clear=True)
+class ValidateTemplateRenderingTest(SimpleTestCase):
+    """validate_template_rendering() is the startup check applied to TEMPLATE_RENDERING."""
+
+    def test_valid_values(self):
+        for value in (
+            'legacy',
+            {},
+            {'webhooks': 'restricted'},
+            {'custom_links': 'legacy', 'webhooks': 'restricted'},
+        ):
+            with self.subTest(value=value):
+                settings_utils.validate_template_rendering('TEMPLATE_RENDERING', value)
+
+    def test_unknown_feature_raises(self):
+        with self.assertRaisesMessage(ImproperlyConfigured, "unknown feature 'reports'"):
+            settings_utils.validate_template_rendering('TEMPLATE_RENDERING', {'reports': 'legacy'})
+
+    def test_unknown_mode_raises(self):
+        for value in ('disabled', {'webhooks': 'disabled'}, {'webhooks': None}):
+            with self.subTest(value=value):
+                with self.assertRaisesMessage(ImproperlyConfigured, 'unknown mode'):
+                    settings_utils.validate_template_rendering('TEMPLATE_RENDERING', value)
+
+    def test_unsupported_mode_raises(self):
+        with self.assertRaisesMessage(ImproperlyConfigured, "custom_links does not support the 'restricted'"):
+            settings_utils.validate_template_rendering('TEMPLATE_RENDERING', {'custom_links': 'restricted'})
+
+    def test_unsupported_single_mode_names_features(self):
+        with self.assertRaisesMessage(ImproperlyConfigured, "'restricted' mode is not supported by custom_links."):
+            settings_utils.validate_template_rendering('TEMPLATE_RENDERING', 'restricted')
+
+
 class LoadLdapConfigTest(SimpleTestCase):
     def test_loads_sibling_ldap_config(self):
         with tempfile.TemporaryDirectory() as conf_dir:

+ 95 - 3
netbox/utilities/jinja2.py

@@ -1,16 +1,26 @@
 import fnmatch
 import os
 import re
+from decimal import Decimal
+from types import FunctionType
 
 from django.apps import apps
+from django.conf import settings
 from django.core.exceptions import ValidationError
 from django.utils.translation import gettext_lazy as _
 from jinja2 import BaseLoader, TemplateNotFound
+from jinja2.environment import TemplateModule
 from jinja2.exceptions import TemplateSyntaxError
+from jinja2.filters import _GroupTuple
 from jinja2.meta import find_referenced_templates
-from jinja2.sandbox import SandboxedEnvironment
+from jinja2.runtime import BlockReference, LoopContext, Macro, TemplateReference, Undefined
+from jinja2.sandbox import SandboxedEnvironment, SecurityError
+from jinja2.utils import Cycler, Joiner, Namespace
+from markupsafe import Markup
+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
 
 __all__ = (
@@ -18,7 +28,10 @@ __all__ = (
     'HTTP_HEADER_INVALID_CHARS_RE',
     'JINJA2_TEMPLATE_RE',
     'DataFileLoader',
+    'RestrictedRenderState',
+    'RestrictedSandboxedEnvironment',
     'env_filter',
+    'get_template_rendering_mode',
     'render_jinja2',
     'sanitize_http_header',
     'validate_jinja2_syntax',
@@ -93,6 +106,66 @@ class DataFileLoader(BaseLoader):
         self._template_cache.update(templates)
 
 
+class RestrictedSandboxedEnvironment(SandboxedEnvironment):
+    """
+    A sandboxed Jinja2 environment which permits attribute access and method calls only on plain data types.
+    """
+    # Matched by exact type, since a subclass may add its own methods
+    allowed_types = (
+        dict, list, tuple, str, int, float, Decimal, bool, type(None), range,
+        ReturnDict, ReturnList,  # Serializer output
+        Markup, _GroupTuple,  # Escaped strings and groupby() results
+    )
+    # Jinja's own template objects, matched including subclasses (e.g. StrictUndefined)
+    allowed_template_types = (
+        BlockReference, Cycler, Joiner, LoopContext, Macro, Namespace, TemplateModule, TemplateReference, Undefined,
+    )
+
+    def __init__(self, *args, **kwargs):
+        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())
+
+    def is_allowed(self, obj):
+        return type(obj) in self.allowed_types or isinstance(obj, self.allowed_template_types)
+
+    def is_safe_attribute(self, obj, attr, value):
+        return self.is_allowed(obj) and super().is_safe_attribute(obj, attr, value)
+
+    def is_safe_callable(self, obj):
+        if not super().is_safe_callable(obj):
+            return False
+        if any(obj is allowed for allowed in self.allowed_callables):
+            return True
+        # Unwrap the sandbox's str.format() wrapper, then permit only methods of (or calls to) allowed types
+        if isinstance(obj, FunctionType):
+            obj = getattr(obj, '__wrapped__', obj)
+        return self.is_allowed(getattr(obj, '__self__', obj))
+
+    def getattr(self, obj, attribute):
+        if not self.is_allowed(obj):
+            return self.unsafe_undefined(obj, attribute)
+        return super().getattr(obj, attribute)
+
+    def getitem(self, obj, argument):
+        if not self.is_allowed(obj):
+            return self.unsafe_undefined(obj, argument)
+        return super().getitem(obj, argument)
+
+    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.")
+
+
+class RestrictedRenderState:
+    """
+    State shared across a single restricted render: the user on whose behalf it runs, and a cache of fetched objects.
+    """
+    def __init__(self, user=None):
+        self.user = user
+        self.cache = {}
+
+
 #
 # Utility functions
 #
@@ -114,7 +187,19 @@ def _jinja2_filters(filters=None):
     }
 
 
-def render_jinja2(template_code, context, environment_params=None, data_file=None, debug=False, filters=None):
+def get_template_rendering_mode(feature):
+    """
+    Return the TEMPLATE_RENDERING mode configured for the given feature (e.g. 'export_templates').
+    """
+    if feature not in TEMPLATE_RENDERING_FEATURES:
+        raise ValueError(f"Unknown template rendering feature: {feature}")
+    if isinstance(settings.TEMPLATE_RENDERING, str):
+        return settings.TEMPLATE_RENDERING
+    return settings.TEMPLATE_RENDERING.get(feature, TEMPLATE_RENDERING_DEFAULT)
+
+
+def render_jinja2(template_code, context, environment_params=None, data_file=None, debug=False, filters=None,
+                  restricted=None):
     """
     Render a Jinja2 template with the provided context. Return the rendered content.
 
@@ -122,8 +207,14 @@ 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 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)
 
     if debug:
         extensions = list(environment_params.get('extensions', []))
@@ -141,7 +232,8 @@ def render_jinja2(template_code, context, environment_params=None, data_file=Non
             loader = BaseLoader()
         environment_params['loader'] = loader
 
-    environment = SandboxedEnvironment(**environment_params)
+    environment_class = SandboxedEnvironment if restricted is None else RestrictedSandboxedEnvironment
+    environment = environment_class(**environment_params)
     environment.filters.update(_jinja2_filters(filters))
 
     if data_file:

+ 196 - 0
netbox/utilities/tests/test_jinja2.py

@@ -0,0 +1,196 @@
+from decimal import Decimal
+
+from django.test import SimpleTestCase, TestCase, override_settings
+from jinja2 import ChainableUndefined, StrictUndefined, UndefinedError
+from jinja2.sandbox import SecurityError
+from rest_framework.utils.serializer_helpers import ReturnDict
+
+from netbox.constants import TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED
+from utilities.jinja2 import RestrictedRenderState, get_template_rendering_mode, render_jinja2
+
+
+class Thing:
+    name = 'thing'
+
+    def __str__(self):
+        return 'Thing'
+
+    def __getitem__(self, key):
+        return key
+
+    def method(self):
+        return 'called'
+
+
+class ThingDict(dict):
+
+    def method(self):
+        return 'called'
+
+
+def thing_filter(value):
+    return Thing()
+
+
+def render(template_code, **context):
+    return render_jinja2(template_code, context, restricted=RestrictedRenderState())
+
+
+class RestrictedSandboxedEnvironmentTest(TestCase):
+
+    def test_data_types(self):
+        context = {
+            'd': {'a': 1, 'b': [1, 2]},
+            'rd': ReturnDict({'a': 1}, serializer=None),
+            't': (1, 2),
+            'dec': Decimal('1.50'),
+            'n': None,
+        }
+        cases = (
+            ('{{ d.a }}', '1'),
+            ('{{ d["b"][1] }}', '2'),
+            ('{{ d.get("c", 3) }}', '3'),
+            ('{% for k, v in d.items() %}{{ k }}{% endfor %}', 'ab'),
+            ('{{ rd.a }}', '1'),
+            ('{{ t[0] }}', '1'),
+            ('{{ "a,b".split(",") | join("-") }}', 'a-b'),
+            ('{{ "x".upper() }}', 'X'),
+            ('{{ "{}-{}".format(1, 2) }}', '1-2'),
+            ('{{ (7).bit_length() }}', '3'),
+            ('{{ dec.quantize(dec) }}', '1.50'),
+            ('{{ n is none }}', 'True'),
+            ('{{ range(3)[1] }}', '1'),
+            ('{{ ("a" | e).upper() }}', 'A'),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                self.assertEqual(render(template_code, **context), expected)
+
+    def test_jinja_template_objects(self):
+        cases = (
+            ('{% for i in range(3) %}{{ loop.index }}{{ loop.cycle("a", "b") }}{% endfor %}', '1a2b3a'),
+            ('{% set ns = namespace(x=1) %}{% set ns.x = 2 %}{{ ns.x }}', '2'),
+            ('{% set c = cycler("a", "b") %}{{ c.next() }}{{ c.next() }}', 'ab'),
+            ('{% set j = joiner(",") %}{{ j() }}a{{ j() }}b', 'a,b'),
+            ('{{ dict(a=1).a }}', '1'),
+            ('{% macro m(x) %}{{ x }}{{ caller() }}{% endmacro %}{% call m(1) %}2{% endcall %}', '12'),
+            (
+                '{% for i in [[1, [2]]] recursive %}{% if i is iterable %}{{ loop(i) }}{% else %}{{ i }}{% endif %}'
+                '{% endfor %}',
+                '12'
+            ),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                self.assertEqual(render(template_code), expected)
+
+    def test_filters(self):
+        context = {'items': [{'name': 'a'}, {'name': 'b'}]}
+        self.assertEqual(render('{{ items | map(attribute="name") | join }}', **context), 'ab')
+        self.assertEqual(
+            render('{% for g in items | groupby("name") %}{{ g.grouper }}{{ g.list | length }}{% endfor %}', **context),
+            'a1b1'
+        )
+        self.assertEqual(
+            render_jinja2(
+                '{{ "x" | custom }}', {}, filters={'custom': str.upper}, restricted=RestrictedRenderState()
+            ),
+            'X'
+        )
+
+    def test_other_objects_render_as_strings(self):
+        self.assertEqual(render('{{ obj }}', obj=Thing()), 'Thing')
+
+    def test_other_objects_are_inaccessible(self):
+        context = {'obj': Thing(), 'objs': [Thing()], 'thing_dict': ThingDict(a=1)}
+        for template_code in (
+            '{{ thing_dict.a }}',
+            '{{ thing_dict.method() }}',
+            '{{ obj.name }}',
+            '{{ obj["name"] }}',
+            '{{ obj.method() }}',
+            '{{ obj | attr("name") }}',
+            '{{ objs | map(attribute="name") | join }}',
+            '{{ "{0.name}".format(obj) }}',
+        ):
+            with self.subTest(template_code=template_code):
+                with self.assertRaises(SecurityError):
+                    render(template_code, **context)
+
+    def test_private_attributes_are_inaccessible(self):
+        for template_code in ('{{ d.__class__ }}', '{{ "x".__class__ }}', '{{ d | attr("__class__") }}'):
+            with self.subTest(template_code=template_code):
+                with self.assertRaises(SecurityError):
+                    render(template_code, d={})
+
+    def test_filter_results_are_inaccessible(self):
+        with self.assertRaises(SecurityError):
+            render_jinja2(
+                '{{ ("x" | thing).name }}', {}, filters={'thing': thing_filter}, restricted=RestrictedRenderState()
+            )
+
+    def test_calls(self):
+        thing = Thing()
+        context = {
+            'cls': Thing,
+            'func': thing_filter,
+            'methods': {'method': thing.method},
+        }
+        for template_code in ('{{ cls() }}', '{{ func("x") }}', '{{ methods.method() }}'):
+            with self.subTest(template_code=template_code):
+                with self.assertRaises(SecurityError):
+                    render(template_code, **context)
+
+    def test_undefined(self):
+        with self.assertRaises(UndefinedError):
+            render('{{ missing.attr }}')
+        with self.assertRaises(UndefinedError):
+            render_jinja2(
+                '{{ missing }}',
+                {},
+                environment_params={'undefined': StrictUndefined},
+                restricted=RestrictedRenderState(),
+            )
+        self.assertEqual(
+            render_jinja2(
+                '{{ missing.attr.other }}',
+                {},
+                environment_params={'undefined': ChainableUndefined},
+                restricted=RestrictedRenderState(),
+            ),
+            ''
+        )
+
+    def test_finalize_is_ignored(self):
+        environment_params = {'finalize': lambda value: 'finalized'}
+        self.assertEqual(render_jinja2('{{ 1 }}', {}, environment_params=environment_params), 'finalized')
+        self.assertEqual(
+            render_jinja2('{{ 1 }}', {}, environment_params=environment_params, restricted=RestrictedRenderState()),
+            '1'
+        )
+
+    def test_restricted_requires_render_state(self):
+        with self.assertRaises(TypeError):
+            render_jinja2('{{ 1 }}', {}, restricted=False)
+
+    def test_legacy_rendering_is_unchanged(self):
+        self.assertEqual(render_jinja2('{{ obj.name }} {{ obj.method() }}', {'obj': Thing()}), 'thing called')
+
+
+class GetTemplateRenderingModeTest(SimpleTestCase):
+
+    @override_settings(TEMPLATE_RENDERING=TEMPLATE_RENDERING_RESTRICTED)
+    def test_single_mode(self):
+        self.assertEqual(get_template_rendering_mode('webhooks'), TEMPLATE_RENDERING_RESTRICTED)
+
+    @override_settings(TEMPLATE_RENDERING={'webhooks': TEMPLATE_RENDERING_RESTRICTED})
+    def test_mode_per_feature(self):
+        self.assertEqual(get_template_rendering_mode('webhooks'), TEMPLATE_RENDERING_RESTRICTED)
+        self.assertEqual(get_template_rendering_mode('custom_links'), TEMPLATE_RENDERING_LEGACY)
+
+    def test_default(self):
+        self.assertEqual(get_template_rendering_mode('export_templates'), TEMPLATE_RENDERING_LEGACY)
+
+    def test_unknown_feature(self):
+        with self.assertRaises(ValueError):
+            get_template_rendering_mode('reports')