Jelajahi Sumber

Closes #23877: Add restricted rendering mode for webhooks

Support the restricted mode of TEMPLATE_RENDERING for webhooks. Their
URL, headers, and body template are rendered in the restricted
environment, with a context reduced to plain data. Data returned by
plugin callbacks is round-tripped through JSON, and omitted if it can't
be serialized.
Jeremy Stretch 17 jam lalu
induk
melakukan
cfce74c0d0

+ 1 - 1
docs/configuration/system.md

@@ -443,7 +443,7 @@ TEMPLATE_RENDERING = {
 | Config templates | `config_templates` | No |
 | Custom links | `custom_links` | No |
 | Export templates | `export_templates` | No |
-| Webhooks | `webhooks` | No |
+| Webhooks | `webhooks` | Yes |
 
 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.
 

+ 7 - 0
docs/integrations/webhooks.md

@@ -47,6 +47,13 @@ Whenever a header value incorporates data which may be influenced by other users
 X-Object-Name: {{ data.name | header_safe }}
 ```
 
+### Restricted Rendering
+
+When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for webhooks, the URL, headers, and body template are rendered in a restricted environment which permits access only to plain data (dictionaries, lists, strings, numbers, booleans, and `None`). The available context is the same, with a few differences:
+
+* `request.GET` holds the last value of each query parameter.
+* Data provided by plugins under `context` is converted to plain data, as if serialized to JSON. If a plugin's data can't be serialized, all of it is omitted and a warning is logged.
+
 ### Default Request Body
 
 If no body template is specified, the request body will be populated with a JSON object containing the context data. For example, a newly created site might appear as follows:

+ 2 - 0
docs/plugins/development/webhooks.md

@@ -8,6 +8,8 @@ Plugins can register callback functions to supplement a webhook's payload with t
 
 This can be accomplished by defining a function which accepts a defined set of keyword arguments and registering it as a webhook callback. Whenever a new webhook is generated, the function will be called, and any data it returns will be attached to the webhook's payload under the `context` key.
 
+The returned data must be serializable to JSON. When webhooks are rendered in [restricted mode](../../configuration/system.md#template_rendering), the data is converted as if serialized to JSON, and if it can't be serialized, all of it is omitted and a warning is logged.
+
 ### Example
 
 ```python

+ 26 - 4
netbox/extras/models/models.py

@@ -25,6 +25,7 @@ from extras.models.mixins import RenderTemplateMixin
 from extras.querysets import SharedObjectQuerySet
 from extras.utils import image_upload
 from netbox.config import get_config
+from netbox.constants import TEMPLATE_RENDERING_RESTRICTED
 from netbox.event_rules import get_event_rule_action, get_event_rule_action_choices
 from netbox.events import get_event_type_choices
 from netbox.models import ChangeLoggedModel
@@ -40,7 +41,14 @@ from netbox.models.features import (
 from netbox.models.mixins import OwnerMixin
 from netbox.settings_utils import parse_job_timeout
 from utilities.html import clean_html
-from utilities.jinja2 import JINJA2_TEMPLATE_RE, render_jinja2, sanitize_http_header, validate_jinja2_syntax
+from utilities.jinja2 import (
+    JINJA2_TEMPLATE_RE,
+    RestrictedRenderState,
+    get_template_rendering_mode,
+    render_jinja2,
+    sanitize_http_header,
+    validate_jinja2_syntax,
+)
 from utilities.querydict import dict_to_querydict
 from utilities.querysets import RestrictedQuerySet
 from utilities.tables import get_table_for_model
@@ -386,7 +394,12 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, Ch
         ret = {}
         # Expose the `header_safe` filter so template authors can sanitize interpolated values (e.g. user-controlled
         # object data) against HTTP header (CR/LF) injection. See utilities.jinja2.sanitize_http_header.
-        data = render_jinja2(self.additional_headers, context, filters={'header_safe': sanitize_http_header})
+        data = render_jinja2(
+            self.additional_headers,
+            context,
+            filters={'header_safe': sanitize_http_header},
+            restricted=self._get_render_state(),
+        )
         for line in data.splitlines():
             if ':' not in line:
                 continue
@@ -399,14 +412,23 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, Ch
         Render the body template, if defined. Otherwise, jump the context as a JSON object.
         """
         if self.body_template:
-            return render_jinja2(self.body_template, context)
+            return render_jinja2(self.body_template, context, restricted=self._get_render_state())
         return json.dumps(context, cls=JSONEncoder)
 
     def render_payload_url(self, context):
         """
         Render the payload URL.
         """
-        return render_jinja2(self.payload_url, context)
+        return render_jinja2(self.payload_url, context, restricted=self._get_render_state())
+
+    @staticmethod
+    def _get_render_state():
+        """
+        Return the state for rendering webhook templates in restricted mode, or None if it isn't selected.
+        """
+        if get_template_rendering_mode('webhooks') == TEMPLATE_RENDERING_RESTRICTED:
+            return RestrictedRenderState()
+        return None
 
 
 class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel):

+ 89 - 1
netbox/extras/tests/test_event_rules.py

@@ -13,6 +13,7 @@ from django.core.exceptions import ImproperlyConfigured, ValidationError
 from django.http import HttpResponse
 from django.test import RequestFactory, TestCase, override_settings, tag
 from django.urls import reverse
+from jinja2.sandbox import SecurityError
 from PIL import Image
 from requests import Session
 from rest_framework import status
@@ -39,7 +40,7 @@ from netbox.event_rules import (
 )
 from netbox.registry import registry
 from netbox.tests.dummy_plugin.event_rules import DummyRaisingAction
-from users.models import ObjectPermission
+from users.models import ObjectPermission, User
 from utilities.testing import APITestCase, create_test_device, disable_warnings
 from utilities.testing.mixins import RQQueueTestMixin
 
@@ -2046,3 +2047,90 @@ class WebhookRenderHeadersTest(TestCase):
         self.assertEqual(list(headers.keys()), ['X-Object'])
         self.assertNotIn('X-Injected', headers)
         self.assertEqual(headers['X-Object'], 'legitX-Injected: evil')
+
+
+@override_settings(TEMPLATE_RENDERING={'webhooks': 'restricted'})
+class WebhookRestrictedRenderingTest(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.webhook = Webhook.objects.create(
+            name='Webhook 1',
+            payload_url='http://localhost:9000/{{ data.slug }}/',
+            additional_headers='X-Object: {{ data.name | header_safe }}',
+            body_template='{{ data.status.label.upper() }} {{ request.GET.q }} {{ context.plugin.foo }}',
+        )
+        cls.event_rule = EventRule.objects.create(
+            name='Event Rule 1',
+            event_types=[OBJECT_CREATED],
+            action_type=EventRuleActionChoices.WEBHOOK,
+            action_object_type=ObjectType.objects.get_for_model(Webhook),
+            action_object_id=cls.webhook.pk,
+        )
+        cls.site = Site.objects.create(name='Site 1', slug='site-1')
+
+    def test_render(self):
+        context = {'data': {'name': 'Site 1', 'slug': 'site-1', 'status': {'label': 'Active'}}}
+        self.assertEqual(self.webhook.render_payload_url(context), 'http://localhost:9000/site-1/')
+        self.assertEqual(self.webhook.render_headers(context), {'X-Object': 'Site 1'})
+
+    def test_render_restricts_access(self):
+        webhook = Webhook(name='Webhook 2', payload_url='http://localhost:9000/', body_template='{{ data.name }}')
+        with self.assertRaises(SecurityError):
+            webhook.render_body({'data': Site(name='Site 1')})
+
+    def test_send_webhook(self):
+        def plain_callback(object_type, event_type, data, request):
+            return {'plugin': {'foo': 'bar'}}
+
+        def object_callback(object_type, event_type, data, request):
+            return {'site': Site.objects.first()}
+
+        def dummy_send(_, request, **kwargs):
+            # Lazy choice labels and the request's query parameters are plain data
+            self.assertEqual(request.url, 'http://localhost:9000/site-1/')
+            self.assertEqual(request.headers['X-Object'], 'Site 1')
+            self.assertEqual(request.body, b'ACTIVE foo bar')
+            return HttpResponse()
+
+        request = RequestFactory().get('/dcim/sites/', {'q': 'foo'})
+        request.user = User.objects.create_user(username='testuser')
+        with (
+            patch.dict(registry, {'webhook_callbacks': [plain_callback, object_callback]}),
+            patch.object(Session, 'send', dummy_send),
+            self.assertLogs('netbox.webhooks', level='WARNING') as logs,
+        ):
+            send_webhook(
+                event_rule=self.event_rule,
+                object_type=ObjectType.objects.get_for_model(Site),
+                event_type=OBJECT_CREATED,
+                data=serialize_for_event(self.site),
+                timestamp='2026-12-04T00:00:00+00:00',
+                request=request,
+            )
+        # The callback returning an object is omitted
+        self.assertIn('object_callback', logs.output[0])
+        self.assertIn("can't be serialized", logs.output[0])
+
+    def test_send_webhook_default_body(self):
+        Webhook.objects.filter(pk=self.webhook.pk).update(body_template='')
+        self.event_rule.refresh_from_db()
+
+        def dummy_send(_, request, **kwargs):
+            body = json.loads(request.body)
+            self.assertEqual(body['data']['name'], 'Site 1')
+            self.assertEqual(body['data']['status']['label'], 'Active')
+            self.assertEqual(body['request']['GET'], {'q': 'foo'})
+            return HttpResponse()
+
+        request = RequestFactory().get('/dcim/sites/', {'q': 'foo'})
+        request.user = User.objects.create_user(username='testuser')
+        with patch.object(Session, 'send', dummy_send):
+            send_webhook(
+                event_rule=EventRule.objects.get(pk=self.event_rule.pk),
+                object_type=ObjectType.objects.get_for_model(Site),
+                event_type=OBJECT_CREATED,
+                data=serialize_for_event(self.site),
+                timestamp='2026-12-04T00:00:00+00:00',
+                request=request,
+            )

+ 24 - 1
netbox/extras/webhooks.py

@@ -1,16 +1,21 @@
 import hashlib
 import hmac
+import json
 import logging
 
 import requests
 from django.conf import settings
 from django_rq import job
 from jinja2.exceptions import TemplateError
+from rest_framework.utils.encoders import JSONEncoder
 
+from netbox.constants import TEMPLATE_RENDERING_RESTRICTED
 from netbox.registry import registry
 from netbox.settings_utils import parse_job_timeout
+from utilities.jinja2 import get_template_rendering_mode
 from utilities.proxy import resolve_proxies
 from utilities.request import get_safe_request_context
+from utilities.template_objects import to_plain_data
 
 from .constants import WEBHOOK_EVENT_TYPES
 
@@ -68,10 +73,18 @@ def send_webhook(
         context['object_change_ids'] = object_change_ids
 
     # Add any additional context from plugins
+    restricted = get_template_rendering_mode('webhooks') == TEMPLATE_RENDERING_RESTRICTED
     callback_data = {}
     for callback in registry['webhook_callbacks']:
         try:
             if ret := callback(object_type, event_type, data, request):
+                if restricted:
+                    # Reduce the data to plain values, as for the default request body
+                    try:
+                        ret = json.loads(json.dumps(ret, cls=JSONEncoder))
+                    except (TypeError, ValueError) as e:
+                        logger.warning(f"Omitting data from callback {callback}, which can't be serialized: {e}")
+                        continue
                 callback_data.update(**ret)
         except Exception as e:
             logger.warning(f"Caught exception when processing callback {callback}: {e}")
@@ -79,6 +92,10 @@ def send_webhook(
     if callback_data:
         context['context'] = callback_data
 
+    # Restricted rendering permits access only to plain data (e.g. not lazy translation strings or QueryDicts)
+    if restricted:
+        context = to_plain_data(context)
+
     # Build the headers for the HTTP request
     headers = {
         'Content-Type': webhook.http_content_type,
@@ -96,8 +113,14 @@ def send_webhook(
         logger.error(f"Error rendering request body for webhook {webhook}: {e}")
         raise e
 
+    # Render the payload URL
+    try:
+        url = webhook.render_payload_url(context)
+    except TemplateError as e:
+        logger.error(f"Error rendering payload URL for webhook {webhook}: {e}")
+        raise e
+
     # Prepare the HTTP request
-    url = webhook.render_payload_url(context)
     params = {
         'method': webhook.http_method,
         'url': url,

+ 1 - 1
netbox/netbox/constants.py

@@ -30,7 +30,7 @@ TEMPLATE_RENDERING_FEATURES = {
     'config_templates': (TEMPLATE_RENDERING_LEGACY,),
     'custom_links': (TEMPLATE_RENDERING_LEGACY,),
     'export_templates': (TEMPLATE_RENDERING_LEGACY,),
-    'webhooks': (TEMPLATE_RENDERING_LEGACY,),
+    'webhooks': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
 }
 
 # Keys for PostgreSQL advisory locks. These are arbitrary bigints used by the advisory_lock

+ 10 - 6
netbox/utilities/template_objects.py

@@ -1,5 +1,6 @@
 from collections.abc import Mapping
 from copy import deepcopy
+from datetime import date, time
 from decimal import Decimal
 from importlib import import_module
 from types import SimpleNamespace
@@ -34,6 +35,7 @@ __all__ = (
     'get_template_object',
     'get_template_objects',
     'template_json_default',
+    'to_plain_data',
 )
 
 # The number of objects a TemplateObjectList loads at a time
@@ -537,17 +539,19 @@ def _load_objects(queryset, pks, state, cache=False):
 
 
 def _serialize(serializer_class, instance, many=False):
-    return _to_plain_data(serializer_class(instance, many=many, context={'request': None}).data)
+    return to_plain_data(serializer_class(instance, many=many, context={'request': None}).data)
 
 
-def _to_plain_data(value):
+def to_plain_data(value):
     """
-    Convert serializer output to plain dicts, lists, strings, numbers, booleans, and None.
+    Convert serializer output to plain dicts, lists, strings, numbers, booleans, and None, for rendering.
     """
     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]
+        return {key: to_plain_data(item) for key, item in value.items()}
+    if isinstance(value, (list, tuple, set, frozenset)):
+        return [to_plain_data(item) 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):
         return value
     # Anything else (e.g. a lazy translation string) is represented by its string value