Merge branch 'maintenance' into devel
# Conflicts: # src/octoprint/server/views.py # src/octoprint/templates/dialogs/settings/api.jinja2
This commit is contained in:
commit
604d2f7811
7 files changed
+136
-11
No files matched your search
@@ -1328,6 +1328,14 @@ octoprint.server.http.routes
|
||||
view of the blueprint will thus not be reachable since processing of the request will directly be handed over
|
||||
to your defined handler class.
|
||||
|
||||
.. important::
|
||||
|
||||
If you want your route to support CORS if it's enabled in OctoPrint, your `RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_
|
||||
needs to implement the :class:`~octoprint.server.util.tornado.CorsSupportMixin` for this to work. Note that all of
|
||||
:class:`~octoprint.server.util.tornado.LargeResponseHandler`, :class:`~octoprint.server.util.tornado.UrlProxyHandler`,
|
||||
:class:`~octoprint.server.util.tornado.StaticDataHandler` and :class:`~octoprint.server.util.tornado.DeprecatedEndpointHandler`
|
||||
already implement this mixin.
|
||||
|
||||
.. important::
|
||||
|
||||
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
|
||||
|
||||
@@ -572,8 +572,11 @@ class Server(object):
|
||||
ioloop = IOLoop()
|
||||
ioloop.install()
|
||||
|
||||
enable_cors = settings().getBoolean(["api", "allowCrossOrigin"])
|
||||
|
||||
self._router = SockJSRouter(self._create_socket_connection, "/sockjs",
|
||||
session_kls=util.sockjs.ThreadSafeSession)
|
||||
session_kls=util.sockjs.ThreadSafeSession,
|
||||
user_settings=dict(websocket_allow_origin="*" if enable_cors else ""))
|
||||
|
||||
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
|
||||
|
||||
@@ -628,6 +631,7 @@ class Server(object):
|
||||
return joined
|
||||
|
||||
util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug
|
||||
util.tornado.CorsSupportMixin.ENABLE_CORS = enable_cors
|
||||
|
||||
server_routes = self._router.urls + [
|
||||
# various downloads
|
||||
|
||||
@@ -65,11 +65,50 @@ class RequestlessExceptionLoggingMixin(tornado.web.RequestHandler):
|
||||
exc_info=(typ, value, tb))
|
||||
|
||||
|
||||
#~~ CORS support
|
||||
|
||||
|
||||
class CorsSupportMixin(tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ mixin that
|
||||
makes sure to set CORS headers similarily to the Flask backed API endpoints.
|
||||
"""
|
||||
|
||||
ENABLE_CORS = False
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
if self.request.method != "OPTIONS" and origin and self.ENABLE_CORS:
|
||||
self.set_header("Access-Control-Allow-Origin", origin)
|
||||
|
||||
@tornado.web.asynchronous
|
||||
def options(self, *args, **kwargs):
|
||||
if self.ENABLE_CORS:
|
||||
origin = self.request.headers.get("Origin")
|
||||
method = self.request.headers.get("Access-Control-Request-Method")
|
||||
|
||||
# Allow the origin which made the XHR
|
||||
self.set_header("Access-Control-Allow-Origin", origin)
|
||||
# Allow the actual method
|
||||
self.set_header("Access-Control-Allow-Methods", method)
|
||||
# Allow for 10 seconds
|
||||
self.set_header("Access-Control-Max-Age", "10")
|
||||
|
||||
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
|
||||
custom_headers = self.request.headers.get("Access-Control-Request-Headers")
|
||||
if custom_headers is not None:
|
||||
self.set_header("Access-Control-Allow-Headers", custom_headers)
|
||||
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
|
||||
|
||||
#~~ WSGI middleware
|
||||
|
||||
|
||||
@tornado.web.stream_request_body
|
||||
class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin):
|
||||
class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin):
|
||||
"""
|
||||
A ``RequestHandler`` similar to ``tornado.web.FallbackHandler`` which fetches any files contained in the request bodies
|
||||
of content type ``multipart``, stores them in temporary files and supplies the ``fallback`` with the file's ``name``,
|
||||
@@ -871,7 +910,9 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar
|
||||
#~~ customized large response handler
|
||||
|
||||
|
||||
class LargeResponseHandler(RequestlessExceptionLoggingMixin, tornado.web.StaticFileHandler):
|
||||
class LargeResponseHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin,
|
||||
tornado.web.StaticFileHandler):
|
||||
"""
|
||||
Customized `tornado.web.StaticFileHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#tornado.web.StaticFileHandler>`_
|
||||
that allows delivery of the requested resource as attachment and access and request path validation through
|
||||
@@ -965,7 +1006,9 @@ class LargeResponseHandler(RequestlessExceptionLoggingMixin, tornado.web.StaticF
|
||||
##~~ URL Forward Handler for forwarding requests to a preconfigured static URL
|
||||
|
||||
|
||||
class UrlProxyHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandler):
|
||||
class UrlProxyHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin,
|
||||
tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that proxies
|
||||
requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment
|
||||
@@ -1058,7 +1101,18 @@ class UrlProxyHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandl
|
||||
return "%s%s" % (self._basename, extension)
|
||||
|
||||
|
||||
class StaticDataHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandler):
|
||||
class StaticDataHandler(RequestlessExceptionLoggingMixin,
|
||||
CorsSupportMixin,
|
||||
tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that returns
|
||||
static ``data`` of a configured ``content_type``.
|
||||
|
||||
Arguments:
|
||||
data (str): The data with which to respond
|
||||
content_type (str): The content type with which to respond. Defaults to ``text/plain``
|
||||
"""
|
||||
|
||||
def initialize(self, data="", content_type="text/plain"):
|
||||
self.data = data
|
||||
self.content_type = content_type
|
||||
@@ -1071,7 +1125,16 @@ class StaticDataHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHan
|
||||
self.finish()
|
||||
|
||||
|
||||
class DeprecatedEndpointHandler(tornado.web.RequestHandler):
|
||||
class DeprecatedEndpointHandler(CorsSupportMixin,
|
||||
tornado.web.RequestHandler):
|
||||
"""
|
||||
`tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>`_ that redirects
|
||||
to another ``url`` and logs a deprecation warning.
|
||||
|
||||
Arguments:
|
||||
url (str): URL to which to redirect
|
||||
"""
|
||||
|
||||
def initialize(self, url):
|
||||
self._url = url
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -417,10 +417,19 @@ def index():
|
||||
|
||||
|
||||
def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
|
||||
global _logger
|
||||
|
||||
#~~ a bunch of settings
|
||||
|
||||
first_run = settings().getBoolean(["server", "firstRun"])
|
||||
locales = dict((l.language, dict(language=l.language, display=l.display_name, english=l.english_name)) for l in LOCALES)
|
||||
|
||||
locales = dict()
|
||||
for l in LOCALES:
|
||||
try:
|
||||
locales[l.language] = dict(language=l.language, display=l.display_name, english=l.english_name)
|
||||
except:
|
||||
_logger.exception("Error while collecting available locales")
|
||||
|
||||
permissions = [permission.as_dict() for permission in Permissions.all()]
|
||||
extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions()))
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="settings-apiCors" data-bind="checked: api_allowCrossOrigin"> {{ _('Allow <a href="%(url)s">Cross Origin Resource Sharing (CORS)</a>', url = "https://en.wikipedia.org/wiki/Cross-origin_resource_sharing") }}
|
||||
<input type="checkbox" id="settings-apiCors" data-bind="checked: api_allowCrossOrigin"> {{ _('Allow <a href="%(url)s">Cross Origin Resource Sharing (CORS)</a>', url = "https://en.wikipedia.org/wiki/Cross-origin_resource_sharing") }} <label class="label label-info">{{ _('Needs restart') }}</label>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+41
-2
@@ -12,6 +12,15 @@ import logging
|
||||
|
||||
from tornado.web import asynchronous, RequestHandler
|
||||
|
||||
try:
|
||||
# python 3
|
||||
# noinspection PyCompatibility
|
||||
from urllib.parse import urlparse
|
||||
except ImportError:
|
||||
# python 2
|
||||
# noinspection PyCompatibility
|
||||
from urlparse import urlparse
|
||||
|
||||
CACHE_TIME = 31536000
|
||||
|
||||
LOG = logging.getLogger("tornado.general")
|
||||
@@ -126,5 +135,35 @@ class PreflightHandler(BaseHandler):
|
||||
|
||||
def verify_origin(self):
|
||||
"""Verify if request can be served"""
|
||||
# TODO: Verify origin
|
||||
return True
|
||||
|
||||
# adapted from sockjs.tornado.websocket.SockJSWebSocketHandler
|
||||
|
||||
origin = self.request.headers.get('Origin', '*')
|
||||
|
||||
# first check if connection from the same domain
|
||||
same_domain = self.check_origin(origin)
|
||||
if same_domain:
|
||||
return True
|
||||
|
||||
# this is cross-origin connection - check using SockJS server settings
|
||||
allow_origin = self.server.settings.get("websocket_allow_origin", "*")
|
||||
if allow_origin == "":
|
||||
return False
|
||||
elif allow_origin == "*":
|
||||
return True
|
||||
else:
|
||||
parsed_origin = urlparse(origin)
|
||||
origin = parsed_origin.netloc
|
||||
origin = origin.lower()
|
||||
return origin in allow_origin
|
||||
|
||||
def check_origin(self, origin):
|
||||
# adapted from tornado.websocket.WebSocketHandler
|
||||
parsed_origin = urlparse(origin)
|
||||
origin = parsed_origin.netloc
|
||||
origin = origin.lower()
|
||||
|
||||
host = self.request.headers.get("Host")
|
||||
|
||||
# Check to see that origin matches host directly, including ports
|
||||
return origin == host
|
||||
+3
-1
@@ -23,7 +23,9 @@ class SockJSWebSocketHandler(websocket.WebSocketHandler):
|
||||
|
||||
# this is cross-origin connection - check using SockJS server settings
|
||||
allow_origin = self.server.settings.get("websocket_allow_origin", "*")
|
||||
if allow_origin == "*":
|
||||
if allow_origin == "":
|
||||
return False
|
||||
elif allow_origin == "*":
|
||||
return True
|
||||
else:
|
||||
parsed_origin = urlparse(origin)
|
||||
|
||||
Reference in new issue
Block a user