Chef Codev
Chef Codev

Reputation: 21

Why does my content-security-profile (django-csp) not work properly for a view/template loaded in a bootstrap modal? Works fine otherwise

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...

  1. I load this view/template in a modal that is in the homepage. If I include 'unsafe-inline, no issues. It works. Form/view/template behaves normally. Without unsafe-inline and just the above policies, it gives the following error:
\[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)
  1. I load the view as its own page/template; not a modal. Straight forward Django template. With CSP policies as above, the page works normally. No errors.

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

Answers (0)

Related Questions