Skip to content

Commit

Permalink
forward-port security fixes from 3.2
Browse files Browse the repository at this point in the history
- APIHandler for mime-type and Content-Security-Policy
- next_url confined to base_url
  • Loading branch information
minrk committed Jun 22, 2015
2 parents 0dcfc79 + e4cc3a6 commit 0ceeb5c
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 37 deletions.
14 changes: 11 additions & 3 deletions notebook/auth/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ def _render(self, message=None):

def get(self):
if self.current_user:
self.redirect(self.get_argument('next', default=self.base_url))
next_url = self.get_argument('next', default=self.base_url)
if not next_url.startswith(self.base_url):
# require that next_url be absolute path within our path
next_url = self.base_url
self.redirect(next_url)
else:
self._render()

Expand All @@ -47,8 +51,12 @@ def post(self):
else:
self._render(message={'error': 'Invalid password'})
return

self.redirect(self.get_argument('next', default=self.base_url))

next_url = self.get_argument('next', default=self.base_url)
if not next_url.startswith(self.base_url):
# require that next_url be absolute path within our path
next_url = self.base_url
self.redirect(next_url)

@classmethod
def get_user(cls, handler):
Expand Down
43 changes: 34 additions & 9 deletions notebook/base/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,24 @@

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() :
Expand Down Expand Up @@ -301,7 +309,22 @@ def write_error(self, status_code, **kwargs):
html = self.render_template('error.html', **ns)

self.write(html)



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-Type', 'application/json')
return super(APIHandler, self).finish(*args, **kwargs)


class Template404(IPythonHandler):
Expand Down Expand Up @@ -364,13 +387,15 @@ def wrapper(self, *args, **kwargs):
try:
result = yield gen.maybe_future(method(self, *args, **kwargs))
except web.HTTPError as e:
self.set_header('Content-Type', 'application/json')
status = e.status_code
message = e.log_message
self.log.warn(message)
self.set_status(e.status_code)
reply = dict(message=message, reason=e.reason)
self.finish(json.dumps(reply))
except Exception:
self.set_header('Content-Type', 'application/json')
self.log.error("Unhandled error in API request", exc_info=True)
status = 500
message = "Unknown server error"
Expand All @@ -393,7 +418,7 @@ def wrapper(self, *args, **kwargs):
# to minimize subclass changes:
HTTPError = web.HTTPError

class FileFindHandler(web.StaticFileHandler):
class FileFindHandler(IPythonHandler, web.StaticFileHandler):
"""subclass of StaticFileHandler for serving files from a search path"""

# cache search results, don't search for files more than once
Expand Down Expand Up @@ -447,7 +472,7 @@ def validate_absolute_path(self, root, absolute_path):
return super(FileFindHandler, self).validate_absolute_path(root, absolute_path)


class ApiVersionHandler(IPythonHandler):
class APIVersionHandler(APIHandler):

@json_errors
def get(self):
Expand Down Expand Up @@ -518,5 +543,5 @@ def get(self, path=''):

default_handlers = [
(r".*/", TrailingSlashHandler),
(r"api", ApiVersionHandler)
(r"api", APIVersionHandler)
]
4 changes: 2 additions & 2 deletions notebook/services/config/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
from tornado import web

from ipython_genutils.py3compat import PY3
from ...base.handlers import IPythonHandler, json_errors
from ...base.handlers import APIHandler, json_errors

class ConfigHandler(IPythonHandler):
class ConfigHandler(APIHandler):
SUPPORTED_METHODS = ('GET', 'PUT', 'PATCH')

@web.authenticated
Expand Down
8 changes: 4 additions & 4 deletions notebook/services/contents/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from jupyter_client.jsonutil import date_default

from notebook.base.handlers import (
IPythonHandler, json_errors, path_regex,
IPythonHandler, APIHandler, json_errors, path_regex,
)


Expand Down Expand Up @@ -78,7 +78,7 @@ def validate_model(model, expect_content):
)


class ContentsHandler(IPythonHandler):
class ContentsHandler(APIHandler):

SUPPORTED_METHODS = (u'GET', u'PUT', u'PATCH', u'POST', u'DELETE')

Expand Down Expand Up @@ -260,7 +260,7 @@ def delete(self, path=''):
self.finish()


class CheckpointsHandler(IPythonHandler):
class CheckpointsHandler(APIHandler):

SUPPORTED_METHODS = ('GET', 'POST')

Expand Down Expand Up @@ -289,7 +289,7 @@ def post(self, path=''):
self.finish(data)


class ModifyCheckpointsHandler(IPythonHandler):
class ModifyCheckpointsHandler(APIHandler):

SUPPORTED_METHODS = ('POST', 'DELETE')

Expand Down
8 changes: 4 additions & 4 deletions notebook/services/kernels/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
from ipython_genutils.py3compat import cast_unicode
from notebook.utils import url_path_join, url_escape

from ...base.handlers import IPythonHandler, json_errors
from ...base.handlers import IPythonHandler, APIHandler, json_errors
from ...base.zmqhandlers import AuthenticatedZMQStreamHandler, deserialize_binary_message

from jupyter_client import protocol_version as client_protocol_version

class MainKernelHandler(IPythonHandler):
class MainKernelHandler(APIHandler):

@web.authenticated
@json_errors
Expand Down Expand Up @@ -49,7 +49,7 @@ def post(self):
self.finish(json.dumps(model))


class KernelHandler(IPythonHandler):
class KernelHandler(APIHandler):

SUPPORTED_METHODS = ('DELETE', 'GET', 'OPTIONS')

Expand All @@ -76,7 +76,7 @@ def options(self, kernel_id):
self.finish()


class KernelActionHandler(IPythonHandler):
class KernelActionHandler(APIHandler):

@web.authenticated
@json_errors
Expand Down
6 changes: 4 additions & 2 deletions notebook/services/kernels/tests/test_kernels_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ def test_default_kernel(self):

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):
Expand All @@ -82,7 +83,8 @@ def test_main_kernel_handler(self):

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
Expand Down
6 changes: 3 additions & 3 deletions notebook/services/kernelspecs/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from tornado import web

from ...base.handlers import IPythonHandler, json_errors
from ...base.handlers import APIHandler, json_errors
from ...utils import url_path_join

def kernelspec_model(handler, name):
Expand Down Expand Up @@ -43,7 +43,7 @@ def kernelspec_model(handler, name):
)
return d

class MainKernelSpecHandler(IPythonHandler):
class MainKernelSpecHandler(APIHandler):
SUPPORTED_METHODS = ('GET', 'OPTIONS')

@web.authenticated
Expand All @@ -70,7 +70,7 @@ def options(self):
self.finish()


class KernelSpecHandler(IPythonHandler):
class KernelSpecHandler(APIHandler):
SUPPORTED_METHODS = ('GET',)

@web.authenticated
Expand Down
4 changes: 2 additions & 2 deletions notebook/services/nbconvert/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

from tornado import web

from ...base.handlers import IPythonHandler, json_errors
from ...base.handlers import APIHandler, json_errors

class NbconvertRootHandler(IPythonHandler):
class NbconvertRootHandler(APIHandler):
SUPPORTED_METHODS = ('GET',)

@web.authenticated
Expand Down
4 changes: 2 additions & 2 deletions notebook/services/security/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@

from tornado import gen, web

from ...base.handlers import IPythonHandler, json_errors
from ...base.handlers import APIHandler, json_errors
from . import csp_report_uri

class CSPReportHandler(IPythonHandler):
class CSPReportHandler(APIHandler):
'''Accepts a content security policy violation report'''
@web.authenticated
@json_errors
Expand Down
6 changes: 3 additions & 3 deletions notebook/services/sessions/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@

from tornado import web

from ...base.handlers import IPythonHandler, json_errors
from ...base.handlers import APIHandler, json_errors
from jupyter_client.jsonutil import date_default
from notebook.utils import url_path_join, url_escape
from jupyter_client.kernelspec import NoSuchKernel


class SessionRootHandler(IPythonHandler):
class SessionRootHandler(APIHandler):

@web.authenticated
@json_errors
Expand Down Expand Up @@ -74,7 +74,7 @@ def options(self):
self.set_header('Access-Control-Allow-Headers', 'accept, content-type')
self.finish()

class SessionHandler(IPythonHandler):
class SessionHandler(APIHandler):

SUPPORTED_METHODS = ('GET', 'PATCH', 'DELETE')

Expand Down
6 changes: 3 additions & 3 deletions notebook/terminal/api_handlers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import json
from tornado import web, gen
from ..base.handlers import IPythonHandler, json_errors
from ..base.handlers import APIHandler, json_errors
from ..utils import url_path_join

class TerminalRootHandler(IPythonHandler):
class TerminalRootHandler(APIHandler):
@web.authenticated
@json_errors
def get(self):
Expand All @@ -19,7 +19,7 @@ def post(self):
self.finish(json.dumps({'name': name}))


class TerminalHandler(IPythonHandler):
class TerminalHandler(APIHandler):
SUPPORTED_METHODS = ('GET', 'DELETE')

@web.authenticated
Expand Down

0 comments on commit 0ceeb5c

Please sign in to comment.