jazzband/django-analytical

Javascript runs afoul of content security policy

SKisContent opened this issue · 4 comments

On sites that have a HTTP content security policy that is not "unsafe-inline", the analytics Javascript fails to execute. One solution would be to let users specify a string in the settings that is inserted into the <script> opening tag.

Thanks for the notice, @SKisContent. What would be required specifically to work around this, can you give a bit more detail?

One CSPs option is to add a nonce="xxx" attribute to the <script> tag.
<script type="text/javascript" nonce="random_string_of_alphanumericals">
The django-csp-nonce module does this. For analytical this option could be manipulated through the settings. However, for a dynamically generated nonce, this value needs to be updated during the HTML template rendering. Since AnalyticalNode is its own Node and injects the full <script></script> section into the rendered page HTML, it would need to do the value substitution on its own.

Another solution would be to serve up a special view that served the normally inline code as a javascript file instead. (See, for instance, how Matomo/Piwik recommends serving a tracking.js file: https://matomo.org/faq/general/faq_20904/)

django-csp has a context processor to inject nonce into render context and also can add it to response headers.

If analytics nodes could add a placeholder in their script template to handle this template variable it could be easy to use.