Reputation: 21
I didn't include the template code because it is irrelevant. This is the script tag in the template:
<script nonce="{{ CSP_NONCE }}" src="{% static 'js/mmImport.js' %}" defer
data-mmimporturl="{% url 'mmImport' %}">
</script>
Settings.py
MIDDLEWARE = [
'csp.middleware.CSPMiddleware'
....]
# Content Security Policy',
CSP_DEFAULT_SRC = ("'self'")
CSP_IMG_SRC = ("'self'")
CSP_STYLE_SRC = ("'self'")
CSP_SCRIPT_SRC = ("'self'")
CSP_INCLUDE_NONCE_IN = ('script-src')`
So two scenarios...
\[Error\] Refused to execute a script because its hash, its nonce, or 'unsafe-inline' does not appear in the script-src directive of the Content Security Policy. (mmHomepage, line 0)
I suspect it is the way a view/template is handled by bootstrap modals. Not sure where to look. I am new to Django-csp so not familiar with this. Just started familiarizing myself with the spec.
I also tried bringing this js code into the template, so not calling a separate file. No luck. Same error.
UPDATE: I used decorators to override CSP on the homepage view:
@method_decorator(csp_exempt)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
This allowed the modal template JS to run without any errors.
I confirmed using curl that the modal view/template still had the same CSP policy applied; It did.
Overriding the modal view with csp_exempt, however, and leaving the policy in place on the homepage, does not work.
So... essentially it appears that the homepage CSP is conflicting with the modal template CSP.
I had a breakthrough after reading through the CSP spec, but not sure if this is the right way to do this. It seems like CSP protects against scripts added dynamically. Which is what my code does with templates popping into existing templates running new scripts. Anyways, using this resolves the problem...
CSP_SCRIPT_SRC
= ("'self'", "'strict-dynamic'")`
This now works but it forces me to use a nonce for each script tag now. I really don't like this so I am considering updating the code to avoid the modal forms I am using. Any one else have experience with this kind of code or CSP to share some wisdom?
Upvotes: 1
Views: 109