From 1d10ad22474b5aad39dc7b5a3eb94cd0b3af5208 Mon Sep 17 00:00:00 2001 From: Chris Hill-Scott Date: Mon, 6 Nov 2017 10:25:30 +0000 Subject: [PATCH] Stop content security policy blocking GA MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In https://github.com/alphagov/notifications-admin/pull/1583 we changed our Google Analytics settings to use newer browsers’ `sendBeacon` feature. The advantage of this is that it > [ensures] that the data has been sent during the unloading of a > document [which] is something that has traditionally been difficult > for developers – https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon To transmit this data it uses a AJAX request (`XMLHttpRequest`) underneath. AJAX requests are governed by the `connect-src` content security policy (or the `default-src` if one is not present). `connect-src`: > Applies to XMLHttpRequest (AJAX), WebSocket or EventSource. If not > allowed the browser emulates a 400 HTTP status code. – https://content-security-policy.com/ Because we didn’t have one in place, `sendBeacon` requests to GA were getting blocked in browsers that support content security policy (pretty much everything better than IE11[1]). 1. https://caniuse.com/#feat=beacon --- app/__init__.py | 1 + tests/app/main/views/test_headers.py | 1 + 2 files changed, 2 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index 8cf3c7147..c45ad9a84 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -441,6 +441,7 @@ def useful_headers_after_request(response): response.headers.add('Content-Security-Policy', ( "default-src 'self' 'unsafe-inline';" "script-src 'self' *.google-analytics.com 'unsafe-inline' 'unsafe-eval' data:;" + "connect-src 'self' *.google-analytics.com;" "object-src 'self';" "font-src 'self' data:;" "img-src 'self' *.google-analytics.com *.notifications.service.gov.uk {} data:;" diff --git a/tests/app/main/views/test_headers.py b/tests/app/main/views/test_headers.py index 130beac20..7e06b3961 100644 --- a/tests/app/main/views/test_headers.py +++ b/tests/app/main/views/test_headers.py @@ -10,6 +10,7 @@ def test_owasp_useful_headers_set(client, mocker): assert response.headers['Content-Security-Policy'] == ( "default-src 'self' 'unsafe-inline';" "script-src 'self' *.google-analytics.com 'unsafe-inline' 'unsafe-eval' data:;" + "connect-src 'self' *.google-analytics.com;" "object-src 'self';" "font-src 'self' data:;" "img-src 'self' *.google-analytics.com *.notifications.service.gov.uk static-logos.test.com data:;"