summaryrefslogtreecommitdiff
path: root/tests/middleware
diff options
context:
space:
mode:
authorRob Hudson <rob@cogit8.org>2025-05-03 10:01:58 -0700
committernessita <124304+nessita@users.noreply.github.com>2025-06-27 15:57:02 -0300
commitd63241ebc7067fdebbaf704989b34fcd8f26bbe9 (patch)
tree07b5a5cb0c70c446f5f0fb9ad2834501fc3d6544 /tests/middleware
parent3f59711581bd22ebd0f13fb040b15b69c0eee21f (diff)
Fixed #15727 -- Added Content Security Policy (CSP) support.
This initial work adds a pair of settings to configure specific CSP directives for enforcing or reporting policy violations, a new `django.middleware.csp.ContentSecurityPolicyMiddleware` to apply the appropriate headers to responses, and a context processor to support CSP nonces in templates for safely inlining assets. Relevant documentation has been added for the 6.0 release notes, security overview, a new how-to page, and a dedicated reference section. Thanks to the multiple reviewers for their precise and valuable feedback. Co-authored-by: Natalia <124304+nessita@users.noreply.github.com>
Diffstat (limited to 'tests/middleware')
-rw-r--r--tests/middleware/test_csp.py135
-rw-r--r--tests/middleware/urls.py7
-rw-r--r--tests/middleware/views.py28
3 files changed, 170 insertions, 0 deletions
diff --git a/tests/middleware/test_csp.py b/tests/middleware/test_csp.py
new file mode 100644
index 0000000000..de55f0c6a0
--- /dev/null
+++ b/tests/middleware/test_csp.py
@@ -0,0 +1,135 @@
+import time
+
+from utils_tests.test_csp import basic_config, basic_policy
+
+from django.contrib.staticfiles.testing import StaticLiveServerTestCase
+from django.test import SimpleTestCase
+from django.test.selenium import SeleniumTestCase
+from django.test.utils import modify_settings, override_settings
+from django.utils.csp import CSP
+
+from .views import csp_reports
+
+
+@override_settings(
+ MIDDLEWARE=["django.middleware.csp.ContentSecurityPolicyMiddleware"],
+ ROOT_URLCONF="middleware.urls",
+)
+class CSPMiddlewareTest(SimpleTestCase):
+ @override_settings(SECURE_CSP=None, SECURE_CSP_REPORT_ONLY=None)
+ def test_csp_defaults_off(self):
+ response = self.client.get("/csp-base/")
+ self.assertNotIn(CSP.HEADER_ENFORCE, response)
+ self.assertNotIn(CSP.HEADER_REPORT_ONLY, response)
+
+ @override_settings(SECURE_CSP=basic_config, SECURE_CSP_REPORT_ONLY=None)
+ def test_csp_basic(self):
+ """
+ With SECURE_CSP set to a valid value, the middleware adds a
+ "Content-Security-Policy" header to the response.
+ """
+ response = self.client.get("/csp-base/")
+ self.assertEqual(response[CSP.HEADER_ENFORCE], basic_policy)
+ self.assertNotIn(CSP.HEADER_REPORT_ONLY, response)
+
+ @override_settings(SECURE_CSP={"default-src": [CSP.SELF, CSP.NONCE]})
+ def test_csp_basic_with_nonce(self):
+ """
+ Test the nonce is added to the header and matches what is in the view.
+ """
+ response = self.client.get("/csp-nonce/")
+ nonce = response.text
+ self.assertTrue(nonce)
+ self.assertEqual(
+ response[CSP.HEADER_ENFORCE], f"default-src 'self' 'nonce-{nonce}'"
+ )
+
+ @override_settings(SECURE_CSP={"default-src": [CSP.SELF, CSP.NONCE]})
+ def test_csp_basic_with_nonce_but_unused(self):
+ """
+ Test if `request.csp_nonce` is never accessed, it is not added to the header.
+ """
+ response = self.client.get("/csp-base/")
+ nonce = response.text
+ self.assertIsNotNone(nonce)
+ self.assertEqual(response[CSP.HEADER_ENFORCE], basic_policy)
+
+ @override_settings(SECURE_CSP=None, SECURE_CSP_REPORT_ONLY=basic_config)
+ def test_csp_report_only_basic(self):
+ """
+ With SECURE_CSP_REPORT_ONLY set to a valid value, the middleware adds a
+ "Content-Security-Policy-Report-Only" header to the response.
+ """
+ response = self.client.get("/csp-base/")
+ self.assertEqual(response[CSP.HEADER_REPORT_ONLY], basic_policy)
+ self.assertNotIn(CSP.HEADER_ENFORCE, response)
+
+ @override_settings(
+ SECURE_CSP=basic_config,
+ SECURE_CSP_REPORT_ONLY=basic_config,
+ )
+ def test_csp_both(self):
+ """
+ If both SECURE_CSP and SECURE_CSP_REPORT_ONLY are set, the middleware
+ adds both headers to the response.
+ """
+ response = self.client.get("/csp-base/")
+ self.assertEqual(response[CSP.HEADER_ENFORCE], basic_policy)
+ self.assertEqual(response[CSP.HEADER_REPORT_ONLY], basic_policy)
+
+ @override_settings(
+ DEBUG=True,
+ SECURE_CSP=basic_config,
+ SECURE_CSP_REPORT_ONLY=basic_config,
+ )
+ def test_csp_404_debug_view(self):
+ """
+ Test that the CSP headers are not added to the debug view.
+ """
+ response = self.client.get("/csp-404/")
+ self.assertNotIn(CSP.HEADER_ENFORCE, response)
+ self.assertNotIn(CSP.HEADER_REPORT_ONLY, response)
+
+ @override_settings(
+ DEBUG=True,
+ SECURE_CSP=basic_config,
+ SECURE_CSP_REPORT_ONLY=basic_config,
+ )
+ def test_csp_500_debug_view(self):
+ """
+ Test that the CSP headers are not added to the debug view.
+ """
+ response = self.client.get("/csp-500/")
+ self.assertNotIn(CSP.HEADER_ENFORCE, response)
+ self.assertNotIn(CSP.HEADER_REPORT_ONLY, response)
+
+
+@override_settings(
+ ROOT_URLCONF="middleware.urls",
+ SECURE_CSP_REPORT_ONLY={
+ "default-src": [CSP.NONE],
+ "img-src": [CSP.SELF],
+ "script-src": [CSP.SELF],
+ "style-src": [CSP.SELF],
+ "report-uri": "/csp-report/",
+ },
+)
+@modify_settings(
+ MIDDLEWARE={"append": "django.middleware.csp.ContentSecurityPolicyMiddleware"}
+)
+class CSPSeleniumTestCase(SeleniumTestCase, StaticLiveServerTestCase):
+ available_apps = ["middleware"]
+
+ def setUp(self):
+ self.addCleanup(csp_reports.clear)
+ super().setUp()
+
+ def test_reports_are_generated(self):
+ url = self.live_server_url + "/csp-failure/"
+ self.selenium.get(url)
+ time.sleep(1) # Allow time for the CSP report to be sent.
+ reports = sorted(
+ (r["csp-report"]["document-uri"], r["csp-report"]["violated-directive"])
+ for r in csp_reports
+ )
+ self.assertEqual(reports, [(url, "img-src"), (url, "style-src-elem")])
diff --git a/tests/middleware/urls.py b/tests/middleware/urls.py
index 294b80b192..37120c7a54 100644
--- a/tests/middleware/urls.py
+++ b/tests/middleware/urls.py
@@ -1,4 +1,5 @@
from django.urls import path, re_path
+from django.views.debug import default_urlconf
from . import views
@@ -11,4 +12,10 @@ urlpatterns = [
# Should not append slash.
path("sensitive_fbv/", views.sensitive_fbv),
path("sensitive_cbv/", views.SensitiveCBV.as_view()),
+ # Used in CSP tests.
+ path("csp-failure/", default_urlconf),
+ path("csp-report/", views.csp_report_view),
+ path("csp-base/", views.empty_view),
+ path("csp-nonce/", views.csp_nonce),
+ path("csp-500/", views.csp_500),
]
diff --git a/tests/middleware/views.py b/tests/middleware/views.py
index 1de2edfd1b..6dc3ca24c7 100644
--- a/tests/middleware/views.py
+++ b/tests/middleware/views.py
@@ -1,6 +1,12 @@
+import json
+import sys
+
from django.http import HttpResponse
+from django.middleware.csp import get_nonce
from django.utils.decorators import method_decorator
+from django.views.debug import technical_500_response
from django.views.decorators.common import no_append_slash
+from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
@@ -17,3 +23,25 @@ def sensitive_fbv(request, *args, **kwargs):
class SensitiveCBV(View):
def get(self, *args, **kwargs):
return HttpResponse()
+
+
+def csp_nonce(request):
+ return HttpResponse(get_nonce(request))
+
+
+def csp_500(request):
+ try:
+ raise Exception
+ except Exception:
+ return technical_500_response(request, *sys.exc_info())
+
+
+csp_reports = []
+
+
+@csrf_exempt
+def csp_report_view(request):
+ if request.method == "POST":
+ data = json.loads(request.body)
+ csp_reports.append(data)
+ return HttpResponse(status=204)