فهرست منبع

Closes #23502: Support Content-Security-Policy and Permissions-Policy response headers (#23698)

* Fixes #23502: Add SECURE_CSP and SECURE_CSP_REPORT_ONLY configuration parameters

Pass both through to Django's settings of the same names, enable Django's
ContentSecurityPolicyMiddleware directly after SecurityMiddleware, and add
the csp context processor so templates can read the per-request nonce as
csp_nonce. Both parameters default to an empty dict, which sends no header.

* Fixes #23502: Nonce every script NetBox renders

Add nonce="{{ csp_nonce }}" to every <script> in base.html, both token edit
pages and GraphiQL, so NetBox runs under a nonce-based policy without
'unsafe-inline'. Replace the four onerror attributes on core static assets
with one capture-phase error listener, placed first in <head>, that
redirects to the media failure page for assets marked data-media-failure.
A regression test asserts every <script> carries the response's nonce and
that no element has an inline event handler attribute.

* Fixes #23502: Remove htmx runtime eval from global search and the object selector

Global search's 3-character minimum moves out of the keyup[...] trigger
filter into a keyup listener that dispatches netbox:search-input once the
input reaches the length given by data-search-min-length. The generic object
selector's stale-ID guard moves from hx-on::config-request to a
data-htmx-clear-param attribute and one document-level htmx:configRequest
listener. Both keep working under a CSP without 'unsafe-eval'. htmx's
allowEval is left at its default on purpose, as the comment in htmx.ts says.

* Fixes #23502: Nonce the scripts on the Swagger, Redoc and browsable API pages

NetBox now overrides drf-spectacular's Swagger UI and Redoc templates and DRF's script block in the browsable API template so every script tag carries the request's CSP nonce. The overrides extend the upstream templates and change only the blocks that hold scripts. The CSP regression test covers all three pages.

* Fixes #23502: Send a Permissions-Policy header denying unused browser features

Adds PermissionsPolicyMiddleware and a PERMISSIONS_POLICY parameter. By default every response denies camera, microphone, geolocation, payment, usb, hid, serial and bluetooth. An operator's dictionary replaces the default, an empty dictionary sends no header, and a header set by a view is left alone.

* Fixes #23502: Add an example Content Security Policy page to the administration docs

The page gives operators a policy they can copy into SECURE_CSP, says what each directive allows, and explains testing with report-only mode. It states that NetBox's nonce rule covers scripts only and that inline styles are allowed by the example.

* Fixes #23502: Document Copilot's extra hosts for the example CSP

Name the hosts NetBox Copilot loads beyond its loader, for operators whose users enable it.

* Fixes #23502: Document CSP requirements for plugin templates

Adds a Content Security Policy section to the plugin template docs covering script nonces, inline event handlers, runtime eval in htmx attributes, and inline styles, linking to the administration page.
Jason Novinger 23 ساعت پیش
والد
کامیت
902a023f00

+ 1 - 0
AGENTS.md

@@ -323,6 +323,7 @@ Do not include an entry in the release notes for the PR unless explicitly instru
 - `NETBOX_CONFIGURATION` env var controls which settings module loads; set to `netbox.configuration_testing` for tests.
 - The `extras` app is a catch-all for cross-cutting features (custom fields, tags, webhooks, scripts).
 - Plugins API: only documented public APIs are stable. Internal NetBox code is subject to change without notice.
+- `netbox/templates/rest_framework/api.html`, `netbox/templates/drf_spectacular/swagger_ui.html` and `netbox/templates/drf_spectacular/redoc.html` copy upstream script blocks to add CSP nonces. Re-sync them whenever djangorestframework or drf-spectacular is upgraded.
 - See `docs/development/` for the full contributing guide and code style details.
 
 ## References

+ 35 - 0
docs/administration/content-security-policy.md

@@ -0,0 +1,35 @@
+# Content Security Policy
+
+!!! info "This feature was introduced in NetBox v4.8."
+
+A [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP) (CSP) tells the browser from which sources a page may load scripts, images, fonts, and other resources. NetBox does not send one by default. To send one, define it with the [`SECURE_CSP`](../configuration/security.md#secure_csp) or [`SECURE_CSP_REPORT_ONLY`](../configuration/security.md#secure_csp_report_only) configuration parameter.
+
+NetBox's own pages are written to work under a strict script policy. Every `<script>` element NetBox renders carries the per-request nonce, and NetBox does not use inline event handler attributes or evaluate strings as code. This applies to scripts only. NetBox makes no equivalent promise for styles: it renders inline `<style>` elements and `style=` attributes, and none of them carry a nonce.
+
+!!! warning "Debug mode"
+    With `DEBUG` enabled, Django's debug error pages, GraphiQL's debug integration and django-htmx's error handler run scripts that a strict policy blocks or reports. Test policies with `DEBUG` disabled, and don't loosen a policy to accommodate them.
+
+## Example policy
+
+```python
+from django.utils.csp import CSP
+
+SECURE_CSP = {
+    'default-src': [CSP.SELF],
+    'script-src': [
+        CSP.SELF,
+        CSP.NONCE,
+        'https://static.copilot.netboxlabs.ai',
+    ],
+    'style-src': [CSP.SELF, CSP.UNSAFE_INLINE, 'https://fonts.googleapis.com'],
+    'font-src': [CSP.SELF, 'data:', 'https://fonts.gstatic.com'],
+    'img-src': [CSP.SELF, 'data:', 'https:'],
+    'connect-src': [CSP.SELF],
+    'worker-src': [CSP.SELF, 'blob:'],
+    'base-uri': [CSP.SELF],
+}
+```
+
+Try a policy first by assigning it to `SECURE_CSP_REPORT_ONLY`, which reports violations in the browser console without blocking anything.
+
+If your users enable NetBox Copilot, also allow `https://unpkg.com` and `https://js.stripe.com` in `script-src`, `'self'` and `https://js.stripe.com` in `frame-src`, and `https://api.copilot.netboxlabs.ai` and `wss://api.copilot.netboxlabs.ai` in `connect-src`.

+ 63 - 0
docs/configuration/security.md

@@ -200,6 +200,69 @@ The view name or URL to which a user is redirected after logging out.
 
 ---
 
+## PERMISSIONS_POLICY
+
+Default:
+
+```python
+PERMISSIONS_POLICY = {
+    'camera': [],
+    'microphone': [],
+    'geolocation': [],
+    'payment': [],
+    'usb': [],
+    'hid': [],
+    'serial': [],
+    'bluetooth': [],
+}
+```
+
+Defines the `Permissions-Policy` header sent with HTML responses, which controls which browser features NetBox pages may use. See the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Permissions-Policy) for the syntax and the list of features.
+
+Your dictionary replaces the default entirely, so copy the default and edit it. For example, to re-allow the camera for NetBox's own origin:
+
+```python
+PERMISSIONS_POLICY = {
+    'camera': ['self'],
+    'microphone': [],
+    'geolocation': [],
+    'payment': [],
+    'usb': [],
+    'hid': [],
+    'serial': [],
+    'bluetooth': [],
+}
+```
+
+Set `PERMISSIONS_POLICY = {}` to send no header. Values are checked at startup, and Django's quoted `CSP.SELF` is not accepted here.
+
+---
+
+## SECURE_CSP
+
+Default: `{}`
+
+Defines a Content Security Policy (CSP) to be sent with every response in the `Content-Security-Policy` header. This is a pass-through to Django's [`SECURE_CSP`](https://docs.djangoproject.com/en/stable/ref/settings/#secure-csp) setting: directives are mapped to lists of sources, using the constants in `django.utils.csp.CSP`. Include `CSP.NONCE` in a directive to have a fresh nonce generated for each request, which is added to the header whenever the rendered page uses it. If empty (the default), no header is sent.
+
+```python
+from django.utils.csp import CSP
+
+SECURE_CSP = {
+    'default-src': [CSP.SELF],
+    'script-src': [CSP.SELF, CSP.NONCE],
+}
+```
+
+---
+
+## SECURE_CSP_REPORT_ONLY
+
+Default: `{}`
+
+Defines a Content Security Policy to be sent in the `Content-Security-Policy-Report-Only` header. The browser reports violations of this policy without blocking anything, which makes it useful for testing a policy before enforcing it with [`SECURE_CSP`](#secure_csp). This is a pass-through to Django's [`SECURE_CSP_REPORT_ONLY`](https://docs.djangoproject.com/en/stable/ref/settings/#secure-csp-report-only) setting, and takes the same form as `SECURE_CSP`. If empty (the default), no header is sent.
+
+---
+
 ## SECURE_HSTS_INCLUDE_SUBDOMAINS
 
 Default: `False`

+ 20 - 0
docs/plugins/development/templates.md

@@ -203,6 +203,26 @@ This template is used by the `BulkDeleteView` generic view to delete multiple ob
 | `table`      | Yes      | The table class used for rendering the list of objects          |
 | `return_url` | Yes      | The URL to which the user is redirect after submitting the form |
 
+## Content Security Policy
+
+Administrators can send a [Content Security Policy](../../administration/content-security-policy.md) (CSP) that only allows scripts carrying a per-request nonce.
+
+!!! warning
+    NetBox is planning to turn a CSP on by default in v5.0 ([#23503](https://github.com/netbox-community/netbox/issues/23503)), so plugin templates should work under one now.
+
+* **Nonce every script.** Add `nonce="{{ csp_nonce }}"` to every `<script>` element, inline or with a `src`. The `csp_nonce` template variable is public plugin API from NetBox v4.8. A `<script>` inside a fragment that htmx swaps into the page does not run under a nonce policy, so use a static JavaScript listener instead.
+* **No inline event handler attributes.** Attributes such as `onclick=` or `onerror=` are blocked and the handler silently does not run. Attach a listener from a script file under your plugin's static directory instead.
+* **No runtime evaluation of strings as code.** This includes htmx's `hx-on` attributes, `hx-trigger` filter expressions such as `keyup[event.target.value.length > 2]`, and `js:` values in `hx-vals` or `hx-headers`. Without `'unsafe-eval'`, `hx-on` handlers and `js:` values throw an error, which shows in the browser console as a CSP violation, and they do not work. A trigger filter fails open instead: htmx drops the filter, so the request fires on every event. Use a listener that dispatches a custom event or sets a request parameter in `htmx:configRequest`.
+* **Inline styles are fine.** The [example policy](../../administration/content-security-policy.md#example-policy) allows inline `style=` attributes and `<style>` elements, and `style-src` takes no nonce.
+
+```jinja2
+{% load static %}
+<script nonce="{{ csp_nonce }}">
+  window.myPluginConfig = { endpoint: "{% url 'plugins:my_plugin:endpoint' %}" };
+</script>
+<script nonce="{{ csp_nonce }}" src="{% static 'my_plugin/widget.js' %}"></script>
+```
+
 ## Tags
 
 The following custom template tags are available in NetBox.

+ 1 - 0
mkdocs.yml

@@ -173,6 +173,7 @@ nav:
             - Microsoft Entra ID: 'administration/authentication/microsoft-entra-id.md'
             - Okta: 'administration/authentication/okta.md'
         - Permissions: 'administration/permissions.md'
+        - Content Security Policy: 'administration/content-security-policy.md'
         - Error Reporting: 'administration/error-reporting.md'
         - Management Commands: 'administration/management-commands.md'
         - Replicating NetBox: 'administration/replicating-netbox.md'

+ 1 - 1
netbox/ipam/tests/test_views.py

@@ -724,7 +724,7 @@ class PrefixTestCase(ViewTestCases.PrimaryObjectViewTestCase):
         data = {
             'pk': [prefix.pk],
             'scope_content_type': ContentType.objects.get_for_model(Site).pk,
-            # The client-side hx-on::config-request clears the paired object id on a type change.
+            # The client-side data-htmx-clear-param listener clears the paired object id on a type change.
             'scope_object_id': '',
         }
         response = self.client.post(self._get_url('bulk_edit'), data, headers={'HX-Request': 'true'})

+ 3 - 1
netbox/netbox/forms/search.py

@@ -22,7 +22,9 @@ class SearchForm(forms.Form):
             attrs={
                 'hx-get': '',
                 'hx-target': '#object_list',
-                'hx-trigger': 'keyup[target.value.length >= 3] changed delay:500ms',
+                # netbox:search-input is dispatched by htmx.ts once the value reaches data-search-min-length
+                'hx-trigger': 'netbox:search-input changed delay:500ms',
+                'data-search-min-length': '3',
             }
         )
     )

+ 34 - 0
netbox/netbox/middleware.py

@@ -28,6 +28,7 @@ __all__ = (
     'CoreMiddleware',
     'LoginRequiredMiddleware',
     'MaintenanceModeMiddleware',
+    'PermissionsPolicyMiddleware',
     'PrometheusAfterMiddleware',
     'PrometheusBeforeMiddleware',
     'RemoteUserMiddleware',
@@ -52,6 +53,39 @@ class CommonMiddleware(DjangoCommonMiddleware):
         return super().should_redirect_with_slash(request)
 
 
+class PermissionsPolicyMiddleware:
+    """
+    Send a Permissions-Policy header built from the PERMISSIONS_POLICY setting on HTML responses only, since only a
+    browser rendering a document uses it. 3XX responses get none, as the browser never renders their body. Each feature
+    maps to a list of allowed origins, where an empty list denies the feature. An empty setting sends no header, and
+    a header already set by a view is left alone. The header is built once, when the middleware is instantiated.
+    """
+    def __init__(self, get_response):
+        self.get_response = get_response
+        self.header = self.build_header(settings.PERMISSIONS_POLICY) if settings.PERMISSIONS_POLICY else None
+
+    def __call__(self, request):
+        response = self.get_response(request)
+        if (
+            self.header is not None
+            and 'Permissions-Policy' not in response
+            and not 300 <= response.status_code < 400
+            and response.get('Content-Type', '').lower().startswith('text/html')
+        ):
+            response['Permissions-Policy'] = self.header
+        return response
+
+    @staticmethod
+    def build_header(policy):
+        directives = []
+        for feature, origins in policy.items():
+            # "self" and "*" are structured-field tokens. Anything else is an origin, sent as a quoted string.
+            items = ' '.join(origin if origin in ('self', '*') else f'"{origin}"' for origin in origins)
+            # A lone wildcard is sent as a bare token, which the spec treats the same as "(*)".
+            directives.append(f'{feature}=*' if list(origins) == ['*'] else f'{feature}=({items})')
+        return ', '.join(directives)
+
+
 class CoreMiddleware:
 
     def __init__(self, get_response):

+ 16 - 0
netbox/netbox/settings.py

@@ -26,6 +26,7 @@ from netbox.settings_utils import (
     parse_job_timeout,
     resolve_install_paths,
     secret_key_hint,
+    validate_permissions_policy,
     validate_webhook_default_timeout,
 )
 from utilities.release import load_release_data
@@ -167,6 +168,16 @@ LOGIN_FORM_HIDDEN = param('LOGIN_FORM_HIDDEN', False, types=bool)
 LOGOUT_REDIRECT_URL = param('LOGOUT_REDIRECT_URL', 'home', types=str)
 MEDIA_ROOT = param('MEDIA_ROOT', os.path.join(NETBOX_ROOT, 'media'), types=str).rstrip('/')
 METRICS_ENABLED = param('METRICS_ENABLED', False, types=bool)
+PERMISSIONS_POLICY = param('PERMISSIONS_POLICY', {
+    'camera': [],
+    'microphone': [],
+    'geolocation': [],
+    'payment': [],
+    'usb': [],
+    'hid': [],
+    'serial': [],
+    'bluetooth': [],
+}, types=dict, validators=[validate_permissions_policy])
 PLUGINS = param('PLUGINS', [], types=(list, tuple))
 PLUGINS_CONFIG = param('PLUGINS_CONFIG', {}, types=dict)
 PLUGINS_CATALOG_CONFIG = param('PLUGINS_CATALOG_CONFIG', {}, types=dict)
@@ -205,6 +216,8 @@ RQ_RETRY_MAX = param('RQ_RETRY_MAX', 0, types=int, min_value=0)
 SCRIPTS_ROOT = param('SCRIPTS_ROOT', os.path.join(NETBOX_ROOT, 'scripts'), types=str).rstrip('/')
 SEARCH_BACKEND = param('SEARCH_BACKEND', 'netbox.search.backends.CachedValueSearchBackend', types=str)
 SECRET_KEY = param('SECRET_KEY', types=str)  # Required
+SECURE_CSP = param('SECURE_CSP', {}, types=dict)
+SECURE_CSP_REPORT_ONLY = param('SECURE_CSP_REPORT_ONLY', {}, types=dict)
 SECURE_HSTS_INCLUDE_SUBDOMAINS = param('SECURE_HSTS_INCLUDE_SUBDOMAINS', False, types=bool)
 SECURE_HSTS_PRELOAD = param('SECURE_HSTS_PRELOAD', False, types=bool)
 SECURE_HSTS_SECONDS = param('SECURE_HSTS_SECONDS', 0, types=int, min_value=0)
@@ -529,6 +542,8 @@ MIDDLEWARE = [
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.security.SecurityMiddleware',
+    'django.middleware.csp.ContentSecurityPolicyMiddleware',
+    'netbox.middleware.PermissionsPolicyMiddleware',
     'django_htmx.middleware.HtmxMiddleware',
     'netbox.middleware.RemoteUserMiddleware',
     'netbox.middleware.LoginRequiredMiddleware',
@@ -570,6 +585,7 @@ TEMPLATES = [
                 'django.template.context_processors.debug',
                 'django.template.context_processors.request',
                 'django.template.context_processors.media',
+                'django.template.context_processors.csp',
                 'django.contrib.auth.context_processors.auth',
                 'django.contrib.messages.context_processors.messages',
                 'netbox.context_processors.settings',

+ 64 - 0
netbox/netbox/settings_utils.py

@@ -3,10 +3,12 @@
 import importlib
 import importlib.util
 import os
+import re
 import sys
 import threading
 import warnings
 from typing import NamedTuple
+from urllib.parse import urlsplit
 
 from django.core.exceptions import ImproperlyConfigured
 from rq.exceptions import TimeoutFormatError
@@ -22,6 +24,7 @@ __all__ = (
     'parse_job_timeout',
     'resolve_install_paths',
     'secret_key_hint',
+    'validate_permissions_policy',
     'validate_webhook_default_timeout',
 )
 
@@ -121,6 +124,67 @@ def validate_webhook_default_timeout(timeout, job_timeout):
         )
 
 
+_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]+)?')
+
+
+FEATURE_NAME_RE = re.compile(r'[a-z][a-z0-9-]*')
+
+
+def validate_permissions_policy(name, value):
+    """Validate PERMISSIONS_POLICY.
+
+    Feature names are checked for header-safe characters only, not against a list of known features.
+
+    Each value must be a list or tuple whose entries are 'self', '*', or a bare http(s) origin.
+    Anything else would be emitted into the header verbatim and silently discarded by browsers.
+    """
+    for feature, entries in value.items():
+        if not isinstance(feature, str) or FEATURE_NAME_RE.fullmatch(feature) is None:
+            raise ImproperlyConfigured(
+                f"{name} contains the invalid feature name {feature!r}: names start with a lowercase letter, then "
+                "lowercase letters, digits and hyphens"
+            )
+        if not isinstance(entries, (list, tuple)):
+            raise ImproperlyConfigured(
+                f"{name}[{feature!r}] must be a list or tuple of allowed origins (found {entries!r})"
+            )
+        for entry in entries:
+            if entry in ('self', '*'):
+                continue
+            if entry in ("'self'", "'none'"):
+                raise ImproperlyConfigured(
+                    f"{name}[{feature!r}] contains the CSP keyword {entry!r}: use 'self' without the CSP quotes "
+                    f"(CSP.SELF is not accepted), or an empty list to deny the feature"
+                )
+            if not _is_origin(entry):
+                raise ImproperlyConfigured(
+                    f"{name}[{feature!r}] contains {entry!r}, which is not 'self', '*', or an origin such as "
+                    f"'https://scan.example.com'"
+                )
+
+
+def _is_origin(entry):
+    """
+    Return True if entry is exactly a lowercase http(s) scheme, an ASCII host and an optional valid port.
+
+    The host charset is strict because the entry is written into a structured-field header, where one
+    bad character makes the browser drop the whole policy.
+    """
+    if not isinstance(entry, str):
+        return False
+    try:
+        parts = urlsplit(entry)
+        parts.port  # Raises ValueError if the port is not a number from 0 to 65535
+    except ValueError:
+        return False
+    return (
+        parts.scheme in ('http', 'https')
+        and entry == f'{parts.scheme}://{parts.netloc}'
+        and ORIGIN_NETLOC_RE.fullmatch(parts.netloc) is not None
+    )
+
+
 def _import_module(name):
     """Import a configuration module by dotted path.
 

+ 170 - 0
netbox/netbox/tests/test_csp.py

@@ -0,0 +1,170 @@
+import re
+from html.parser import HTMLParser
+from urllib.parse import urlsplit
+
+from django.conf import settings
+from django.contrib.staticfiles import finders
+from django.test import Client, override_settings
+from django.urls import reverse
+from django.utils.csp import CSP
+from drf_spectacular.settings import patched_settings
+
+from dcim.models import Site
+from utilities.testing import TestCase
+
+CSP_POLICY = {
+    'script-src': [CSP.SELF, CSP.NONCE],
+}
+
+
+class ScriptCollector(HTMLParser):
+    """
+    Record the attributes of every <script> element, and every inline event handler attribute (e.g. onerror) on any
+    element.
+    """
+    def __init__(self):
+        super().__init__()
+        self.scripts = []
+        self.handlers = []
+
+    def handle_starttag(self, tag, attrs):
+        attrs = dict(attrs)
+        if tag == 'script':
+            self.scripts.append(attrs)
+        for name in attrs:
+            # Inline event handler attributes are the only standard attributes starting with "on"
+            if name.startswith('on'):
+                self.handlers.append(f'<{tag} {name}="{attrs[name]}">')
+
+
+class HxTriggerCollector(HTMLParser):
+    """
+    Record the attributes of every <input> element that has an hx-trigger attribute.
+    """
+    def __init__(self):
+        super().__init__()
+        self.inputs = []
+
+    def handle_starttag(self, tag, attrs):
+        attrs = dict(attrs)
+        if tag == 'input' and 'hx-trigger' in attrs:
+            self.inputs.append(attrs)
+
+
+@override_settings(SECURE_CSP=CSP_POLICY, DEBUG=False)
+class ScriptNonceTestCase(TestCase):
+    """
+    Every <script> NetBox renders carries the request's CSP nonce, and no page uses inline event handler attributes
+    (which a nonce cannot cover). Together these let NetBox run under a policy without 'unsafe-inline'.
+    """
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.site = Site.objects.create(name='Site 1', slug='site-1')
+
+    def setUp(self):
+        super().setUp()
+
+        self.user.is_superuser = True
+        self.user.save()
+
+    @staticmethod
+    def collect(response):
+        parser = ScriptCollector()
+        parser.feed(response.content.decode())
+        return parser
+
+    def assertScriptsNonced(self, response):
+        self.assertHttpStatus(response, 200)
+        match = re.search(r"'nonce-([^']+)'", response['Content-Security-Policy'])
+        self.assertIsNotNone(match, f"No nonce in header: {response['Content-Security-Policy']}")
+        nonce = match.group(1)
+
+        parser = self.collect(response)
+        self.assertTrue(parser.scripts, 'No <script> elements found')
+        for script in parser.scripts:
+            self.assertEqual(script.get('nonce'), nonce, f'<script> without the request nonce: {script}')
+        self.assertEqual(parser.handlers, [], 'Inline event handler attributes found')
+
+    def test_login(self):
+        self.assertScriptsNonced(Client().get(reverse('login')))
+
+    def test_object_list(self):
+        self.assertScriptsNonced(self.client.get(reverse('dcim:site_list')))
+
+    def test_object_detail(self):
+        self.assertScriptsNonced(self.client.get(self.site.get_absolute_url()))
+
+    def test_user_token_edit(self):
+        self.assertScriptsNonced(self.client.get(reverse('account:usertoken_add')))
+
+    def test_token_edit(self):
+        self.assertScriptsNonced(self.client.get(reverse('users:token_add')))
+
+    def test_copilot_script(self):
+        # Copilot is enabled globally by default. Each user opts in with a preference.
+        self.user.config.set('ui.copilot_enabled', 'true', commit=True)
+
+        response = self.client.get(reverse('dcim:site_list'))
+        self.assertScriptsNonced(response)
+        self.assertIn(settings.NETBOX_COPILOT_URL, [script.get('src') for script in self.collect(response).scripts])
+
+    def test_graphiql(self):
+        self.assertScriptsNonced(self.client.get(reverse('graphql'), HTTP_ACCEPT='text/html'))
+
+    def test_swagger_ui(self):
+        self.assertScriptsNonced(self.client.get(reverse('api_docs')))
+
+    def test_redoc(self):
+        self.assertScriptsNonced(self.client.get(reverse('api_redocs')))
+
+    def test_redoc_with_settings(self):
+        # With REDOC_UI_SETTINGS set, Redoc renders an inline Redoc.init script. drf-spectacular reads its settings
+        # once at import and has no setting_changed hook, so override_settings(SPECTACULAR_SETTINGS=...) has no
+        # effect. patched_settings is its own supported way to override them temporarily.
+        with patched_settings({'REDOC_UI_SETTINGS': {'hideDownloadButton': True}}):
+            response = self.client.get(reverse('api_redocs'))
+        self.assertScriptsNonced(response)
+        inline = [script for script in self.collect(response).scripts if 'src' not in script]
+        self.assertEqual(len(inline), 1)
+        self.assertIn('Redoc.init', response.content.decode())
+
+    def test_browsable_api(self):
+        self.assertScriptsNonced(self.client.get(reverse('api-root'), HTTP_ACCEPT='text/html'))
+        self.assertScriptsNonced(self.client.get(reverse('dcim-api:site-list'), HTTP_ACCEPT='text/html'))
+
+    def test_api_script_sources_exist(self):
+        # The overrides copy upstream script tags, so an upgrade that renames a bundled file (e.g. jQuery) would
+        # leave a dead src. Every same-origin script src must resolve to a static file.
+        static_url = settings.STATIC_URL
+        responses = [
+            self.client.get(reverse('api_docs')),
+            self.client.get(reverse('api_redocs')),
+            self.client.get(reverse('api-root'), HTTP_ACCEPT='text/html'),
+        ]
+        for response in responses:
+            self.assertHttpStatus(response, 200)
+            checked = 0
+            for script in self.collect(response).scripts:
+                src = script.get('src')
+                if not src:
+                    continue
+                path = urlsplit(src).path
+                if not path.startswith(static_url):
+                    continue
+                checked += 1
+                relative = path.removeprefix(static_url)
+                self.assertTrue(finders.find(relative), f'No static file for script src {src}')
+            self.assertGreater(checked, 0, f'No same-origin scripts found on {response.request["PATH_INFO"]}')
+
+    def test_search_has_no_runtime_eval(self):
+        # A trigger filter such as keyup[...] is compiled with eval by htmx, which a policy without
+        # 'unsafe-eval' blocks (htmx then fires with no filter at all).
+        response = self.client.get(reverse('search'))
+        self.assertHttpStatus(response, 200)
+        collector = HxTriggerCollector()
+        collector.feed(response.content.decode())
+        self.assertEqual(len(collector.inputs), 1)
+        attrs = collector.inputs[0]
+        self.assertEqual(attrs['hx-trigger'], 'netbox:search-input changed delay:500ms')
+        self.assertEqual(attrs['data-search-min-length'], '3')

+ 64 - 0
netbox/netbox/tests/test_middleware.py

@@ -1,4 +1,5 @@
 import json
+import re
 from contextlib import contextmanager
 from types import SimpleNamespace
 from unittest import skipIf
@@ -10,6 +11,7 @@ from django.core.signals import got_request_exception
 from django.db.utils import InternalError
 from django.test import Client, RequestFactory, override_settings
 from django.urls import ResolverMatch, reverse
+from django.utils.csp import CSP
 from django.views.generic import View
 from rest_framework import status
 from rest_framework.views import APIView
@@ -17,6 +19,11 @@ from rest_framework.views import APIView
 from netbox.middleware import CoreMiddleware, LoginRequiredMiddleware, MaintenanceModeMiddleware
 from utilities.testing import TestCase
 
+CSP_POLICY = {
+    'default-src': [CSP.SELF],
+    'script-src': [CSP.SELF, CSP.NONCE],
+}
+
 
 class CoreMiddlewareTestCase(TestCase):
 
@@ -249,3 +256,60 @@ class LoginRequiredMiddlewareTestCase(TestCase):
     def test_plugin_views_login_not_required(self):
         response = self.anonymous_client.get(reverse('plugins:dummy_plugin:dummy_model_list'))
         self.assertHttpStatus(response, 200)
+
+
+class ContentSecurityPolicyTestCase(TestCase):
+    """
+    SECURE_CSP and SECURE_CSP_REPORT_ONLY are passed through to Django's CSP middleware.
+    """
+
+    def setUp(self):
+        super().setUp()
+
+        self.anonymous_client = Client()
+
+    def get_nonce(self, response, header='Content-Security-Policy'):
+        match = re.search(r"'nonce-([^']+)'", response[header])
+        self.assertIsNotNone(match, f'No nonce in {header}: {response[header]}')
+        return match.group(1)
+
+    @override_settings(SECURE_CSP=CSP_POLICY)
+    def test_policy_sends_header_with_nonce(self):
+        response = self.anonymous_client.get(reverse('login'))
+        self.assertHttpStatus(response, 200)
+        self.assertIn("default-src 'self'", response['Content-Security-Policy'])
+        nonce = self.get_nonce(response)
+        self.assertIn(f'nonce="{nonce}"', response.content.decode())
+
+    @override_settings(SECURE_CSP=CSP_POLICY)
+    def test_nonce_differs_between_requests(self):
+        nonce1 = self.get_nonce(self.anonymous_client.get(reverse('login')))
+        nonce2 = self.get_nonce(self.anonymous_client.get(reverse('login')))
+        self.assertNotEqual(nonce1, nonce2)
+
+    @override_settings(SECURE_CSP_REPORT_ONLY=CSP_POLICY)
+    def test_report_only_policy(self):
+        response = self.anonymous_client.get(reverse('login'))
+        self.assertHttpStatus(response, 200)
+        self.assertNotIn('Content-Security-Policy', response)
+        nonce = self.get_nonce(response, header='Content-Security-Policy-Report-Only')
+        self.assertIn(f'nonce="{nonce}"', response.content.decode())
+
+    def test_no_header_by_default(self):
+        response = self.anonymous_client.get(reverse('login'))
+        self.assertHttpStatus(response, 200)
+        self.assertNotIn('Content-Security-Policy', response)
+        self.assertNotIn('Content-Security-Policy-Report-Only', response)
+
+    @override_settings(SECURE_CSP=CSP_POLICY, LOGIN_REQUIRED=True, DEBUG=False)
+    def test_header_on_non_html_responses(self):
+        requests = (
+            (reverse('home'), 302),
+            (reverse('api-root'), 403),
+            ('/no-such-page/', 404),
+        )
+        for url, status_code in requests:
+            with self.subTest(url=url):
+                response = self.anonymous_client.get(url)
+                self.assertHttpStatus(response, status_code)
+                self.assertIn("default-src 'self'", response['Content-Security-Policy'])

+ 127 - 0
netbox/netbox/tests/test_permissions_policy.py

@@ -0,0 +1,127 @@
+from unittest.mock import patch
+
+from django.http import HttpResponse
+from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings
+from django.urls import reverse
+
+from netbox.middleware import PermissionsPolicyMiddleware
+from utilities.testing import TestCase as NetBoxTestCase
+
+HEADER = 'Permissions-Policy'
+
+DEFAULT_HEADER = 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), hid=(), serial=(), bluetooth=()'
+
+
+class PermissionsPolicyHeaderTestCase(TestCase):
+    """
+    Check the header on real responses, through the whole middleware stack.
+    """
+
+    def test_default_denies_the_default_deny_list(self):
+        response = self.client.get(reverse('login'))
+        self.assertEqual(response[HEADER], DEFAULT_HEADER)
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['self'], 'geolocation': []})
+    def test_custom_policy_replaces_default(self):
+        response = self.client.get(reverse('login'))
+        self.assertEqual(response[HEADER], 'camera=(self), geolocation=()')
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['self', 'https://scan.example.com']})
+    def test_origins_are_quoted_and_self_is_a_token(self):
+        response = self.client.get(reverse('login'))
+        self.assertEqual(response[HEADER], 'camera=(self "https://scan.example.com")')
+
+    @override_settings(PERMISSIONS_POLICY={})
+    def test_empty_policy_sends_no_header(self):
+        response = self.client.get(reverse('login'))
+        self.assertNotIn(HEADER, response)
+
+
+class PermissionsPolicyContentTypeTestCase(NetBoxTestCase):
+    """
+    The header is only useful to a browser rendering a document, so raw API data responses carry none.
+    """
+
+    def setUp(self):
+        super().setUp()
+
+        self.user.is_superuser = True
+        self.user.save()
+
+    def test_rest_api_json_has_no_header(self):
+        response = self.client.get(reverse('api-root'), HTTP_ACCEPT='application/json')
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response['Content-Type'].startswith('application/json'))
+        self.assertNotIn(HEADER, response)
+
+    def test_graphql_json_has_no_header(self):
+        response = self.client.post(
+            reverse('graphql'),
+            data='{"query": "{ __typename }"}',
+            content_type='application/json',
+        )
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response['Content-Type'].startswith('application/json'))
+        self.assertNotIn(HEADER, response)
+
+    def test_browsable_api_html_has_header(self):
+        response = self.client.get(reverse('api-root'), HTTP_ACCEPT='text/html')
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response['Content-Type'].startswith('text/html'))
+        self.assertEqual(response[HEADER], DEFAULT_HEADER)
+
+    def test_ui_page_has_header(self):
+        response = self.client.get(reverse('home'))
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(response[HEADER], DEFAULT_HEADER)
+
+
+class PermissionsPolicyMiddlewareTestCase(SimpleTestCase):
+    """
+    Check the middleware in isolation, with a view that sets the header itself.
+    """
+
+    def test_header_set_by_view_is_untouched(self):
+        def view(request):
+            response = HttpResponse()
+            response[HEADER] = 'fullscreen=(self)'
+            return response
+
+        response = PermissionsPolicyMiddleware(view)(RequestFactory().get('/'))
+        self.assertEqual(response[HEADER], 'fullscreen=(self)')
+
+    def test_redirects_and_not_modified_have_no_header(self):
+        for status in (301, 302, 304):
+            with self.subTest(status=status):
+                response = HttpResponse(status=status, content_type='text/html')
+                middleware = PermissionsPolicyMiddleware(lambda request, response=response: response)
+                self.assertNotIn(HEADER, middleware(RequestFactory().get('/')))
+
+    def test_html_200_has_header(self):
+        middleware = PermissionsPolicyMiddleware(lambda request: HttpResponse(content_type='text/html'))
+        self.assertEqual(middleware(RequestFactory().get('/'))[HEADER], DEFAULT_HEADER)
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['*']})
+    def test_lone_wildcard_is_a_bare_token(self):
+        response = PermissionsPolicyMiddleware(lambda request: HttpResponse(content_type='text/html'))(
+            RequestFactory().get('/')
+        )
+        self.assertEqual(response[HEADER], 'camera=*')
+
+    @override_settings(PERMISSIONS_POLICY={'camera': ['*', 'self']})
+    def test_wildcard_with_other_origins_stays_an_inner_list(self):
+        response = PermissionsPolicyMiddleware(lambda request: HttpResponse(content_type='text/html'))(
+            RequestFactory().get('/')
+        )
+        self.assertEqual(response[HEADER], 'camera=(* self)')
+
+    def test_header_is_built_once_per_instance(self):
+        with patch.object(
+            PermissionsPolicyMiddleware, 'build_header', wraps=PermissionsPolicyMiddleware.build_header
+        ) as build_header:
+            middleware = PermissionsPolicyMiddleware(lambda request: HttpResponse())
+            first = middleware(RequestFactory().get('/'))
+            second = middleware(RequestFactory().get('/'))
+        build_header.assert_called_once()
+        self.assertEqual(first[HEADER], DEFAULT_HEADER)
+        self.assertEqual(second[HEADER], DEFAULT_HEADER)

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

@@ -397,6 +397,73 @@ class ValidateWebhookDefaultTimeoutTest(SimpleTestCase):
                     settings_utils.validate_webhook_default_timeout(timeout, 300)
 
 
+class ValidatePermissionsPolicyTest(SimpleTestCase):
+    """validate_permissions_policy() is the startup check applied to PERMISSIONS_POLICY."""
+
+    def test_valid_policies(self):
+        valid = (
+            {},
+            {'camera': []},
+            {'camera': ['self']},
+            {'camera': ['*']},
+            {'camera': ('self',)},
+            {'camera': ['self', 'https://scan.example.com'], 'usb': []},
+            {'camera': ['http://localhost:8000']},
+            {'camera': ['https://[::1]:8443']},
+            {'camera': ['https://*.example.com']},
+            {'camera': ['https://*.example.com:8443']},
+            {'camera': ['https://localhost']},
+            {'camera': ['https://xn--bcher-kva.example']},
+            {'camera': ['https://scan_1.example.com']},
+            {'camera': ['https://_service.example.com']},
+        )
+        for value in valid:
+            with self.subTest(value=value):
+                settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', value)
+
+    def test_csp_quoted_keywords_raise(self):
+        for entry in ("'self'", "'none'"):
+            with self.subTest(entry=entry):
+                with self.assertRaisesMessage(ImproperlyConfigured, 'without the CSP quotes'):
+                    settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': [entry]})
+
+    def test_error_names_feature_and_entry(self):
+        with self.assertRaisesMessage(ImproperlyConfigured, "camera"):
+            settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': ['scan.example.com']})
+        with self.assertRaisesMessage(ImproperlyConfigured, "'scan.example.com'"):
+            settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': ['scan.example.com']})
+
+    def test_malformed_feature_names_raise(self):
+        for feature in ('camera ()', 'cam=era', 'Camera', '', 5, '1camera', '-camera'):
+            with self.subTest(feature=feature):
+                with self.assertRaisesMessage(ImproperlyConfigured, repr(feature)):
+                    settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {feature: []})
+
+    def test_well_formed_feature_names_are_not_checked_against_a_list(self):
+        for feature in ('camera', 'publickey-credentials-get', 'future-feature'):
+            with self.subTest(feature=feature):
+                settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {feature: []})
+
+    def test_bare_string_value_raises(self):
+        with self.assertRaisesMessage(ImproperlyConfigured, 'must be a list or tuple'):
+            settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': 'self'})
+
+    def test_invalid_origins_raise(self):
+        invalid = (
+            'scan.example.com', 'ftp://scan.example.com', 'https://', 'https://example.com/path', '', 5,
+            'https://u@x', 'https://x:abc', 'https://x:99999', 'https://x:', 'https://x?', 'https://x#',
+            'https://x y', 'https:// x', 'HTTPS://x',
+            'https://x"y', 'https://x,y', 'https://x;y', 'https://x%20y', 'https://x\x00', 'https://x\x7f',
+            'https://bücher.example',
+            'https://*', 'https://ex*ample.com', 'https://a*b.example.com', 'https://*.*.example.com',
+            'https://-', 'https://..', 'https://.example.com', 'https://example.com.', 'https://*.example.com:',
+        )
+        for entry in invalid:
+            with self.subTest(entry=entry):
+                with self.assertRaises(ImproperlyConfigured):
+                    settings_utils.validate_permissions_policy('PERMISSIONS_POLICY', {'camera': [entry]})
+
+
 class LoadLdapConfigTest(SimpleTestCase):
     def test_loads_sibling_ldap_config(self):
         with tempfile.TemporaryDirectory() as conf_dir:

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
netbox/project-static/dist/netbox.js


تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
netbox/project-static/dist/netbox.js.map


+ 5 - 0
netbox/project-static/src/global.d.ts

@@ -96,5 +96,10 @@ interface HTMLElementEventMap {
     parameters: Record<string, string>;
     formData: FormData;
     headers: Record<string, string>;
+    elt: Element;
   }>;
 }
+
+interface DocumentEventMap {
+  'htmx:configRequest': HTMLElementEventMap['htmx:configRequest'];
+}

+ 35 - 0
netbox/project-static/src/htmx.ts

@@ -45,11 +45,46 @@ function revealSubmissionErrors(event: Event): void {
   }
 }
 
+/**
+ * Dispatch `netbox:search-input` on an input once its value reaches the length in
+ * `data-search-min-length`. The input's `hx-trigger` listens for this event instead of using a
+ * `keyup[...]` filter, which htmx compiles with runtime eval.
+ */
+function dispatchSearchInput(event: KeyboardEvent): void {
+  const input = event.target;
+  if (!(input instanceof HTMLInputElement)) return;
+  const rawMinLength = input.dataset.searchMinLength;
+  if (!rawMinLength) return;
+  const minLength = Number(rawMinLength);
+  if (Number.isNaN(minLength)) return;
+  if (input.value.length >= minLength) {
+    input.dispatchEvent(new CustomEvent('netbox:search-input', { bubbles: true }));
+  }
+}
+
+/**
+ * Blank the request parameter named by `data-htmx-clear-param` on the requesting element. The
+ * generic object selector uses this so a stale object ID can't cross content types. It replaces
+ * an `hx-on::config-request` attribute, which htmx evaluates at runtime.
+ */
+function clearConfiguredParam(event: HTMLElementEventMap['htmx:configRequest']): void {
+  const { elt, parameters } = event.detail;
+  const param = elt.getAttribute('data-htmx-clear-param');
+  if (param) {
+    parameters[param] = '';
+  }
+}
+
 /**
  * Hook into HTMX's event system to reinitialize specific native event listeners when HTMX swaps
  * elements.
  */
 export function initHtmx(): void {
+  // htmx.config.allowEval stays at its default: a CSP without 'unsafe-eval' already blocks eval,
+  // and disabling it would break plugins that use hx-on or trigger filters. See #23503.
+  document.addEventListener('keyup', dispatchSearchInput);
+  document.addEventListener('htmx:configRequest', clearConfiguredParam);
+
   document.addEventListener('htmx:afterSettle', event => {
     initDepedencies();
     revealSubmissionErrors(event);

+ 1 - 1
netbox/templates/account/usertoken_edit.html

@@ -8,7 +8,7 @@
 
 {% block javascript %}
 {{ block.super }}
-<script>
+<script nonce="{{ csp_nonce }}">
   (function () {
     const versionField = document.getElementById('id_version');
     const v1Warning = document.getElementById('v1-deprecation-warning');

+ 18 - 7
netbox/templates/base/base.html

@@ -24,19 +24,29 @@
     {# Page title #}
     <title>{% block title %}{% trans "Home" %}{% endblock %} | NetBox</title>
 
+    {# Redirect to the media failure page if a core static asset fails to load. Must precede those assets. #}
+    <script type="text/javascript" nonce="{{ csp_nonce }}">
+      window.addEventListener('error', function (event) {
+        if (event.target instanceof Element && event.target.dataset.mediaFailure) {
+          window.location = '{% url 'media_failure' %}?filename=' + event.target.dataset.mediaFailure;
+        }
+      }, true);
+    </script>
+
     {# Initialize color mode and sidebar folding #}
     <script
       type="text/javascript"
       src="{% static_with_params 'setmode.js' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=setmode.js'">
+      data-media-failure="setmode.js"
+      nonce="{{ csp_nonce }}">
     </script>
-    <script type="text/javascript">
+    <script type="text/javascript" nonce="{{ csp_nonce }}">
       (function () {
         initMode()
       })();
       window.CSRF_TOKEN = "{{ csrf_token }}";
     </script>
-    <script type="text/javascript">
+    <script type="text/javascript" nonce="{{ csp_nonce }}">
       initSidebar();
     </script>
 
@@ -44,12 +54,12 @@
     <link
       rel="stylesheet"
       href="{% static_with_params 'netbox-external.css' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=netbox-external.css'"
+      data-media-failure="netbox-external.css"
     />
     <link
       rel="stylesheet"
       href="{% static_with_params 'netbox.css' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=netbox.css'"
+      data-media-failure="netbox.css"
     />
     <link rel="icon" type="image/png" href="{% static 'netbox.ico' %}" />
     <link rel="apple-touch-icon" type="image/png" href="{% static 'netbox_touch-icon-180.png' %}" />
@@ -58,7 +68,8 @@
     <script
       type="text/javascript"
       src="{% static_with_params 'netbox.js' v=settings.RELEASE.version %}"
-      onerror="window.location='{% url 'media_failure' %}?filename=netbox.js'">
+      data-media-failure="netbox.js"
+      nonce="{{ csp_nonce }}">
     </script>
     {% django_htmx_script %}
 
@@ -74,7 +85,7 @@
 
     {# Additional Javascript #}
     {% if copilot_enabled and request.user.is_authenticated %}
-      <script src="{{ settings.NETBOX_COPILOT_URL }}" defer></script>
+      <script src="{{ settings.NETBOX_COPILOT_URL }}" defer nonce="{{ csp_nonce }}"></script>
     {% endif %}
     {% block javascript %}{% endblock %}
 

+ 16 - 0
netbox/templates/drf_spectacular/redoc.html

@@ -0,0 +1,16 @@
+{# Extends the upstream drf_spectacular template of the same name. The body block copies upstream to add CSP nonces: re-sync it when drf-spectacular is upgraded. #}
+{% extends 'drf_spectacular/redoc.html' %}
+
+{% block body %}
+  {% if settings %}
+    <div id="redoc-container"></div>
+    <script src="{{ redoc_standalone }}" nonce="{{ csp_nonce }}"></script>
+    <script nonce="{{ csp_nonce }}">
+      const redocSettings = {{ settings|safe }};
+      Redoc.init("{{ schema_url }}", redocSettings, document.getElementById('redoc-container'))
+    </script>
+  {% else %}
+    <redoc spec-url="{{ schema_url }}"></redoc>
+    <script src="{{ redoc_standalone }}" nonce="{{ csp_nonce }}"></script>
+  {% endif %}
+{% endblock body %}

+ 15 - 0
netbox/templates/drf_spectacular/swagger_ui.html

@@ -0,0 +1,15 @@
+{# Extends the upstream drf_spectacular template of the same name. The body block copies upstream to add CSP nonces: re-sync it when drf-spectacular is upgraded. #}
+{% extends 'drf_spectacular/swagger_ui.html' %}
+
+{% block body %}
+  <div id="swagger-ui"></div>
+  <script src="{{ swagger_ui_bundle }}" nonce="{{ csp_nonce }}"></script>
+  <script src="{{ swagger_ui_standalone }}" nonce="{{ csp_nonce }}"></script>
+  {% if script_url %}
+    <script src="{{ script_url }}" nonce="{{ csp_nonce }}"></script>
+  {% else %}
+    <script nonce="{{ csp_nonce }}">
+      {% include template_name_js %}
+    </script>
+  {% endif %}
+{% endblock body %}

+ 1 - 1
netbox/templates/graphql/graphiql.html

@@ -56,6 +56,6 @@
       data-graphql-worker="{% url 'graphiql_worker' name='graphql' %}"
       data-json-worker="{% url 'graphiql_worker' name='json' %}"
     >Loading...</div>
-    <script src="{% static_with_params 'graphiql/graphiql.js' v=settings.RELEASE.version %}"></script>
+    <script src="{% static_with_params 'graphiql/graphiql.js' v=settings.RELEASE.version %}" nonce="{{ csp_nonce }}"></script>
   </body>
 </html>

+ 17 - 0
netbox/templates/rest_framework/api.html

@@ -7,6 +7,23 @@
   <link rel="icon" type="image/png" href="{% static 'rest-api.ico' %}" />
 {% endblock head %}
 
+{% block script %}
+  {# Copies the upstream DRF script block to add CSP nonces: re-sync it when djangorestframework is upgraded. #}
+  <script type="application/json" id="drf_csrf" nonce="{{ csp_nonce }}">
+    {
+      "csrfHeaderName": "{{ csrf_header_name|default:'X-CSRFToken' }}",
+      "csrfToken": "{% if request %}{{ csrf_token }}{% endif %}"
+    }
+  </script>
+  <script src="{% static 'rest_framework/js/jquery-3.7.1.min.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/ajax-form.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/csrf.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/bootstrap.min.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/prettify-min.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/default.js' %}" nonce="{{ csp_nonce }}"></script>
+  <script src="{% static 'rest_framework/js/load-ajax-form.js' %}" nonce="{{ csp_nonce }}"></script>
+{% endblock script %}
+
 {% block title %}{% if name %}{{ name }} | {% endif %}NetBox {% trans "REST API" %}{% endblock %}
 
 {% block branding %}

+ 1 - 1
netbox/templates/users/token_edit.html

@@ -20,7 +20,7 @@
 
 {% block javascript %}
 {{ block.super }}
-<script>
+<script nonce="{{ csp_nonce }}">
   (function () {
     const versionField = document.getElementById('id_version');
     const v1Warning = document.getElementById('v1-deprecation-warning');

+ 2 - 3
netbox/utilities/forms/fields/generic.py

@@ -195,9 +195,8 @@ class GenericObjectChoiceField(forms.MultiValueField):
 
         # Clear the paired object selection client-side when the content type changes, so a stale object_id
         # cannot cross model boundaries on the HTMX re-render (a Site pk must not resurface as a Region pk).
-        self.content_type_field.widget.attrs['hx-on::config-request'] = (
-            f"event.detail.parameters['{field_name}_object_id'] = ''"
-        )
+        # The htmx:configRequest listener in htmx.ts blanks the parameter named here.
+        self.content_type_field.widget.attrs['data-htmx-clear-param'] = f'{field_name}_object_id'
 
         content_type_value = self._resolve_subvalue(form, field_name, 'content_type')
         object_value = self._resolve_subvalue(form, field_name, 'object_id')

+ 4 - 4
netbox/utilities/tests/test_forms.py

@@ -909,10 +909,10 @@ class GenericObjectChoiceFieldTestCase(TestCase):
         form = self._make_form(initial={'obj': self.site})
         field = form.fields['obj']
         field.get_bound_field(form, 'obj')
-        self.assertEqual(
-            field.content_type_field.widget.attrs.get('hx-on::config-request'),
-            "event.detail.parameters['obj_object_id'] = ''",
-        )
+        attrs = field.content_type_field.widget.attrs
+        self.assertEqual(attrs.get('data-htmx-clear-param'), 'obj_object_id')
+        # The clearing is done by a listener in the static bundle, not by htmx runtime eval.
+        self.assertNotIn('hx-on::config-request', attrs)
 
     def test_content_type_lookup_is_cached(self):
         """Repeated content-type resolution hits the database only once per field instance."""

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است