From f2d874c5325546f2e7ab48dcff2d987eff2cd960 2015-06-20 20:03:10 From: Min RK Date: 2015-06-20 20:03:10 Subject: [PATCH] make content_security_policy a property and *add* `default-src: 'none'` to API handlers custom CSP applies to all handlers --- diff --git a/IPython/html/base/handlers.py b/IPython/html/base/handlers.py index f05009e..fc5563e 100644 --- a/IPython/html/base/handlers.py +++ b/IPython/html/base/handlers.py @@ -42,16 +42,24 @@ sys_info = json.dumps(get_sys_info()) class AuthenticatedHandler(web.RequestHandler): """A RequestHandler with an authenticated user.""" + + @property + def content_security_policy(self): + """The default Content-Security-Policy header + + Can be overridden by defining Content-Security-Policy in settings['headers'] + """ + return '; '.join([ + "frame-ancestors 'self'", + # Make sure the report-uri is relative to the base_url + "report-uri " + url_path_join(self.base_url, csp_report_uri), + ]) def set_default_headers(self): headers = self.settings.get('headers', {}) if "Content-Security-Policy" not in headers: - headers["Content-Security-Policy"] = ( - "frame-ancestors 'self'; " - # Make sure the report-uri is relative to the base_url - "report-uri " + url_path_join(self.base_url, csp_report_uri) + ";" - ) + headers["Content-Security-Policy"] = self.content_security_policy # Allow for overriding headers for header_name,value in headers.items() : @@ -311,8 +319,16 @@ class IPythonHandler(AuthenticatedHandler): class APIHandler(IPythonHandler): """Base class for API handlers""" + + @property + def content_security_policy(self): + csp = '; '.join([ + super(APIHandler, self).content_security_policy, + "default-src 'none'", + ]) + return csp + def finish(self, *args, **kwargs): - self.set_header('Content-Security-Policy', "default-src 'none'") self.set_header('Content-Type', 'application/json') return super(APIHandler, self).finish(*args, **kwargs) diff --git a/IPython/html/services/kernels/tests/test_kernels_api.py b/IPython/html/services/kernels/tests/test_kernels_api.py index b33142c..b779786 100644 --- a/IPython/html/services/kernels/tests/test_kernels_api.py +++ b/IPython/html/services/kernels/tests/test_kernels_api.py @@ -67,7 +67,8 @@ class KernelAPITest(NotebookTestBase): self.assertEqual(r.headers['Content-Security-Policy'], ( "frame-ancestors 'self'; " - "report-uri /api/security/csp-report;" + "report-uri /api/security/csp-report; " + "default-src 'none'" )) def test_main_kernel_handler(self): @@ -80,7 +81,8 @@ class KernelAPITest(NotebookTestBase): self.assertEqual(r.headers['Content-Security-Policy'], ( "frame-ancestors 'self'; " - "report-uri /api/security/csp-report;" + "report-uri /api/security/csp-report; " + "default-src 'none'" )) # GET request