Stop content security policy blocking GA

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
This commit is contained in:
Chris Hill-Scott
2017-11-06 10:25:30 +00:00
parent 98c8ddca38
commit 1d10ad2247
2 changed files with 2 additions and 0 deletions

View File

@@ -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:;"

View File

@@ -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:;"