2
0
Эх сурвалжийг харах

Add Content Security Policy testing setup (#426)

Co-authored-by: Thibaud Colas <thibaudcolas@gmail.com>
Storm Heg 1 жил өмнө
parent
commit
a31d570b7c

+ 8 - 0
.env.example

@@ -0,0 +1,8 @@
+# This file contains Content Security Policy (CSP) directives.
+# If the variables defined here are loaded into the environment, CSP will be enabled.
+
+# Careful about the quoting of directives! It is easy to break.
+# CSP_DEFAULT_SRC="'self'"
+
+# Enable this rule to allow font awesome to load from CDN
+# CSP_FONT_SRC="'self', https://cdnjs.cloudflare.com"

+ 29 - 0
bakerydemo/settings/base.py

@@ -204,3 +204,32 @@ WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [
 ]
 
 ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "changeme")
+
+# Content Security policy settings
+# http://django-csp.readthedocs.io/en/latest/configuration.html
+
+# Only enable CSP when enabled through environment variables.
+if "CSP_DEFAULT_SRC" in os.environ:
+    MIDDLEWARE.append("csp.middleware.CSPMiddleware")
+
+    # Only report violations, don't enforce policy
+    CSP_REPORT_ONLY = True
+
+    # The “special” source values of 'self', 'unsafe-inline', 'unsafe-eval', and 'none' must be quoted!
+    # e.g.: CSP_DEFAULT_SRC = "'self'" Without quotes they will not work as intended.
+
+    CSP_DEFAULT_SRC = os.environ.get("CSP_DEFAULT_SRC").split(",")
+    if "CSP_SCRIPT_SRC" in os.environ:
+        CSP_SCRIPT_SRC = os.environ.get("CSP_SCRIPT_SRC").split(",")
+    if "CSP_STYLE_SRC" in os.environ:
+        CSP_STYLE_SRC = os.environ.get("CSP_STYLE_SRC").split(",")
+    if "CSP_IMG_SRC" in os.environ:
+        CSP_IMG_SRC = os.environ.get("CSP_IMG_SRC").split(",")
+    if "CSP_CONNECT_SRC" in os.environ:
+        CSP_CONNECT_SRC = os.environ.get("CSP_CONNECT_SRC").split(",")
+    if "CSP_FONT_SRC" in os.environ:
+        CSP_FONT_SRC = os.environ.get("CSP_FONT_SRC").split(",")
+    if "CSP_BASE_URI" in os.environ:
+        CSP_BASE_URI = os.environ.get("CSP_BASE_URI").split(",")
+    if "CSP_OBJECT_SRC" in os.environ:
+        CSP_OBJECT_SRC = os.environ.get("CSP_OBJECT_SRC").split(",")

+ 1 - 0
requirements/base.txt

@@ -4,4 +4,5 @@ wagtail>=5,<5.1
 wagtail-font-awesome-svg>=0.0.3,<1
 django-debug-toolbar>=3.2,<4
 django-extensions==3.2.1
+django-csp==3.7
 dj-database-url==0.4.1