Răsfoiți Sursa

Closes #23901: Allow restricted rendering per object

Add a restricted rendering field to config templates, export
templates, custom links, and webhooks. Where TEMPLATE_RENDERING
selects legacy mode for a feature, enabling the field renders that
object in restricted mode, so templates can be converted one at a
time before switching the whole feature. Where restricted mode is
selected, the field has no effect.
Jeremy Stretch 15 ore în urmă
părinte
comite
ea0b5840d0
35 a modificat fișierele cu 379 adăugiri și 103 ștergeri
  1. 2 0
      docs/configuration/system.md
  2. 1 1
      docs/customization/custom-links.md
  3. 1 1
      docs/customization/export-templates.md
  4. 1 1
      docs/features/configuration-rendering.md
  5. 1 1
      docs/integrations/webhooks.md
  6. 5 1
      docs/models/extras/configtemplate.md
  7. 4 0
      docs/models/extras/customlink.md
  8. 4 0
      docs/models/extras/exporttemplate.md
  9. 4 0
      docs/models/extras/webhook.md
  10. 9 0
      netbox/dcim/tests/test_models.py
  11. 2 2
      netbox/extras/api/serializers_/configtemplates.py
  12. 1 1
      netbox/extras/api/serializers_/customlinks.py
  13. 1 1
      netbox/extras/api/serializers_/events.py
  14. 1 1
      netbox/extras/api/serializers_/exporttemplates.py
  15. 4 3
      netbox/extras/filtersets.py
  16. 20 0
      netbox/extras/forms/bulk_edit.py
  17. 5 5
      netbox/extras/forms/bulk_import.py
  18. 35 4
      netbox/extras/forms/filtersets.py
  19. 5 4
      netbox/extras/forms/model_forms.py
  20. 4 0
      netbox/extras/graphql/filters.py
  21. 31 0
      netbox/extras/migrations/0146_restricted_rendering.py
  22. 2 1
      netbox/extras/models/configs.py
  23. 34 13
      netbox/extras/models/mixins.py
  24. 16 15
      netbox/extras/models/models.py
  25. 20 4
      netbox/extras/tables/tables.py
  26. 22 19
      netbox/extras/templatetags/custom_links.py
  27. 8 0
      netbox/extras/tests/test_api.py
  28. 22 1
      netbox/extras/tests/test_event_rules.py
  29. 28 0
      netbox/extras/tests/test_filtersets.py
  30. 7 0
      netbox/extras/tests/test_models.py
  31. 45 0
      netbox/extras/tests/test_templatetags.py
  32. 21 13
      netbox/extras/tests/test_views.py
  33. 4 0
      netbox/extras/ui/panels.py
  34. 1 3
      netbox/extras/webhooks.py
  35. 8 8
      netbox/netbox/tables/columns.py

+ 2 - 0
docs/configuration/system.md

@@ -445,6 +445,8 @@ TEMPLATE_RENDERING = {
 | Export templates | `export_templates` | Yes |
 | Webhooks | `webhooks` | Yes |
 
+Where a feature uses `legacy` mode, individual objects can opt into restricted mode by enabling their restricted rendering field. This allows templates to be converted and checked one at a time, before the whole feature is switched to `restricted` mode. The field has no effect on a feature which uses `restricted` mode: all of its objects are rendered in restricted mode. A template included by another (e.g. with `{% include %}`) is rendered in the mode of the template which includes it.
+
 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"

+ 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
 
-When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for custom links, 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, and the context changes as follows:
 
 | 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
 
-When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for export templates, they're 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, with the following context:
 
 | Variable  | Description |
 |-----------|-------------|

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

@@ -51,7 +51,7 @@ There are {{ dcim.Site.objects.count() }} sites.
 
 #### Restricted Rendering
 
-When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for config templates, 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:
 
 * `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.

+ 1 - 1
docs/integrations/webhooks.md

@@ -49,7 +49,7 @@ 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:
+When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for webhooks, or a webhook has restricted rendering enabled, its 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.

+ 5 - 1
docs/models/extras/configtemplate.md

@@ -49,4 +49,8 @@ The file name to give to the rendered export file (optional).
 The file extension to append to the file name in the response (optional).
 
 ### As Attachment
-If selected, the rendered content will be returned as a file attachment, rather than displayed directly in-browser (where supported).
+If selected, the rendered content will be returned as a file attachment, rather than displayed directly in-browser (where supported).
+
+### Restricted Rendering
+
+If enabled, the template is rendered in [restricted mode](../../features/configuration-rendering.md#restricted-rendering), even where the [`TEMPLATE_RENDERING`](../../configuration/system.md#template_rendering) configuration parameter selects legacy mode. This allows templates to be converted to restricted mode one at a time. Where restricted mode is selected, it applies regardless of this setting.

+ 4 - 0
docs/models/extras/customlink.md

@@ -43,6 +43,10 @@ Jinja2 template code for rendering the button text. (Note that this does not _ne
 
 Jinja2 template code for rendering the hyperlink. See below for available context data.
 
+### Restricted Rendering
+
+If enabled, the link is rendered in [restricted mode](../../customization/custom-links.md#restricted-rendering), even where the [`TEMPLATE_RENDERING`](../../configuration/system.md#template_rendering) configuration parameter selects legacy mode. This allows templates to be converted to restricted mode one at a time. Where restricted mode is selected, it applies regardless of this setting.
+
 ## Context Data
 
 The following context variables are available in to the text and link templates.

+ 4 - 0
docs/models/extras/exporttemplate.md

@@ -51,3 +51,7 @@ The file extension to append to the file name in the response (optional).
 ### As Attachment
 
 If selected, the rendered content will be returned as a file attachment, rather than displayed directly in-browser (where supported).
+
+### Restricted Rendering
+
+If enabled, the template is rendered in [restricted mode](../../customization/export-templates.md#restricted-rendering), even where the [`TEMPLATE_RENDERING`](../../configuration/system.md#template_rendering) configuration parameter selects legacy mode. This allows templates to be converted to restricted mode one at a time. Where restricted mode is selected, it applies regardless of this setting.

+ 4 - 0
docs/models/extras/webhook.md

@@ -100,6 +100,10 @@ The timeout must be less than [`RQ_DEFAULT_TIMEOUT`](../../configuration/miscell
 
 When a request does time out, the failure is recorded by the `netbox.webhooks` logger and the background job is marked as failed.
 
+### Restricted Rendering
+
+If enabled, the webhook is rendered in [restricted mode](../../integrations/webhooks.md#restricted-rendering), even where the [`TEMPLATE_RENDERING`](../../configuration/system.md#template_rendering) configuration parameter selects legacy mode. This allows templates to be converted to restricted mode one at a time. Where restricted mode is selected, it applies regardless of this setting.
+
 ## Context Data
 
 The following context variables are available to the text and link templates.

+ 9 - 0
netbox/dcim/tests/test_models.py

@@ -1773,6 +1773,15 @@ class DeviceRestrictedRenderConfigTestCase(TestCase):
         with self.assertRaises(ValueError):
             self.device.render_config(config_template)
 
+    @override_settings(TEMPLATE_RENDERING={'config_templates': 'legacy'})
+    def test_restricted_template(self):
+        # A template which opts in renders in restricted mode, while others still render in legacy mode
+        template_code = '{{ device.status.value }} {{ dcim is defined }}'
+        config_template = ConfigTemplate.objects.create(name='Template 1', template_code=template_code, restricted=True)
+        self.assertEqual(self.device.render_config(config_template, user=self.superuser), 'active False')
+        config_template = ConfigTemplate.objects.create(name='Template 2', template_code=template_code)
+        self.assertEqual(self.device.render_config(config_template, user=self.superuser), ' True')
+
 
 class DeviceBayTestCase(TestCase):
 

+ 2 - 2
netbox/extras/api/serializers_/configtemplates.py

@@ -36,8 +36,8 @@ class ConfigTemplateSerializer(
         model = ConfigTemplate
         fields = [
             'id', 'url', 'display_url', 'display', 'name', 'description', 'environment_params', 'template_code',
-            'mime_type', 'file_name', 'file_extension', 'as_attachment', 'debug', 'data_source', 'data_path',
-            'data_file', 'auto_sync_enabled', 'data_synced', 'owner', 'tags', 'created', 'last_updated',
+            'mime_type', 'file_name', 'file_extension', 'as_attachment', 'debug', 'restricted', 'data_source',
+            'data_path', 'data_file', 'auto_sync_enabled', 'data_synced', 'owner', 'tags', 'created', 'last_updated',
         ]
         brief_fields = ('id', 'url', 'display', 'name', 'description')
         model_clean_fields = ('data_source', 'data_path', 'auto_sync_enabled', 'data_synced', 'template_code')

+ 1 - 1
netbox/extras/api/serializers_/customlinks.py

@@ -19,6 +19,6 @@ class CustomLinkSerializer(OwnerMixin, ChangeLogMessageSerializer, ValidatedMode
         model = CustomLink
         fields = [
             'id', 'url', 'display_url', 'display', 'object_types', 'name', 'enabled', 'link_text', 'link_url',
-            'weight', 'group_name', 'button_class', 'new_window', 'owner', 'created', 'last_updated',
+            'weight', 'group_name', 'button_class', 'new_window', 'restricted', 'owner', 'created', 'last_updated',
         ]
         brief_fields = ('id', 'url', 'display', 'name')

+ 1 - 1
netbox/extras/api/serializers_/events.py

@@ -65,6 +65,6 @@ class WebhookSerializer(OwnerMixin, NetBoxModelSerializer):
         fields = [
             'id', 'url', 'display_url', 'display', 'name', 'description', 'payload_url', 'http_method',
             'http_content_type', 'additional_headers', 'body_template', 'secret', 'ssl_verification', 'ca_file_path',
-            'timeout', 'custom_fields', 'owner', 'tags', 'created', 'last_updated',
+            'timeout', 'restricted', 'custom_fields', 'owner', 'tags', 'created', 'last_updated',
         ]
         brief_fields = ('id', 'url', 'display', 'name', 'description')

+ 1 - 1
netbox/extras/api/serializers_/exporttemplates.py

@@ -29,7 +29,7 @@ class ExportTemplateSerializer(OwnerMixin, ChangeLogMessageSerializer, Validated
         model = ExportTemplate
         fields = [
             'id', 'url', 'display_url', 'display', 'object_types', 'name', 'description', 'environment_params',
-            'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'data_source',
+            'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'restricted', 'data_source',
             'data_path', 'data_file', 'auto_sync_enabled', 'data_synced', 'owner', 'created', 'last_updated',
         ]
         brief_fields = ('id', 'url', 'display', 'name', 'description')

+ 4 - 3
netbox/extras/filtersets.py

@@ -89,7 +89,7 @@ class WebhookFilterSet(OwnerFilterMixin, NetBoxModelFilterSet):
         model = Webhook
         fields = (
             'id', 'name', 'payload_url', 'http_method', 'http_content_type', 'secret', 'ssl_verification',
-            'ca_file_path', 'timeout', 'description',
+            'ca_file_path', 'timeout', 'restricted', 'description',
         )
 
     def search(self, queryset, name, value):
@@ -280,6 +280,7 @@ class CustomLinkFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet):
         model = CustomLink
         fields = (
             'id', 'name', 'enabled', 'link_text', 'link_url', 'weight', 'group_name', 'new_window', 'button_class',
+            'restricted',
         )
 
     def search(self, queryset, name, value):
@@ -320,7 +321,7 @@ class ExportTemplateFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet):
     class Meta:
         model = ExportTemplate
         fields = (
-            'id', 'name', 'description', 'mime_type', 'file_name', 'file_extension', 'as_attachment',
+            'id', 'name', 'description', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'restricted',
             'auto_sync_enabled', 'data_synced',
         )
 
@@ -902,7 +903,7 @@ class ConfigTemplateFilterSet(OwnerFilterMixin, ChangeLoggedModelFilterSet):
         model = ConfigTemplate
         fields = (
             'id', 'name', 'description', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'debug',
-            'auto_sync_enabled', 'data_synced'
+            'restricted', 'auto_sync_enabled', 'data_synced'
         )
 
     def search(self, queryset, name, value):

+ 20 - 0
netbox/extras/forms/bulk_edit.py

@@ -154,6 +154,11 @@ class CustomLinkBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm):
         choices=add_blank_choice(CustomLinkButtonClassChoices),
         required=False
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=BulkEditNullBooleanSelect()
+    )
 
 
 class ExportTemplateBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm):
@@ -185,6 +190,11 @@ class ExportTemplateBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm
         required=False,
         widget=BulkEditNullBooleanSelect()
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=BulkEditNullBooleanSelect()
+    )
 
     nullable_fields = ('description', 'mime_type', 'file_name', 'file_extension')
 
@@ -285,6 +295,11 @@ class WebhookBulkEditForm(OwnerMixin, NetBoxModelBulkEditForm):
         max_value=3600,
         label=_('Timeout')
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=BulkEditNullBooleanSelect()
+    )
 
     nullable_fields = ('secret', 'ca_file_path', 'timeout')
 
@@ -420,6 +435,11 @@ class ConfigTemplateBulkEditForm(ChangelogMessageMixin, OwnerMixin, BulkEditForm
         required=False,
         widget=BulkEditNullBooleanSelect()
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=BulkEditNullBooleanSelect()
+    )
     auto_sync_enabled = forms.NullBooleanField(
         label=_('Auto sync enabled'),
         required=False,

+ 5 - 5
netbox/extras/forms/bulk_import.py

@@ -169,7 +169,7 @@ class CustomLinkImportForm(OwnerCSVMixin, CSVModelForm):
         model = CustomLink
         fields = (
             'name', 'object_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window', 'link_text',
-            'link_url', 'owner',
+            'link_url', 'restricted', 'owner',
         )
 
 
@@ -208,7 +208,7 @@ class ExportTemplateImportForm(OwnerCSVMixin, CSVModelForm):
         model = ExportTemplate
         fields = (
             'name', 'object_types', 'description', 'environment_params', 'mime_type', 'file_name', 'file_extension',
-            'as_attachment', 'template_code', 'data_source', 'data_file', 'auto_sync_enabled', 'owner',
+            'as_attachment', 'template_code', 'data_source', 'data_file', 'auto_sync_enabled', 'restricted', 'owner',
         )
 
     def clean_data_source(self):
@@ -265,8 +265,8 @@ class ConfigTemplateImportForm(OwnerCSVMixin, CSVModelForm):
         model = ConfigTemplate
         fields = (
             'name', 'description', 'template_code', 'data_source', 'data_file', 'auto_sync_enabled',
-            'environment_params', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'debug', 'owner',
-            'tags',
+            'environment_params', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'debug', 'restricted',
+            'owner', 'tags',
         )
 
     def clean_data_source(self):
@@ -306,7 +306,7 @@ class WebhookImportForm(OwnerCSVMixin, NetBoxModelImportForm):
         model = Webhook
         fields = (
             'name', 'payload_url', 'http_method', 'http_content_type', 'additional_headers', 'body_template',
-            'secret', 'ssl_verification', 'ca_file_path', 'timeout', 'description', 'owner', 'tags'
+            'secret', 'ssl_verification', 'ca_file_path', 'timeout', 'restricted', 'description', 'owner', 'tags'
         )
 
 

+ 35 - 4
netbox/extras/forms/filtersets.py

@@ -164,7 +164,7 @@ class CustomLinkFilterForm(OwnerFilterMixin, SavedFiltersMixin, FilterForm):
     model = CustomLink
     fieldsets = (
         FieldSet('q', 'filter_id'),
-        FieldSet('object_type_id', 'enabled', 'new_window', 'weight', name=_('Attributes')),
+        FieldSet('object_type_id', 'enabled', 'new_window', 'weight', 'restricted', name=_('Attributes')),
         FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
     )
     object_type_id = ContentTypeMultipleChoiceField(
@@ -190,6 +190,13 @@ class CustomLinkFilterForm(OwnerFilterMixin, SavedFiltersMixin, FilterForm):
         label=_('Weight'),
         required=False
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
 
 
 class ExportTemplateFilterForm(OwnerFilterMixin, SavedFiltersMixin, FilterForm):
@@ -197,7 +204,7 @@ class ExportTemplateFilterForm(OwnerFilterMixin, SavedFiltersMixin, FilterForm):
     fieldsets = (
         FieldSet('q', 'filter_id', 'object_type_id'),
         FieldSet('data_source_id', 'data_file_id', name=_('Data')),
-        FieldSet('mime_type', 'file_name', 'file_extension', 'as_attachment', name=_('Rendering')),
+        FieldSet('mime_type', 'file_name', 'file_extension', 'as_attachment', 'restricted', name=_('Rendering')),
         FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
     )
     data_source_id = DynamicModelMultipleChoiceField(
@@ -237,6 +244,13 @@ class ExportTemplateFilterForm(OwnerFilterMixin, SavedFiltersMixin, FilterForm):
             choices=BOOLEAN_WITH_BLANK_CHOICES
         )
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
 
 
 class ImageAttachmentFilterForm(SavedFiltersMixin, FilterForm):
@@ -324,7 +338,8 @@ class WebhookFilterForm(OwnerFilterMixin, NetBoxModelFilterSetForm):
     fieldsets = (
         FieldSet('q', 'filter_id', 'tag'),
         FieldSet(
-            'payload_url', 'http_method', 'http_content_type', 'timeout__gte', 'timeout__lte', name=_('Attributes')
+            'payload_url', 'http_method', 'http_content_type', 'timeout__gte', 'timeout__lte', 'restricted',
+            name=_('Attributes')
         ),
         FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
     )
@@ -351,6 +366,13 @@ class WebhookFilterForm(OwnerFilterMixin, NetBoxModelFilterSetForm):
         min_value=1,
         label=_('Maximum timeout (seconds)')
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
     tag = TagFilterField(model)
 
 
@@ -540,7 +562,9 @@ class ConfigTemplateFilterForm(OwnerFilterMixin, SavedFiltersMixin, FilterForm):
     fieldsets = (
         FieldSet('q', 'filter_id', 'tag'),
         FieldSet('data_source_id', 'data_file_id', 'auto_sync_enabled', name=_('Data')),
-        FieldSet('mime_type', 'file_name', 'file_extension', 'as_attachment', 'debug', name=_('Rendering')),
+        FieldSet(
+            'mime_type', 'file_name', 'file_extension', 'as_attachment', 'debug', 'restricted', name=_('Rendering')
+        ),
         FieldSet('owner_group_id', 'owner_id', name=_('Ownership')),
     )
     data_source_id = DynamicModelMultipleChoiceField(
@@ -590,6 +614,13 @@ class ConfigTemplateFilterForm(OwnerFilterMixin, SavedFiltersMixin, FilterForm):
             choices=BOOLEAN_WITH_BLANK_CHOICES
         )
     )
+    restricted = forms.NullBooleanField(
+        label=_('Restricted rendering'),
+        required=False,
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
 
 
 class LocalConfigContextFilterForm(forms.Form):

+ 5 - 4
netbox/extras/forms/model_forms.py

@@ -353,7 +353,7 @@ class CustomLinkForm(ChangelogMessageMixin, OwnerMixin, forms.ModelForm):
             'name', 'object_types', 'weight', 'group_name', 'button_class', 'enabled', 'new_window',
             name=_('Custom Link')
         ),
-        FieldSet('link_text', 'link_url', name=_('Templates')),
+        FieldSet('link_text', 'link_url', 'restricted', name=_('Templates')),
     )
 
     class Meta:
@@ -389,7 +389,8 @@ class ExportTemplateForm(ChangelogMessageMixin, SyncedDataMixin, OwnerMixin, for
         FieldSet('name', 'object_types', 'description', 'template_code', name=_('Export Template')),
         FieldSet('data_source', 'data_file', 'auto_sync_enabled', name=_('Data Source')),
         FieldSet(
-            'mime_type', 'file_name', 'file_extension', 'environment_params', 'as_attachment', name=_('Rendering')
+            'mime_type', 'file_name', 'file_extension', 'environment_params', 'as_attachment', 'restricted',
+            name=_('Rendering')
         ),
     )
 
@@ -581,7 +582,7 @@ class WebhookForm(OwnerMixin, NetBoxModelForm):
         FieldSet('name', 'description', 'tags', name=_('Webhook')),
         FieldSet(
             'payload_url', 'http_method', 'http_content_type', 'additional_headers', 'body_template', 'secret',
-            'timeout', name=_('HTTP Request')
+            'timeout', 'restricted', name=_('HTTP Request')
         ),
         FieldSet('ssl_verification', 'ca_file_path', name=_('SSL')),
     )
@@ -868,7 +869,7 @@ class ConfigTemplateForm(ChangelogMessageMixin, SyncedDataMixin, OwnerMixin, for
         FieldSet('name', 'description', 'tags', 'template_code', name=_('Config Template')),
         FieldSet('data_source', 'data_file', 'auto_sync_enabled', name=_('Data Source')),
         FieldSet(
-            'mime_type', 'file_name', 'file_extension', 'environment_params', 'as_attachment', 'debug',
+            'mime_type', 'file_name', 'file_extension', 'environment_params', 'as_attachment', 'debug', 'restricted',
             name=_('Rendering')
         ),
     )

+ 4 - 0
netbox/extras/graphql/filters.py

@@ -135,6 +135,7 @@ class ConfigTemplateFilter(SyncedDataFilterMixin, ChangeLoggedModelFilter):
     file_name: StrFilterLookup | None = strawberry_django.filter_field()
     file_extension: StrFilterLookup | None = strawberry_django.filter_field()
     as_attachment: FilterLookup[bool] | None = strawberry_django.filter_field()
+    restricted: FilterLookup[bool] | None = strawberry_django.filter_field()
 
 
 @register_filter(models.CustomField, lookups=True)
@@ -258,6 +259,7 @@ class CustomLinkFilter(ChangeLoggedModelFilter):
         strawberry_django.filter_field()
     )
     new_window: FilterLookup[bool] | None = strawberry_django.filter_field()
+    restricted: FilterLookup[bool] | None = strawberry_django.filter_field()
 
 
 @register_filter(models.ExportTemplate, lookups=True)
@@ -272,6 +274,7 @@ class ExportTemplateFilter(SyncedDataFilterMixin, ChangeLoggedModelFilter):
     file_name: StrFilterLookup | None = strawberry_django.filter_field()
     file_extension: StrFilterLookup | None = strawberry_django.filter_field()
     as_attachment: FilterLookup[bool] | None = strawberry_django.filter_field()
+    restricted: FilterLookup[bool] | None = strawberry_django.filter_field()
 
 
 @register_filter(models.ImageAttachment, lookups=True)
@@ -400,6 +403,7 @@ class WebhookFilter(CustomFieldsFilterMixin, TagsFilterMixin, ChangeLoggedModelF
     ssl_verification: FilterLookup[bool] | None = strawberry_django.filter_field()
     ca_file_path: StrFilterLookup | None = strawberry_django.filter_field()
     timeout: FilterLookup[int] | None = strawberry_django.filter_field()
+    restricted: FilterLookup[bool] | None = strawberry_django.filter_field()
     events: Annotated['EventRuleFilter', strawberry.lazy('extras.graphql.filters')] | None = (
         strawberry_django.filter_field()
     )

+ 31 - 0
netbox/extras/migrations/0146_restricted_rendering.py

@@ -0,0 +1,31 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('extras', '0145_taggeditem_object_id_bigint'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='configtemplate',
+            name='restricted',
+            field=models.BooleanField(default=False),
+        ),
+        migrations.AddField(
+            model_name='customlink',
+            name='restricted',
+            field=models.BooleanField(default=False),
+        ),
+        migrations.AddField(
+            model_name='exporttemplate',
+            name='restricted',
+            field=models.BooleanField(default=False),
+        ),
+        migrations.AddField(
+            model_name='webhook',
+            name='restricted',
+            field=models.BooleanField(default=False),
+        ),
+    ]

+ 2 - 1
netbox/extras/models/configs.py

@@ -14,7 +14,7 @@ from django.utils.translation import gettext_lazy as _
 from jinja2.exceptions import TemplateError
 from jsonschema.exceptions import ValidationError as JSONValidationError
 
-from extras.models.mixins import RenderTemplateMixin
+from extras.models.mixins import RenderTemplateMixin, RestrictedRenderingMixin
 from extras.querysets import ConfigContextQuerySet
 from netbox.models import ChangeLoggedModel, PrimaryModel
 from netbox.models.features import CloningMixin, CustomLinksMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin
@@ -428,6 +428,7 @@ class ConfigContextModel(models.Model):
 #
 
 class ConfigTemplate(
+    RestrictedRenderingMixin,
     RenderTemplateMixin,
     SyncedDataMixin,
     CustomLinksMixin,

+ 34 - 13
netbox/extras/models/mixins.py

@@ -28,6 +28,7 @@ from utilities.jinja2 import RestrictedRenderState, get_template_rendering_mode,
 __all__ = (
     'PythonModuleMixin',
     'RenderTemplateMixin',
+    'RestrictedRenderingMixin',
 )
 
 logger = logging.getLogger(__name__)
@@ -101,7 +102,39 @@ class PythonModuleMixin:
         return module
 
 
-class RenderTemplateMixin(models.Model):
+class TemplateRenderingModeMixin:
+    """
+    Determines whether an object's templates render in restricted mode.
+    """
+    # The TEMPLATE_RENDERING feature which governs this model's rendering (set by subclasses)
+    template_rendering_feature = None
+
+    def uses_restricted_rendering(self):
+        """
+        Return True if this object renders in restricted mode: either it's opted in (see RestrictedRenderingMixin), or
+        TEMPLATE_RENDERING selects restricted mode for its feature.
+        """
+        return getattr(self, 'restricted', False) or (
+            self.template_rendering_feature is not None and
+            get_template_rendering_mode(self.template_rendering_feature) == TEMPLATE_RENDERING_RESTRICTED
+        )
+
+
+class RestrictedRenderingMixin(TemplateRenderingModeMixin, models.Model):
+    """
+    Enables opting an object into restricted template rendering where TEMPLATE_RENDERING selects legacy mode.
+    """
+    restricted = models.BooleanField(
+        verbose_name=_('restricted rendering'),
+        default=False,
+        help_text=_('Render in restricted mode, even where legacy mode is configured')
+    )
+
+    class Meta:
+        abstract = True
+
+
+class RenderTemplateMixin(TemplateRenderingModeMixin, models.Model):
     """
     Enables support for rendering templates.
     """
@@ -141,21 +174,9 @@ class RenderTemplateMixin(models.Model):
         help_text=_("Download file as attachment")
     )
 
-    # The TEMPLATE_RENDERING feature which governs this model's rendering (set by subclasses)
-    template_rendering_feature = None
-
     class Meta:
         abstract = True
 
-    def uses_restricted_rendering(self):
-        """
-        Return True if TEMPLATE_RENDERING selects restricted mode for this model's templates.
-        """
-        return (
-            self.template_rendering_feature is not None and
-            get_template_rendering_mode(self.template_rendering_feature) == TEMPLATE_RENDERING_RESTRICTED
-        )
-
     def get_context(self, context=None, queryset=None, user=None):
         _context = defaultdict(dict)
 

+ 16 - 15
netbox/extras/models/models.py

@@ -23,11 +23,10 @@ from rest_framework.utils.encoders import JSONEncoder
 from extras.choices import *
 from extras.conditions import ConditionSet, InvalidCondition
 from extras.constants import *
-from extras.models.mixins import RenderTemplateMixin
+from extras.models.mixins import RenderTemplateMixin, RestrictedRenderingMixin
 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
@@ -46,7 +45,6 @@ from utilities.html import clean_html
 from utilities.jinja2 import (
     JINJA2_TEMPLATE_RE,
     RestrictedRenderState,
-    get_template_rendering_mode,
     render_jinja2,
     sanitize_http_header,
     validate_jinja2_syntax,
@@ -219,7 +217,9 @@ class EventRule(CustomFieldsMixin, ExportTemplatesMixin, OwnerMixin, TagsMixin,
             return False
 
 
-class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, ChangeLoggedModel):
+class Webhook(
+    RestrictedRenderingMixin, CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, ChangeLoggedModel
+):
     """
     A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
     delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
@@ -325,6 +325,8 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, Ch
         object_id_field='action_object_id'
     )
 
+    template_rendering_feature = 'webhooks'
+
     class Meta:
         ordering = ('name',)
         verbose_name = _('webhook')
@@ -425,17 +427,16 @@ class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, Ch
         """
         return render_jinja2(self.payload_url, context, restricted=self._get_render_state())
 
-    @staticmethod
-    def _get_render_state():
+    def _get_render_state(self):
         """
-        Return the state for rendering webhook templates in restricted mode, or None if it isn't selected.
+        Return the state for rendering the webhook's templates in restricted mode, or None if it doesn't use it.
         """
-        if get_template_rendering_mode('webhooks') == TEMPLATE_RENDERING_RESTRICTED:
+        if self.uses_restricted_rendering():
             return RestrictedRenderState()
         return None
 
 
-class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel):
+class CustomLink(RestrictedRenderingMixin, CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel):
     """
     A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
     code to be rendered with an object as context.
@@ -486,9 +487,11 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMod
     )
 
     clone_fields = (
-        'object_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window',
+        'object_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window', 'restricted',
     )
 
+    template_rendering_feature = 'custom_links'
+
     class Meta:
         ordering = ['group_name', 'weight', 'name']
         indexes = (
@@ -510,11 +513,8 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMod
     @staticmethod
     def get_render_state(request):
         """
-        Return the state for rendering custom links in restricted mode on behalf of the request's user, or None if
-        restricted mode isn't selected.
+        Return the state for rendering custom links in restricted mode on behalf of the request's user.
         """
-        if get_template_rendering_mode('custom_links') != TEMPLATE_RENDERING_RESTRICTED:
-            return None
         # Render on behalf of the request's user, or an anonymous user if it has none
         user = None if request is None else getattr(request, 'user', None) or AnonymousUser()
         # Links render for every row of a table, so cap the objects a query() can return
@@ -582,6 +582,7 @@ def _get_user_data(user):
 
 
 class ExportTemplate(
+    RestrictedRenderingMixin,
     SyncedDataMixin,
     CloningMixin,
     ExportTemplatesMixin,
@@ -605,7 +606,7 @@ class ExportTemplate(
     )
 
     clone_fields = (
-        'object_types', 'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment',
+        'object_types', 'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment', 'restricted',
     )
 
     template_rendering_feature = 'export_templates'

+ 20 - 4
netbox/extras/tables/tables.py

@@ -204,6 +204,10 @@ class CustomLinkTable(NetBoxTable):
         verbose_name=_('New Window'),
         false_mark=None
     )
+    restricted = columns.BooleanColumn(
+        verbose_name=_('Restricted Rendering'),
+        false_mark=None
+    )
     owner = tables.Column(
         linkify=True,
         verbose_name=_('Owner')
@@ -213,7 +217,7 @@ class CustomLinkTable(NetBoxTable):
         model = CustomLink
         fields = (
             'pk', 'id', 'name', 'object_types', 'enabled', 'link_text', 'link_url', 'weight', 'group_name',
-            'button_class', 'new_window', 'created', 'last_updated',
+            'button_class', 'new_window', 'restricted', 'created', 'last_updated',
         )
         default_columns = ('pk', 'name', 'object_types', 'enabled', 'group_name', 'button_class', 'new_window')
 
@@ -239,6 +243,10 @@ class ExportTemplateTable(NetBoxTable):
         verbose_name=_('As Attachment'),
         false_mark=None
     )
+    restricted = columns.BooleanColumn(
+        verbose_name=_('Restricted Rendering'),
+        false_mark=None
+    )
     data_source = tables.Column(
         verbose_name=_('Data Source'),
         linkify=True
@@ -260,7 +268,7 @@ class ExportTemplateTable(NetBoxTable):
         model = ExportTemplate
         fields = (
             'pk', 'id', 'name', 'object_types', 'description', 'mime_type', 'file_name', 'file_extension',
-            'as_attachment', 'data_source', 'data_file', 'data_synced', 'created', 'last_updated',
+            'as_attachment', 'restricted', 'data_source', 'data_file', 'data_synced', 'created', 'last_updated',
         )
         default_columns = (
             'pk', 'name', 'object_types', 'description', 'mime_type', 'file_name', 'file_extension',
@@ -499,6 +507,10 @@ class WebhookTable(NetBoxTable):
     timeout = tables.Column(
         verbose_name=_('Timeout (sec)'),
     )
+    restricted = columns.BooleanColumn(
+        verbose_name=_('Restricted Rendering'),
+        false_mark=None
+    )
     owner = tables.Column(
         linkify=True,
         verbose_name=_('Owner')
@@ -511,7 +523,7 @@ class WebhookTable(NetBoxTable):
         model = Webhook
         fields = (
             'pk', 'id', 'name', 'http_method', 'payload_url', 'http_content_type', 'secret', 'ssl_verification',
-            'ca_file_path', 'timeout', 'description', 'tags', 'created', 'last_updated',
+            'ca_file_path', 'timeout', 'restricted', 'description', 'tags', 'created', 'last_updated',
         )
         default_columns = (
             'pk', 'name', 'http_method', 'payload_url', 'description',
@@ -732,6 +744,10 @@ class ConfigTemplateTable(NetBoxTable):
         verbose_name=_('Debug'),
         false_mark=None
     )
+    restricted = columns.BooleanColumn(
+        verbose_name=_('Restricted Rendering'),
+        false_mark=None
+    )
     owner = tables.Column(
         linkify=True,
         verbose_name=_('Owner')
@@ -764,7 +780,7 @@ class ConfigTemplateTable(NetBoxTable):
         model = ConfigTemplate
         fields = (
             'pk', 'id', 'name', 'description', 'data_source', 'data_file', 'data_synced', 'as_attachment', 'debug',
-            'mime_type', 'file_name', 'file_extension', 'role_count', 'platform_count', 'device_count',
+            'restricted', 'mime_type', 'file_name', 'file_extension', 'role_count', 'platform_count', 'device_count',
             'vm_count', 'created', 'last_updated', 'tags',
         )
         default_columns = (

+ 22 - 19
netbox/extras/templatetags/custom_links.py

@@ -40,29 +40,32 @@ def custom_links(context, obj):
     if not custom_links:
         return ''
 
-    # Pass select context data when rendering the CustomLink
-    render_state = CustomLink.get_render_state(context['request'])
-    context_error = None
-    if render_state is None:
-        link_context = {
-            'object': obj,
-            'debug': context.get('debug', False),  # django.template.context_processors.debug
-            'request': get_safe_request_context(context['request']),  # Sanitized subset of the request
-            'user': context['user'],  # django.contrib.auth.context_processors.auth
-            'perms': context['perms'],  # django.contrib.auth.context_processors.auth
-        }
-    else:
-        try:
-            link_context = CustomLink.get_restricted_context(
-                obj, render_state, context['request'], debug=context.get('debug', False)
-            )
-        except Exception as e:
-            link_context, context_error = None, e
+    # Pass select context data when rendering the CustomLink. Each context is built only if a link renders in its mode.
+    legacy_context = render_state = restricted_context = context_error = None
 
     def render_link(cl):
+        nonlocal legacy_context, render_state, restricted_context, context_error
+        if not cl.uses_restricted_rendering():
+            if legacy_context is None:
+                legacy_context = {
+                    'object': obj,
+                    'debug': context.get('debug', False),  # django.template.context_processors.debug
+                    'request': get_safe_request_context(context['request']),  # Sanitized subset of the request
+                    'user': context['user'],  # django.contrib.auth.context_processors.auth
+                    'perms': context['perms'],  # django.contrib.auth.context_processors.auth
+                }
+            return cl.render(legacy_context)
+        if render_state is None:
+            render_state = CustomLink.get_render_state(context['request'])
+            try:
+                restricted_context = CustomLink.get_restricted_context(
+                    obj, render_state, context['request'], debug=context.get('debug', False)
+                )
+            except Exception as e:
+                context_error = e
         if context_error is not None:
             raise context_error
-        return cl.render(link_context, restricted=render_state)
+        return cl.render(restricted_context, restricted=render_state)
 
     template_code = ''
     group_names = {}

+ 8 - 0
netbox/extras/tests/test_api.py

@@ -72,11 +72,13 @@ class WebhookTestCase(APIViewTestCases.APIViewTestCase):
         {
             'name': 'Webhook 6',
             'payload_url': 'http://example.com/?6',
+            'restricted': True,
         },
     ]
     bulk_update_data = {
         'description': 'New description',
         'ssl_verification': False,
+        'restricted': True,
     }
     bulk_update_invalid_data = {
         'http_method': 'not-a-valid-http-method',
@@ -633,11 +635,13 @@ class CustomLinkTestCase(APIViewTestCases.APIViewTestCase):
             'enabled': False,
             'link_text': 'Link 6',
             'link_url': 'http://example.com/?6',
+            'restricted': True,
         },
     ]
     bulk_update_data = {
         'new_window': True,
         'enabled': False,
+        'restricted': True,
     }
     bulk_update_invalid_data = {
         'button_class': 'not-a-valid-button-class',
@@ -1030,10 +1034,12 @@ class ExportTemplateTestCase(APIViewTestCases.APIViewTestCase):
             'name': 'Test Export Template 6',
             'template_code': '{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
             'file_name': 'test_export_template_6',
+            'restricted': True,
         },
     ]
     bulk_update_data = {
         'description': 'New description',
+        'restricted': True,
     }
     bulk_update_invalid_data = {
         'object_types': ['dcim.notamodel'],
@@ -2074,10 +2080,12 @@ class ConfigTemplateTestCase(APIViewTestCases.APIViewTestCase):
         {
             'name': 'Config Template 6',
             'template_code': 'Baz: {{ baz }}',
+            'restricted': True,
         },
     ]
     bulk_update_data = {
         'description': 'New description',
+        'restricted': True,
     }
     bulk_update_invalid_data = {
         'data_source': 99999,

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

@@ -2080,6 +2080,27 @@ class WebhookRestrictedRenderingTest(TestCase):
             webhook.render_body({'data': Site(name='Site 1')})
 
     def test_send_webhook(self):
+        self.assert_send_webhook(self.event_rule)
+
+    @override_settings(TEMPLATE_RENDERING={'webhooks': 'legacy'})
+    def test_send_restricted_webhook(self):
+        # A webhook which opts in is sent as in restricted mode
+        Webhook.objects.filter(pk=self.webhook.pk).update(restricted=True)
+        self.assert_send_webhook(EventRule.objects.get(pk=self.event_rule.pk))
+
+    @override_settings(TEMPLATE_RENDERING={'webhooks': 'legacy'})
+    def test_restricted_webhook(self):
+        # A webhook which opts in renders in restricted mode, while others still render in legacy mode
+        context = {'data': Site(name='Site 1')}
+        webhook = Webhook(
+            name='Webhook 2', payload_url='http://localhost:9000/', body_template='{{ data.name }}', restricted=True
+        )
+        with self.assertRaises(SecurityError):
+            webhook.render_body(context)
+        webhook.restricted = False
+        self.assertEqual(webhook.render_body(context), 'Site 1')
+
+    def assert_send_webhook(self, event_rule):
         def plain_callback(object_type, event_type, data, request):
             return {'plugin': {'foo': 'bar'}}
 
@@ -2101,7 +2122,7 @@ class WebhookRestrictedRenderingTest(TestCase):
             self.assertLogs('netbox.webhooks', level='WARNING') as logs,
         ):
             send_webhook(
-                event_rule=self.event_rule,
+                event_rule=event_rule,
                 object_type=ObjectType.objects.get_for_model(Site),
                 event_type=OBJECT_CREATED,
                 data=serialize_for_event(self.site),

+ 28 - 0
netbox/extras/tests/test_filtersets.py

@@ -252,6 +252,7 @@ class WebhookTestCase(TestCase, BaseFilterSetTestMixin):
                 http_method='PATCH',
                 ssl_verification=False,
                 timeout=30,
+                restricted=True,
                 description='foobar3'
             ),
             Webhook(
@@ -289,6 +290,12 @@ class WebhookTestCase(TestCase, BaseFilterSetTestMixin):
         params = {'ssl_verification': True}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
+    def test_restricted(self):
+        params = {'restricted': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'restricted': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 4)
+
     def test_timeout(self):
         params = {'timeout': [10, 20]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
@@ -495,6 +502,7 @@ class CustomLinkTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 enabled=False,
                 weight=300,
                 new_window=True,
+                restricted=True,
                 link_text='Link 1',
                 link_url='http://example.com/?3'
             ),
@@ -527,6 +535,12 @@ class CustomLinkTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'enabled': False}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
 
+    def test_restricted(self):
+        params = {'restricted': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'restricted': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
     def test_new_window(self):
         params = {'new_window': False}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
@@ -753,6 +767,7 @@ class ExportTemplateTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 file_name='baz',
                 file_extension='baz',
                 as_attachment=False,
+                restricted=True,
                 data_file=data_files[2],
             ),
         )
@@ -790,6 +805,12 @@ class ExportTemplateTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'file_extension': ['foo', 'bar']}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
+    def test_restricted(self):
+        params = {'restricted': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'restricted': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
     def test_as_attachment(self):
         params = {'as_attachment': True}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
@@ -1414,6 +1435,7 @@ class ConfigTemplateTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 file_name='baz',
                 file_extension='baz',
                 as_attachment=False,
+                restricted=True,
                 data_file=data_files[2],
             ),
         )
@@ -1443,6 +1465,12 @@ class ConfigTemplateTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'file_extension': ['foo', 'bar']}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
 
+    def test_restricted(self):
+        params = {'restricted': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'restricted': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
     def test_as_attachment(self):
         params = {'as_attachment': True}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)

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

@@ -1714,6 +1714,13 @@ class ExportTemplateRestrictedRenderTestCase(TestCase):
         response = t.render_to_response(queryset=Site.objects.all(), user=self.user)
         self.assertNotIn('Content-Security-Policy', response)
 
+    @override_settings(TEMPLATE_RENDERING={'export_templates': 'legacy'})
+    def test_restricted_template(self):
+        # A template which opts in renders in restricted mode, while others still render in legacy mode
+        template_code = '{{ objects | length }} {{ queryset is defined }} {{ dcim is defined }}'
+        self.assertEqual(self.render(template_code, restricted=True), '2 False False')
+        self.assertEqual(self.render(template_code), '2 True True')
+
     @override_settings(TEMPLATE_RENDERING={'export_templates': 'legacy'})
     def test_legacy_context(self):
         output = self.render(

+ 45 - 0
netbox/extras/tests/test_templatetags.py

@@ -237,6 +237,45 @@ class CustomLinkRenderErrorEscapingTest(TestCase):
         self.assertIn(escape(self.XSS_PAYLOAD), rendered)
 
 
+class CustomLinkRestrictedOptInTest(TestCase):
+    """
+    In legacy mode, a custom link which opts in renders in restricted mode, while others still render in legacy mode.
+    """
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.site = Site.objects.create(name='Site 1', slug='site-1')
+        cls.user = User.objects.create_superuser(username='admin')
+        site_type = ObjectType.objects.get_for_model(Site)
+        for name, restricted in (('Legacy', False), ('Restricted', True)):
+            custom_link = CustomLink.objects.create(
+                name=name,
+                link_text=f'{name} {{{{ object.cf is defined }}}}',
+                link_url='http://example.com/',
+                restricted=restricted,
+            )
+            custom_link.object_types.set([site_type])
+
+    def get_request(self):
+        request = RequestFactory().get('/dcim/sites/')
+        request.user = self.user
+        return request
+
+    def test_template_tag(self):
+        request = self.get_request()
+        output = custom_links({'request': request, 'user': request.user, 'perms': PermWrapper(request.user)}, self.site)
+        self.assertIn('>Legacy True</a>', output)
+        self.assertIn('>Restricted False</a>', output)
+
+    def test_table(self):
+        table = SiteTable(Site.objects.all())
+        table.context = {'request': self.get_request()}
+        table.paginate(per_page=10)
+        row = table.page.object_list[0]
+        self.assertIn('>Legacy True</a>', row.get_cell('cl_Legacy'))
+        self.assertIn('>Restricted False</a>', row.get_cell('cl_Restricted'))
+
+
 @override_settings(TEMPLATE_RENDERING={'custom_links': 'restricted'})
 class CustomLinkRestrictedRenderingTest(TestCase):
 
@@ -286,6 +325,12 @@ class CustomLinkRestrictedRenderingTest(TestCase):
                 finally:
                     CustomLink.objects.all().delete()
 
+    def test_context_without_auth_processor(self):
+        # Restricted links don't depend on the user and perms provided by the auth context processor
+        custom_link = CustomLink.objects.create(name='Link 1', link_text='{{ user.username }}', link_url='/')
+        custom_link.object_types.set([ObjectType.objects.get_for_model(Site)])
+        self.assertIn('>user1</a>', custom_links({'request': self.get_request()}, self.sites[0]))
+
     def test_permission_in_unpermitted_app(self):
         output = self.render_link('{% if perms.circuits.view_circuit %}yes{% else %}no{% endif %}')
         self.assertIn('>no</a>', output)

+ 21 - 13
netbox/extras/tests/test_views.py

@@ -167,14 +167,15 @@ class CustomLinkTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             'weight': 100,
             'button_class': CustomLinkButtonClassChoices.DEFAULT,
             'link_text': 'Link X',
-            'link_url': 'http://example.com/?x'
+            'link_url': 'http://example.com/?x',
+            'restricted': True,
         }
 
         cls.csv_data = (
-            "name,object_types,enabled,weight,button_class,link_text,link_url",
-            "Custom Link 4,dcim.site,True,100,blue,Link 4,http://exmaple.com/?4",
-            "Custom Link 5,dcim.site,True,100,blue,Link 5,http://exmaple.com/?5",
-            "Custom Link 6,dcim.site,False,100,blue,Link 6,http://exmaple.com/?6",
+            "name,object_types,enabled,weight,button_class,link_text,link_url,restricted",
+            "Custom Link 4,dcim.site,True,100,blue,Link 4,http://exmaple.com/?4,True",
+            "Custom Link 5,dcim.site,True,100,blue,Link 5,http://exmaple.com/?5,False",
+            "Custom Link 6,dcim.site,False,100,blue,Link 6,http://exmaple.com/?6,",
         )
 
         cls.csv_update_data = (
@@ -188,6 +189,7 @@ class CustomLinkTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             'button_class': CustomLinkButtonClassChoices.CYAN,
             'enabled': False,
             'weight': 200,
+            'restricted': True,
         }
 
 
@@ -661,14 +663,15 @@ class ExportTemplateTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             'template_code': TEMPLATE_CODE,
             'environment_params': ENVIRONMENT_PARAMS,
             'file_name': 'template_x',
+            'restricted': True,
         }
 
         cls.csv_data = {
             'default': (
-                "name,object_types,template_code,file_name",
-                f"Export Template 4,dcim.site,{TEMPLATE_CODE},",
-                f"Export Template 5,dcim.site,{TEMPLATE_CODE},template_5",
-                f"Export Template 6,dcim.site,{TEMPLATE_CODE},",
+                "name,object_types,template_code,file_name,restricted",
+                f"Export Template 4,dcim.site,{TEMPLATE_CODE},,True",
+                f"Export Template 5,dcim.site,{TEMPLATE_CODE},template_5,False",
+                f"Export Template 6,dcim.site,{TEMPLATE_CODE},,",
             ),
             'with_data_file': (
                 "name,object_types,data_file,auto_sync_enabled",
@@ -691,6 +694,7 @@ class ExportTemplateTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             'mime_type': 'text/html',
             'file_extension': 'html',
             'as_attachment': True,
+            'restricted': True,
         }
 
     def test_bulk_import_objects_with_permission(self):
@@ -889,14 +893,15 @@ class WebhookTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             'http_method': 'GET',
             'http_content_type': 'application/foo',
             'timeout': 45,
+            'restricted': True,
             'description': 'My webhook',
         }
 
         cls.csv_data = (
-            "name,payload_url,http_method,http_content_type,timeout,description",
-            "Webhook 4,http://example.com/?4,GET,application/json,15,Foo",
-            "Webhook 5,http://example.com/?5,GET,application/json,,Bar",
-            "Webhook 6,http://example.com/?6,GET,application/json,,Baz",
+            "name,payload_url,http_method,http_content_type,timeout,restricted,description",
+            "Webhook 4,http://example.com/?4,GET,application/json,15,True,Foo",
+            "Webhook 5,http://example.com/?5,GET,application/json,,False,Bar",
+            "Webhook 6,http://example.com/?6,GET,application/json,,,Baz",
         )
 
         cls.csv_update_data = (
@@ -909,6 +914,7 @@ class WebhookTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         cls.bulk_edit_data = {
             'http_method': 'GET',
             'timeout': 60,
+            'restricted': True,
         }
 
 
@@ -1213,6 +1219,7 @@ class ConfigTemplateTestCase(
             'template_code': TEMPLATE_CODE,
             'environment_params': ENVIRONMENT_PARAMS,
             'file_name': 'config_x',
+            'restricted': True,
         }
 
         cls.csv_update_data = (
@@ -1228,6 +1235,7 @@ class ConfigTemplateTestCase(
             'file_name': 'output',
             'file_extension': 'html',
             'as_attachment': True,
+            'restricted': True,
         }
 
     def test_content_is_not_cacheable(self):

+ 4 - 0
netbox/extras/ui/panels.py

@@ -227,6 +227,7 @@ class CustomLinkPanel(panels.ObjectAttributesPanel):
     weight = attrs.NumericAttr('weight')
     button_class = attrs.ChoiceAttr('button_class')
     new_window = attrs.BooleanAttr('new_window')
+    restricted = attrs.BooleanAttr('restricted', label=_('Restricted rendering'))
 
 
 #
@@ -242,6 +243,7 @@ class ExportTemplatePanel(panels.ObjectAttributesPanel):
     file_name = attrs.TextAttr('file_name')
     file_extension = attrs.TextAttr('file_extension')
     as_attachment = attrs.BooleanAttr('as_attachment', label=_('Attachment'))
+    restricted = attrs.BooleanAttr('restricted', label=_('Restricted rendering'))
 
 
 #
@@ -354,6 +356,7 @@ class WebhookHTTPPanel(panels.ObjectAttributesPanel):
     http_content_type = attrs.TextAttr('http_content_type', label=_('HTTP content type'))
     secret = attrs.TextAttr('secret')
     timeout = WebhookTimeoutAttr('timeout')
+    restricted = attrs.BooleanAttr('restricted', label=_('Restricted rendering'))
 
 
 class WebhookSSLPanel(panels.ObjectAttributesPanel):
@@ -481,6 +484,7 @@ class ConfigTemplatePanel(panels.ObjectAttributesPanel):
     file_extension = attrs.TextAttr('file_extension')
     as_attachment = attrs.BooleanAttr('as_attachment', label=_('Attachment'))
     debug = attrs.BooleanAttr('debug')
+    restricted = attrs.BooleanAttr('restricted', label=_('Restricted rendering'))
     data_source = attrs.RelatedObjectAttr('data_source', linkify=True)
     data_file = attrs.TemplatedAttr(
         'data_path',

+ 1 - 3
netbox/extras/webhooks.py

@@ -9,10 +9,8 @@ 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_template_data
@@ -73,7 +71,7 @@ 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
+    restricted = webhook.uses_restricted_rendering()
     callback_data = {}
     for callback in registry['webhook_callbacks']:
         try:

+ 8 - 8
netbox/netbox/tables/columns.py

@@ -724,14 +724,14 @@ class CustomLinkColumn(tables.Column):
         # A table rendered in a template has a context, while one being exported has only the request it was
         # configured for
         request = getattr(table, 'context', {}).get('request') or getattr(table, 'request', None)
-        # Share the render state, and the objects serialized for it, among all of the table's custom link columns.
-        # Retain them only for the request they were created for.
-        cached_request, state, objects = getattr(table, '_custom_link_render_state', (None, None, None))
-        if request is None or cached_request is not request:
-            state, objects = self.customlink.get_render_state(request), {}
-            if request is not None:
-                table._custom_link_render_state = (request, state, objects)
-        if state is not None:
+        if self.customlink.uses_restricted_rendering():
+            # Share the render state, and the objects serialized for it, among all of the table's custom link columns
+            # which render in restricted mode. Retain them only for the request they were created for.
+            cached_request, state, objects = getattr(table, '_custom_link_render_state', (None, None, None))
+            if request is None or cached_request is not request:
+                state, objects = self.customlink.get_render_state(request), {}
+                if request is not None:
+                    table._custom_link_render_state = (request, state, objects)
             obj = self._get_template_object(record, table, state, objects)
             context = self.customlink.get_restricted_context(obj, state, request, debug=settings.DEBUG)
             return self.customlink.render(context, restricted=state)