Skip to contentSkip to conversation

Add a Content Security Policy

PATCH New Tim Orling 1 participant 1 message Oct 8

lore
Share & tools
lore

Tim Orling

author
#0 lore raw

PATCH 1/1 Add a Content Security Policy

From: Michael Halstead <[email protected]>

Error reports contain user submitted build logs, machine names, recipe names and so on, so add a strict Content Security Policy as a backstop against cross site scripting.

Django 4.2 has no built in CSP support, so add a small middleware which sends the policy from the new CONTENT_SECURITY_POLICY setting. The default only allows resources served by the application itself. Setting CONTENT_SECURITY_POLICY_REPORT_ONLY (CSP_REPORT_ONLY in the docker .env) sends the policy as Content-Security-Policy-Report-Only instead.

The statistics charts relied on an inline script which jQuery executed with eval. Embed the chart data with json_script and move the drawing code into main.js. Also escape the tooltip text, which nvd3 inserts as HTML, and URL encode the filter value when clicking a bar.

Replace inline style attributes with classes in custom.css and drop the inline script blocks from the registration templates, which were never rendered since base.html has no scripts block.

Document the policy in the README and add tests.

AI-Generated: Claude Opus 5.5

---
 Post/middleware.py                            | 41 +++++++++++++
 Post/static/css/custom.css                    | 28 +++++++++
 Post/static/js/main.js                        | 59 ++++++++++++++++++
 Post/test.py                                  | 61 ++++++++++++++++++-
 Post/views.py                                 |  8 +--
 README                                        | 35 +++++++++++
 project/settings.py                           | 23 +++++++
 project/settings.py.docker                    | 23 +++++++
 templates/discretebarchart.html               | 49 +++------------
 templates/error-details.html                  |  4 +-
 templates/home.html                           | 52 +++-------------
 templates/latest-errors.html                  | 16 ++---
 templates/registration/login.html             |  9 ---
 .../registration/password_reset_confirm.html  |  9 ---
 .../registration/password_reset_form.html     |  9 ---
 templates/registration/registration_form.html |  9 ---
 16 files changed, 300 insertions(+), 135 deletions(-)
 create mode 100644 Post/middleware.py
Post/middleware.py new file +41 -0
new file mode 100644
index 0000000..52ade71
@@ -0,0 +1,41 @@
+# SPDX-License-Identifier: MIT
+#
+# error-reporting-tool - middleware
+#
+# Licensed under the MIT license, see COPYING.MIT for details
+
+from django.conf import settings
+
+
+class ContentSecurityPolicyMiddleware:
+    """Add a Content-Security-Policy header to every response.
+
+    The policy is read from settings.CONTENT_SECURITY_POLICY, a dict mapping
+    each directive to a list of sources (an empty list gives a directive with
+    no value, e.g. 'upgrade-insecure-requests'). When
+    settings.CONTENT_SECURITY_POLICY_REPORT_ONLY is True the policy is sent
+    as Content-Security-Policy-Report-Only instead, so violations are
+    reported by browsers but not blocked.
+    """
+
+    def __init__(self, get_response):
+        self.get_response = get_response
+
+        policy = getattr(settings, 'CONTENT_SECURITY_POLICY', None) or {}
+        self.policy = "; ".join(
+            " ".join([directive] + list(sources))
+            for directive, sources in policy.items())
+
+        if getattr(settings, 'CONTENT_SECURITY_POLICY_REPORT_ONLY', False):
+            self.header = 'Content-Security-Policy-Report-Only'
+        else:
+            self.header = 'Content-Security-Policy'
+
+    def __call__(self, request):
+        response = self.get_response(request)
+
+        # Leave alone any policy a view has set itself
+        if self.policy and self.header not in response:
+            response[self.header] = self.policy
+
+        return response
Post/static/css/custom.css +28 -0
index b640ad5..5912a23 100644
@@ -129,3 +129,31 @@ th a, th span {
         word-wrap: break-word;
         word-break: break-all;
 }
+
+/* Styles below replace inline style attributes, which the Content
+ * Security Policy (style-src 'self') does not allow.
+ */
+.filter.visible, .sorting-arrows.visible {
+        visibility: visible;
+}
+
+.back-btn {
+        margin-top: 7px;
+}
+
+.details-title {
+        margin-left: 60px;
+}
+
+.pagesize-label {
+        padding-top: 5px;
+}
+
+select.pagesize {
+        margin-top: 5px;
+        margin-bottom: 0px;
+}
+
+.chart-svg {
+        height: 400px;
+}
Post/static/js/main.js +59 -0

67 lines not on this page · raw message

Post/test.py +60 -1

70 lines not on this page · raw message

Post/views.py +3 -5
index 89a57cf..add68d5 100644
@@ -296,11 +296,9 @@ def chart(request, template_name, key):
     if (alldata == {}):
         return HttpResponse("")
 
-    data = json.dumps([{ 'values': list(alldata)}])
-    # Replace MACHINE with x and dcount with value
-    # We do this in the string as it's more efficient
-    data = data.replace(key, "x")
-    data = data.replace("dcount", "y")
+    # Rename e.g. MACHINE to x and dcount to y for nvd3
+    data = [{ 'values': [{ 'x': item[key], 'y': item['dcount'] }
+                         for item in alldata] }]
 
     context = { 'data' : data,
                'chart_id': key,
README +35 -0
index d56fdbd..04f88d2 100644
@@ -38,6 +38,41 @@ In order to send an error report to the server, run the "send-error-report file_
 
 For more information on error reporting and log collection see: http://www.yoctoproject.org/docs/current/dev-manual/dev-manual.html#using-the-error-reporting-tool
 
+Content Security Policy
+-----------------------
+
+Every response carries a Content-Security-Policy header, added by
+Post.middleware.ContentSecurityPolicyMiddleware. The default policy in
+settings.py only allows resources served by the application itself:
+
+  default-src 'self'; script-src 'self'; style-src 'self';
+  img-src 'self' data:; font-src 'self'; connect-src 'self';
+  object-src 'none'; base-uri 'self'; form-action 'self';
+  frame-ancestors 'none'
+
+Inline scripts, inline event handlers (onclick=...), style attributes and
+eval() are blocked. When changing templates put JavaScript in
+Post/static/js/main.js and CSS in Post/static/css/custom.css. To pass data
+from a view to JavaScript use the json_script template filter or data-*
+attributes.
+
+The policy is configured with CONTENT_SECURITY_POLICY, a dict mapping each
+directive to a list of sources. For example, to also load images from a CDN
+and have browsers report violations:
+
+  CONTENT_SECURITY_POLICY['img-src'] = ["'self'", "data:", "https://cdn.example.com"]
+  CONTENT_SECURITY_POLICY['report-uri'] = ["https://example.com/csp-report"]
+
+Set CONTENT_SECURITY_POLICY = None to disable the header. Set
+CONTENT_SECURITY_POLICY_REPORT_ONLY = True to send the policy as
+Content-Security-Policy-Report-Only, so violations are reported but not
+blocked; this is useful when trying out a policy change. With the docker
+setup set CSP_REPORT_ONLY=1 in .env to do the same.
+
+If the web server in front of Django (Apache, nginx) also sets a
+Content-Security-Policy header, browsers enforce both, so set it in one place.
+The Django admin pages may lose some minor cosmetic styling under this policy.
+
 Maintenance
 -----------
 
project/settings.py +23 -0
index 33d8ef9..1ec6891 100644
@@ -48,6 +48,28 @@ MAX_UPLOAD_SIZE = "5242880"
 # Tolerance value to determine the distance between similar errors
 SIMILAR_FAILURE_DISTANCE = 10
 
+# Content Security Policy sent with every response by
+# Post.middleware.ContentSecurityPolicyMiddleware. Each directive maps to a
+# list of sources. All scripts, styles, fonts and images are served locally,
+# so no inline scripts or style attributes are allowed. Set to None to
+# disable the header.
+CONTENT_SECURITY_POLICY = {
+    'default-src': ["'self'"],
+    'script-src': ["'self'"],
+    'style-src': ["'self'"],
+    'img-src': ["'self'", "data:"],
+    'font-src': ["'self'"],
+    'connect-src': ["'self'"],
+    'object-src': ["'none'"],
+    'base-uri': ["'self'"],
+    'form-action': ["'self'"],
+    'frame-ancestors': ["'none'"],
+}
+
+# Send the policy as Content-Security-Policy-Report-Only so violations are
+# reported by browsers but not blocked. Useful when changing the policy.
+CONTENT_SECURITY_POLICY_REPORT_ONLY = False
+
 
 # Local time zone for this installation. Choices can be found here:
 # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
@@ -120,6 +142,7 @@ MIDDLEWARE = [
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
+    'Post.middleware.ContentSecurityPolicyMiddleware',
     # Uncomment the next line for simple clickjacking protection:
     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ]
project/settings.py.docker +23 -0
index 4dcb58d..b7ff669 100644
@@ -42,6 +42,28 @@ MAX_UPLOAD_SIZE = "5242880"
 # Tolerance value to determine the distance between similar errors
 SIMILAR_FAILURE_DISTANCE = 10
 
+# Content Security Policy sent with every response by
+# Post.middleware.ContentSecurityPolicyMiddleware. Each directive maps to a
+# list of sources. All scripts, styles, fonts and images are served locally,
+# so no inline scripts or style attributes are allowed. Set to None to
+# disable the header.
+CONTENT_SECURITY_POLICY = {
+    'default-src': ["'self'"],
+    'script-src': ["'self'"],
+    'style-src': ["'self'"],
+    'img-src': ["'self'", "data:"],
+    'font-src': ["'self'"],
+    'connect-src': ["'self'"],
+    'object-src': ["'none'"],
+    'base-uri': ["'self'"],
+    'form-action': ["'self'"],
+    'frame-ancestors': ["'none'"],
+}
+
+# Send the policy as Content-Security-Policy-Report-Only so violations are
+# reported by browsers but not blocked. Useful when changing the policy.
+CONTENT_SECURITY_POLICY_REPORT_ONLY = os.environ.get('CSP_REPORT_ONLY', '').lower() in ('1', 'true', 'yes')
+
 
 # Local time zone for this installation. Choices can be found here:
 # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
@@ -114,6 +136,7 @@ MIDDLEWARE = [
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
+    'Post.middleware.ContentSecurityPolicyMiddleware',
     # Uncomment the next line for simple clickjacking protection:
     # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ]
templates/discretebarchart.html +10 -39

49 lines not on this page · raw message

templates/error-details.html +2 -2
index 35bf0aa..abdc2d1 100644
@@ -6,10 +6,10 @@
     <div class="alert"><p>Build id not found</p></div>
   {% else %}
   <div class="page-header">
-    <a class="btn pull-left back-btn" style="margin-top:7px;" href="#">
+    <a class="btn pull-left back-btn" href="#">
       <i class="icon-arrow-left"></i>
     </a>
-    <h1 style="margin-left:60px;">
+    <h1 class="details-title">
         {% if detail.BUILD.ERROR_TYPE == error_types.RECIPE %}
         {{detail.RECIPE}}-{{detail.RECIPE_VERSION}}
         {% endif %}
templates/home.html +8 -44

97 lines not on this page · raw message

templates/latest-errors.html +8 -8
index b9f081e..2080210 100644
@@ -40,8 +40,8 @@
       {% endif %}
 
       <div class="pull-right">
-        <span class="help-inline" style="padding-top:5px;">Show rows: </span>
-        <select style="margin-top:5px;margin-bottom:0px;" class="input-mini pagesize">
+        <span class="help-inline pagesize-label">Show rows: </span>
+        <select class="input-mini pagesize">
           {% with "10 25 50 100 150" as list%}
           {% for i in list.split %}
           {% if request.session.limit == i|add:0 %}
@@ -93,10 +93,10 @@
 
                   {% if request.GET.order_by == "-"|add:col.field %}
                   <a href="#" class="sort-col sorted" data-order-by="{{col.field}}" >{{col.name}}</a>
-                  <span class="sorting-arrows" style="visibility: visible">&#9650</span>
+                  <span class="sorting-arrows visible">&#9650</span>
                   {% else %}
                   <a href="#" class="sort-col sorted" data-order-by="-{{col.field}}" >{{col.name}}</a>
-                   <span class="sorting-arrows" style="visibility: visible">&#9660</span>
+                   <span class="sorting-arrows visible">&#9660</span>
                    {% endif %}
                 {% else %}
                 {# default case is sorted by submitted_on #}
@@ -105,7 +105,7 @@
 
                   {% if col.clclass == "submitted_on" and not request.GET.order_by %}
                    <a href="#" class="sort-col sorted" data-order-by="-{{col.field}}" >{{col.name}}</a>
-                   <span class="sorting-arrows" style="visibility: visible">&#9660</span>
+                   <span class="sorting-arrows visible">&#9660</span>
 
                   {% elif col.clclass == "failure" %}
                   {{col.name}}
@@ -192,7 +192,7 @@
                   <div class="btn" rel="popover"
                       data-content='
                       {{ build_fail.BUILD.COMMIT|escape}}
-                      <p><a href="#" class="filter" style="visibility: visible" data-filter="{{build_fail.BUILD.COMMIT}}" data-type="commit" >Filter by commit</a>'
+                      <p><a href="#" class="filter visible" data-filter="{{build_fail.BUILD.COMMIT}}" data-type="commit" >Filter by commit</a>'
                       data-html="true"
                     >
                     {{ build_fail.BUILD.COMMIT|truncatechars:10}}
@@ -240,8 +240,8 @@
               {%endif%}
             </ul>
             <div class="pull-right">
-              <span class="help-inline" style="padding-top:5px;">Show rows:</span>
-              <select style="margin-top:5px;margin-bottom:0px;" class="input-mini pagesize">
+              <span class="help-inline pagesize-label">Show rows:</span>
+              <select class="input-mini pagesize">
                 {% with "10 25 50 100 150" as list%}
                 {% for i in list.split %}
                 {% if request.session.limit == i|add:0 %}
templates/registration/login.html +0 -9
index b8c1655..a6ae44f 100644
@@ -16,12 +16,3 @@
 <p>{% trans "Forgot password" %}? <a href="{% url "auth_password_reset" %}">{% trans "Reset it" %}</a>!</p>
 <p>{% trans "Don't have an account" %}? <a href="{% url "registration_register" %}">{% trans "Create one now" %}</a>!</p>
 {% endblock %}
-
-
-{% block scripts %}
-<script>
-    $(document).ready(function() {
-        $("#login_form input:text, #login_form textarea").first().focus();
-    });
-</script>
-{% endblock %}
templates/registration/password_reset_confirm.html +0 -9
index 09fc9c1..186ece5 100644
@@ -19,12 +19,3 @@
 {% endif %}
 
 {% endblock %}
-
-
-{% block scripts %}
-<script>
-    $(document).ready(function() {
-        $("#password_form input:text, #password_form textarea").first().focus();
-    });
-</script>
-{% endblock %}
templates/registration/password_reset_form.html +0 -9
index 1339756..067f15e 100644
@@ -12,12 +12,3 @@
   {% csrf_token %}
 </form>
 {% endblock %}
-
-
-{% block scripts %}
-<script>
-    $(document).ready(function() {
-        $("#password_form input:text, #password_form textarea").first().focus();
-    });
-</script>
-{% endblock %}
templates/registration/registration_form.html +0 -9
index 1f76ddb..32cb55b 100644
@@ -13,12 +13,3 @@
   {% csrf_token %}
 </form>
 {% endblock %}
-
-
-{% block scripts %}
-<script>
-    $(document).ready(function() {
-        $("#registration_form input:text, #registration_form textarea").first().focus();
-    });
-</script>
-{% endblock %}
Signature · 1 line
2.56.0