Use CSP middleware to block online sources in DEBUG mode
See original GitHub issueSummary
With KA Lite, we debugged some issues fetching online sources with JavaScript.
During this process, I had a theory that external content (fetched from our update/content server) was blocked due to inadequate security definitions. This wasn’t true, however a CSP middleware came out of it.
I made it so it only triggers in DEBUG=True
mode. The advantage is that we can ensure that ALL resources fetched from online sources etc. are blocked while we are developing. Or explicitly allowed. That way, we can ensure that we don’t accidentally fetch an online source during testing or development that won’t actually be available in an offline context.
class CSPMiddleware:
"""
Implements the Content-Security-Policy response header, which
conforming user-agents can use to restrict the permitted sources
of various content.
See http://www.w3.org/TR/CSP/
"""
def process_response(self, request, response):
# Check for debug view
status_code = response.status_code
if not settings.DEBUG or status_code in (403, 404, 500):
return response
header = 'Content-Security-Policy'
if getattr(settings, 'CSP_REPORT_ONLY', False):
header += '-Report-Only'
response[header] = "default-src 'self' 'unsafe-eval' 'unsafe-inline' data: *.learningequality.org; img-src data: *; script-src 'self' *.learningequality.org 'unsafe-eval' 'unsafe-inline'"
return response
How to reproduce
- Use an external JS library that has an online-dependent behavior
- Don’t notice it during development or testing
- Be baffled when stuff breaks offline.
Real-life consequences (anything community should be aware of, for instance how it affects your deployment)
I think the threat is real, as we don’t necessary profile the networking behavior of all client-side browser scripts.
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (8 by maintainers)
Top GitHub Comments
Would be interesting to see whether this is transitive into sandboxed iframes. We probably wouldn’t want to prevent them from doing inline JS or whatever they want (within the confines of the
sandbox
specifications), but we similarly would want to prevent them from trying to load online resources, as described in the initial proposal above.A supplemental approach can be Zulip’s test suite that prohibits remote connections during tests:
https://zulip.readthedocs.io/en/latest/testing/testing.html#internet-access-inside-test-suites