Skip to content

Commit

Permalink
check origin of API requests
Browse files Browse the repository at this point in the history
    
protects agains CSRF on POST endpoints via forms.
  • Loading branch information
minrk committed Jul 9, 2015
1 parent cead281 commit b001be2
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions notebook/base/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
from http.client import responses
except ImportError:
from httplib import responses
try:
from urllib.parse import urlparse # Py 3
except ImportError:
from urlparse import urlparse # Py 2

from jinja2 import TemplateNotFound
from tornado import web
Expand Down Expand Up @@ -314,6 +318,50 @@ def write_error(self, status_code, **kwargs):
class APIHandler(IPythonHandler):
"""Base class for API handlers"""

def check_origin(self):
"""Check Origin for cross-site API requests.
Copied from WebSocket with changes:
- allow unspecified host/origin (e.g. scripts)
"""
if self.allow_origin == '*':
return True

host = self.request.headers.get("Host")
origin = self.request.headers.get("Origin")

# If no header is provided, assume it comes from a script/curl.
# We are only concerned with cross-site browser stuff here.
if origin is None or host is None:
return True

origin = origin.lower()
origin_host = urlparse(origin).netloc

# OK if origin matches host
if origin_host == host:
return True

# Check CORS headers
if self.allow_origin:
allow = self.allow_origin == origin
elif self.allow_origin_pat:
allow = bool(self.allow_origin_pat.match(origin))
else:
# No CORS headers deny the request
allow = False
if not allow:
self.log.warn("Blocking Cross Origin API request. Origin: %s, Host: %s",
origin, host,
)
return allow

def prepare(self):
if not self.check_origin():
raise web.HTTPError(404)
return super(APIHandler, self).prepare()

@property
def content_security_policy(self):
csp = '; '.join([
Expand Down

0 comments on commit b001be2

Please sign in to comment.