summaryrefslogtreecommitdiff
path: root/django/middleware
diff options
context:
space:
mode:
authorRob Hudson <rob@cogit8.org>2025-08-23 12:23:53 -0700
committernessita <124304+nessita@users.noreply.github.com>2025-08-28 17:23:48 -0300
commit550822bceea227b07445d1852c4376b663c09ea4 (patch)
treec7b9a032939c7611156b54767c10059d7d6e373c /django/middleware
parent292b9e6fe8f23491680d9cc60f328562e2b1c823 (diff)
Fixed #36532 -- Added Content Security Policy view decorators to override or disable policies.
Co-authored-by: Natalia <124304+nessita@users.noreply.github.com>
Diffstat (limited to 'django/middleware')
-rw-r--r--django/middleware/csp.py23
1 files changed, 10 insertions, 13 deletions
diff --git a/django/middleware/csp.py b/django/middleware/csp.py
index e1c66ada5a..ba08cfff0c 100644
--- a/django/middleware/csp.py
+++ b/django/middleware/csp.py
@@ -1,5 +1,3 @@
-from http import HTTPStatus
-
from django.conf import settings
from django.utils.csp import CSP, LazyNonce, build_policy
from django.utils.deprecation import MiddlewareMixin
@@ -14,22 +12,21 @@ class ContentSecurityPolicyMiddleware(MiddlewareMixin):
request._csp_nonce = LazyNonce()
def process_response(self, request, response):
- # In DEBUG mode, exclude CSP headers for specific status codes that
- # trigger the debug view.
- exempted_status_codes = {
- HTTPStatus.NOT_FOUND,
- HTTPStatus.INTERNAL_SERVER_ERROR,
- }
- if settings.DEBUG and response.status_code in exempted_status_codes:
- return response
-
nonce = get_nonce(request)
+
+ sentinel = object()
+ if (csp_config := getattr(response, "_csp_config", sentinel)) is sentinel:
+ csp_config = settings.SECURE_CSP
+ if (csp_ro_config := getattr(response, "_csp_ro_config", sentinel)) is sentinel:
+ csp_ro_config = settings.SECURE_CSP_REPORT_ONLY
+
for header, config in [
- (CSP.HEADER_ENFORCE, settings.SECURE_CSP),
- (CSP.HEADER_REPORT_ONLY, settings.SECURE_CSP_REPORT_ONLY),
+ (CSP.HEADER_ENFORCE, csp_config),
+ (CSP.HEADER_REPORT_ONLY, csp_ro_config),
]:
# If headers are already set on the response, don't overwrite them.
# This allows for views to set their own CSP headers as needed.
+ # An empty config means CSP headers are not added to the response.
if config and header not in response:
response.headers[str(header)] = build_policy(config, nonce)