From 1acf69cb6de6e529859ad57d7a76945d874ed26d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 31 Jan 2019 17:38:10 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Add=20CORS=20headers=20to=20torn?= =?UTF-8?q?ado=20endpoints=20(if=20enabled)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes 1) of #3024 --- docs/plugins/hooks.rst | 8 +++ src/octoprint/server/__init__.py | 1 + src/octoprint/server/util/tornado.py | 73 ++++++++++++++++++++++++++-- 3 files changed, 77 insertions(+), 5 deletions(-) diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 59bf21e48..c5bb1db3a 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -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 `_ + 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. diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 9a173c76d..4d9a2bb4c 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -559,6 +559,7 @@ class Server(object): return joined util.tornado.RequestlessExceptionLoggingMixin.LOG_REQUEST = debug + util.tornado.CorsSupportMixin.ENABLE_CORS = settings().getBoolean(["api", "allowCrossOrigin"]) server_routes = self._router.urls + [ # various downloads diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index e40fbb2b9..55ff3876d 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -65,11 +65,50 @@ class RequestlessExceptionLoggingMixin(tornado.web.RequestHandler): exc_info=(typ, value, tb)) +#~~ CORS support + + +class CorsSupportMixin(tornado.web.RequestHandler): + """ + `tornado.web.RequestHandler `_ 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 `_ 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 `_ 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 `_ 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 `_ 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__)