More filtering in middlewares
jonprindiville opened this issue ยท 4 comments
I've started using django-csp
to add CSP headers to the responses coming out of a Django site. I notice, though, that the middlewares in the app seem to apply the header fairly indiscriminately.
I do see that they omit it in following cases:
- view was exempted using the supplied decorator
- view was exempted via the
CSP_EXCLUDE_URL_PREFIXES
- response was a 500 and
settings.DEBUG
is truthy - response already contained the header
I believe that there are additional cases that could reasonably be left out, but I wanted to discuss here before submitting a feature request or a PR...
-
Filtering on
response.status_code
: is there any reason to attach a CSP to HTTP redirects? Any other response codes that don't make sense with a CSP? -
Filtering on
response['content-type']
: I could imagine this varying more from project to project, but I found it simpler to excludeapplication/json
responses in the middleware versus finding and decorating all of the JSON views in my big old hairy codebase (but maybe I'm just lazy ๐)
I could imagine baking some ignore redirects behaviour in to the base CSPMiddleware
... but if someone has a reason that this is a bad idea, I'm all ears ๐
The content-type filtering... probably best to let folks decide that for each project. My initial though was obvious, only put it on HTML! but some Googling turns up folks talking about CSPs for SVG and PDF. I guess that could makes sense: Javascripts can run in those contexts... I don't really know about client support for CSPs in non-HTML contexts, though ๐ค
Hm... maybe I will just propose PRs for these things and see if that sparks any discussion ๐คทโโ
I think the mime type filtering is simple enough to implement by subclassing the provided middleware, but I am curious about whether there are other status codes to which a CSP shouldn't apply. Probably have to dive into the spec to figure that out.
Github claims that the current policy will apply to redirects, but I can't find it in the specs.
It's best to apply CSP to all responses since error or polymorphic type responses can be used for XSS or clickjacking.
I'd recommend using CSP report only mode or decorators like @csp_exempt
to test and build up your CSP header https://django-csp.readthedocs.io/en/latest/decorators.html#modifying-the-policy-with-decorators and subclassing the django-csp middleware if you really want to filter on status code or content type.