diff --git a/.github/fixtures/with_acl/config.yaml b/.github/fixtures/with_acl/config.yaml index f62e6554f..d409a5735 100644 --- a/.github/fixtures/with_acl/config.yaml +++ b/.github/fixtures/with_acl/config.yaml @@ -2,6 +2,7 @@ accessControl: salt: zXmvzI3uWuTLkSPOEfA2ZLwn3f3sGUNS devel: enableRateLimiter: false + enableCsrfProtection: false plugins: virtual_printer: enabled: true diff --git a/docs/api/general.rst b/docs/api/general.rst index 8eaede945..121839bf8 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -135,7 +135,7 @@ check the corresponding checkbox in the API settings dialog. .. warning:: - This means any browser page can send requests to the OctoPrint API. Authorization is still required however. + This means any browser page can send requests to the OctoPrint API. Authorization via an API-Key is still required however. If CORS is not enabled you will get errors like the following:: @@ -151,6 +151,29 @@ If CORS is not enabled you will get errors like the following:: the login mechanism (or reusing an existing login session). When accessing OctoPrint via CORS, you'll therefore always need to use an API key. +.. _sec-api-general-csrf: + +CSRF Protection +=============== + +.. versionadded:: 1.8.3 + +To protect OctoPrint against `CSRF attacks `_ against the non CORS affected upload endpoints, in case of browser session based authorization the API +is protected using the `Double Submit Cookie mitigation strategy `_. +On first page load of the UI, the login page or the recovery page, a ``csrf_token_P`` or ``csrf_token_P_R`` cookie is set +that can be read via client-side JavaScript. All requests towards the API that are not ``GET``, ``HEAD`` or ``OPTIONS`` +and rely on cookie based authorization (so not on an API key but rather an active login session) are required +to send both the ``csrf_token`` cookie as well as an ``X-CSRF-Token`` header containing its value. + +.. note:: + + If you use the :ref:`JS Client library `, this will take care of doing the needful for you. Any code in the *Core UI* calling + API functions through ``$.ajax`` or ``$.get`` or ``$.post`` will also take care of this for you. If you use another library for + accessing OctoPrint's API in a browser context, you'll need to make sure to send the ``X-CSRF-Token`` header yourself. Examples for + several JS frameworks can be found in the `OWASP cheatsheet on CSRF attacks `_. + Take a look at the implementations of ``OctoPrintClient.getCookie`` and ``OctoPrintClient.getHeaders`` in ``src/octoprint/static/js/client/base.js`` + for details on how to retrieve the cookie value and how to construct the header. + .. _sec-api-general-login: Login diff --git a/docs/jsclientlib/base.rst b/docs/jsclientlib/base.rst index 37416fd10..edd34058a 100644 --- a/docs/jsclientlib/base.rst +++ b/docs/jsclientlib/base.rst @@ -74,15 +74,39 @@ :returns string: The base url to use to access OctoPrint's API. -.. js:function:: OctoPrintClient.getRequestHeaders(additional) +.. js:function:: OctoPrintClient.getCookie(name) + + .. versionadded:: 1.8.3 + + Returns the value of the cookie with name ``name``. The port based cookie suffix and if + necessary also the script root based suffix will be automatically applied to the ``name`` + prior to looking up the value. + + :return string: The value of the cookie, if set & accessible, else an empty string. + +.. js:function:: OctoPrintClient.getRequestHeaders(method, additional, opts) + + .. versionchanged:: 1.8.3 Generates a dictionary of HTTP headers to use for API requests against OctoPrint with all necessary headers and any additionally provided ones. At the moment this entails setting the ``X-Api-Key`` header based on the current value of - ``OctoPrint.options.apikey`` at a minimum. + ``OctoPrint.options.apikey``, if set. Otherwise, for non-cross-domain requests targeting + methods other than ``GET``, ``HEAD`` or ``OPTIONS``, the current CSRF token is read from the + associated cookie and set as ``X-CSRF-Token``. - :param object additional: Additional headers to add to the request. + .. note:: + + Up until OctoPrint 1.8.3, this method's signature consisted only of the ``additional`` + parameter. It has been changed in a backward compatible way so that calling it with the + first parameter being the set of additional headers will still work. This mode of operation + is deprecated however and will be removed in a future version. + A warning will be logged to the debug console accordingly. + + :param str method: Method of the request for which to set headers + :param object additional: Additional headers to add to the request, optional. + :param object opts: Additional opts passed to the request, used to read cross domain setting, optional. :returns object: HTTP headers to use for requests. .. js:function:: OctoPrintClient.ajax(method, url, opts) diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index b43982670..31969fa21 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1352,8 +1352,39 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo" + .. warning:: + + As of OctoPrint 1.8.3, endpoints provided through a ``BlueprintPlugin`` do **not** automatically fall under + OctoPrint's :ref:`CSRF protection `, for reasons of backwards compatibility. There will be a short grace period before this changes. You + can and should however already opt into CSRF protection for your endpoints by implementing ``is_blueprint_csrf_protected`` + and returning ``True`` from it. You can exempt certain endpoints from CSRF protection by decorating them with + ``@octoprint.plugin.BlueprintPlugin.csrf_exempt``. + + .. code-block:: python + + class MyPlugin(octoprint.plugin.BlueprintPlugin): + @octoprint.plugin.BlueprintPlugin.route("/hello_world", methods=["GET"]) + def hello_world(self): + # This is a GET request and thus not subject to CSRF protection + return "Hello world!" + + @octoprint.plugin.BlueprintPlugin.route("/hello_you", methods=["POST"]) + def hello_you(self): + # This is a POST request and thus subject to CSRF protection. It is not exempt. + return "Hello you!" + + @octoprint.plugin.BlueprintPlugin.route("/hello_me", methods=["POST"]) + @octoprint.plugin.BlueprintPlugin.csrf_exempt() + def hello_me(self): + # This is a POST request and thus subject to CSRF protection, but this one is exempt. + return "Hello me!" + + def is_blueprint_csrf_protected(self): + return True ``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`. + + .. versionchanged:: 1.8.3 """ @staticmethod @@ -1372,7 +1403,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): def decorator(f): # We attach the decorator parameters directly to the function object, because that's the only place # we can access right now. - # This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/ + # This neat little trick was adapted from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/ if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None: f._blueprint_rules = defaultdict(list) f._blueprint_rules[f.__name__].append((rule, options)) @@ -1405,6 +1436,27 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): return decorator + @staticmethod + def csrf_exempt(): + """ + A decorator to mark a view method in your BlueprintPlugin as exempt from :ref:`CSRF protection `. This makes sense + if you offer an authenticated API for a certain workflow (see e.g. the bundled appkeys plugin) but in most + cases should not be needed. + + .. versionadded:: 1.8.3 + """ + + def decorator(f): + if ( + not hasattr(f, "_blueprint_csrf_exempt") + or f._blueprint_csrf_exempt is None + ): + f._blueprint_csrf_exempt = set() + f._blueprint_csrf_exempt.add(f.__name__) + return f + + return decorator + # noinspection PyProtectedMember def get_blueprint(self): """ @@ -1422,6 +1474,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): import flask + from octoprint.server.util.csrf import add_exempt_view + kwargs = self.get_blueprint_kwargs() blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs) @@ -1435,9 +1489,14 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): # this attribute was annotated with our @route decorator for blueprint_rule in f._blueprint_rules[member]: rule, options = blueprint_rule - blueprint.add_url_rule( - rule, options.pop("endpoint", f.__name__), view_func=f, **options - ) + endpoint = options.pop("endpoint", f.__name__) + blueprint.add_url_rule(rule, endpoint, view_func=f, **options) + + if ( + hasattr(f, "_blueprint_csrf_exempt") + and member in f._blueprint_csrf_exempt + ): + add_exempt_view(f"plugin.{self._identifier}.{endpoint}") if ( hasattr(f, "_blueprint_error_handler") @@ -1486,6 +1545,29 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): """ return True + # noinspection PyMethodMayBeStatic + def is_blueprint_csrf_protected(self): + """ + Whether a blueprint's endpoints are :ref:`CSRF protected `. For now, this defaults to ``False`` to leave it up to + plugins to decide which endpoints *should* be protected. Long term, this will default to ``True`` and hence + enforce protection unless a plugin opts out by returning False here. + + If you do not override this method in your mixin implementation, a warning will be logged to the console + to alert you of the requirement to make a decision here and to not rely on the default implementation, due to the + forthcoming change in implemented default behaviour. + + .. versionadded:: 1.8.3 + """ + self._logger.warning( + "The Blueprint of this plugin is relying on the default implementation of " + "is_blueprint_csrf_protected (newly added in OctoPrint 1.8.3), which in a future version will " + "be switched from False to True for security reasons. Plugin authors should ensure they explicitly " + "declare the CSRF protection status in their BlueprintPlugin mixin implementation. " + "Recommendation is to enable CSRF protection and exempt views that must not use it with the " + "octoprint.plugin.BlueprintPlugin.csrf_exempt decorator." + ) + return False + # noinspection PyMethodMayBeStatic def get_blueprint_api_prefixes(self): """ diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 82ea66c2b..2f5b7d2d5 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -291,6 +291,9 @@ class AnnouncementPlugin( def is_blueprint_protected(self): return False + def is_blueprint_csrf_protected(self): + return True + ##~~ EventHandlerPlugin def on_event(self, event, payload): diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index e3190ad36..bc3a396cc 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -161,6 +161,7 @@ class AppKeysPlugin( return NO_CONTENT @octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"]) + @octoprint.plugin.BlueprintPlugin.csrf_exempt() @no_firstrun_access def handle_request(self): data = flask.request.json @@ -196,7 +197,7 @@ class AppKeysPlugin( ) return response - @octoprint.plugin.BlueprintPlugin.route("/request/") + @octoprint.plugin.BlueprintPlugin.route("/request/", methods=["GET"]) @no_firstrun_access def handle_decision_poll(self, app_token): result = self._get_pending_by_app_token(app_token) @@ -214,7 +215,7 @@ class AppKeysPlugin( return flask.abort(404) - @octoprint.plugin.BlueprintPlugin.route("/auth/") + @octoprint.plugin.BlueprintPlugin.route("/auth/", methods=["GET"]) @no_firstrun_access def handle_auth_dialog(self, app_token): user_id = current_user.get_name() @@ -284,6 +285,9 @@ class AppKeysPlugin( def is_blueprint_protected(self): return False # No API key required to request API access + def is_blueprint_csrf_protected(self): + return True # protect anything that isn't explicitly marked as exempt + ##~~ SimpleApiPlugin mixin def get_api_commands(self): diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 5b140b2c3..19e1e69b3 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -356,6 +356,9 @@ class BackupPlugin( def is_blueprint_protected(self): return False + def is_blueprint_csrf_protected(self): + return True + ##~~ WizardPlugin def is_wizard_required(self): diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index a24e9dc3c..e2d9154f1 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -40,7 +40,6 @@ $(function () { dataType: "json", maxNumberOfFiles: 1, autoUpload: false, - headers: OctoPrint.getRequestHeaders(), add: function (e, data) { if (data.files.length === 0) { // no files? ignore diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 7752d50b4..9a9f27c2c 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -74,6 +74,11 @@ class CoreWizardPlugin( else: return {} + # ~~ BlueprintPlugin API + + def is_blueprint_csrf_protected(self): + return True + # ~~ WizardPlugin API def is_wizard_required(self): diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 9d0fbeebd..6e617bd78 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -134,6 +134,9 @@ class DiscoveryPlugin( def is_blueprint_protected(self): return False + def is_blueprint_csrf_protected(self): + return True + ##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup def on_startup(self, host, port): diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 8fcf640d1..5e3f2ec58 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -127,6 +127,9 @@ class LoggingPlugin( def is_blueprint_protected(self): return False + def is_blueprint_csrf_protected(self): + return True + def _get_usage(self): import psutil diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 5137995c1..7eeaf430c 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -609,6 +609,9 @@ class PluginManagerPlugin( def is_blueprint_protected(self): return False + def is_blueprint_csrf_protected(self): + return True + ##~~ EventHandlerPlugin def on_event(self, event, payload): diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 8783720e8..d1cdb4e09 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1453,6 +1453,9 @@ class SoftwareUpdatePlugin( def is_blueprint_protected(self): return False + def is_blueprint_csrf_protected(self): + return True + # ~~ Asset API def get_assets(self): diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 133b0937e..fd2ed32ac 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -127,6 +127,7 @@ from octoprint.printer.standard import Printer from octoprint.server.util import ( corsRequestHandler, corsResponseHandler, + csrfRequestHandler, loginFromApiKeyRequestHandler, requireLoginRequestHandler, ) @@ -1916,6 +1917,16 @@ class Server: blueprint.before_request(loginFromApiKeyRequestHandler) blueprint.after_request(corsResponseHandler) + if plugin.is_blueprint_csrf_protected(): + self._logger.debug( + f"CSRF Protection for Blueprint of plugin {name} is enabled" + ) + blueprint.before_request(csrfRequestHandler) + else: + self._logger.warning( + f"CSRF Protection for Blueprint of plugin {name} is DISABLED" + ) + if plugin.is_blueprint_protected(): blueprint.before_request(requireLoginRequestHandler) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index a3bc89339..14ef6e475 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -28,6 +28,7 @@ from octoprint.server import NO_CONTENT from octoprint.server.util import ( corsRequestHandler, corsResponseHandler, + csrfRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, noCachingExceptGetResponseHandler, @@ -68,6 +69,7 @@ api.after_request(noCachingExceptGetResponseHandler) api.before_request(corsRequestHandler) api.before_request(loginFromAuthorizationHeaderRequestHandler) api.before_request(loginFromApiKeyRequestHandler) +api.before_request(csrfRequestHandler) api.after_request(corsResponseHandler) # ~~ data from plugins diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 157959d53..79bf9e05e 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -148,6 +148,26 @@ def corsResponseHandler(resp): return resp +def csrfRequestHandler(): + """ + ``before_request`` handler for blueprints which checks for CRFS double token on + relevant requests & methods. + """ + from octoprint.server.util.csrf import validate_csrf_request + + if settings().getBoolean(["devel", "enableCsrfProtection"]): + validate_csrf_request(_flask.request) + + +def csrfResponseHandler(resp): + """ + ``after_request`` handler for updating the CSRF cookie on each response. + """ + from octoprint.server.util.csrf import add_csrf_cookie + + return add_csrf_cookie(resp) + + def noCachingResponseHandler(resp): """ ``after_request`` handler for blueprints which shall set no caching headers diff --git a/src/octoprint/server/util/csrf.py b/src/octoprint/server/util/csrf.py new file mode 100644 index 000000000..74821440a --- /dev/null +++ b/src/octoprint/server/util/csrf.py @@ -0,0 +1,97 @@ +"""CSRF double cookie implementation""" + +__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import flask + +from octoprint.server.util.flask import OctoPrintFlaskResponse + +exempt_views = set() + + +def _get_view_location(view): + if isinstance(view, str): + return view + else: + return f"{view.__module__}.{view.__name__}" + + +def add_exempt_view(view): + exempt_views.add(_get_view_location(view)) + + +def is_exempt(view): + if not view: + return False + + return _get_view_location(view) in exempt_views + + +def generate_csrf_token(): + import hashlib + import os + + from itsdangerous import URLSafeTimedSerializer + + value = hashlib.sha1(os.urandom(64)).hexdigest() + + secret = flask.current_app.config["SECRET_KEY"] + s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token") + + return s.dumps(value) + + +def validate_csrf_tokens(cookie, header): + import hmac + + from itsdangerous import URLSafeTimedSerializer + + if cookie is None or header is None: + return False + + secret = flask.current_app.config["SECRET_KEY"] + s = URLSafeTimedSerializer(secret, salt="octoprint-csrf-token") + + try: + # TODO: set max age for values, once we have a REST based heartbeat + # that takes care of regular cookie refresh + value_cookie = s.loads(cookie) + value_header = s.loads(header) + return hmac.compare_digest(value_cookie, value_header) + except Exception: + return False + + +def add_csrf_cookie(response): + if not isinstance(response, OctoPrintFlaskResponse): + return + + token = generate_csrf_token() + response.set_cookie("csrf_token", token, httponly=False) + return response + + +def validate_csrf_request(request): + if request.method in ["GET", "HEAD", "OPTIONS"]: + # Irrelevant method for CSRF, bypass + return + + if getattr(flask.g, "login_via_apikey", False): + # API key authorization, bypass + return + + if is_exempt(request.endpoint): + # marked as exempt, bypass + return + + cookie = request.cookies.get("csrf_token", None) + header = request.headers.get("X-CSRF-Token", None) + + if not validate_csrf_tokens(cookie, header): + flask.abort(400, "CSRF validation failed") + + +def csrf_exempt(view): + add_exempt_view(view) + return view diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 5757ce6c4..2654a8144 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -43,6 +43,7 @@ from octoprint.server.util import ( require_login_with, validate_local_redirect, ) +from octoprint.server.util.csrf import add_csrf_cookie from octoprint.settings import settings from octoprint.util import sv, to_bytes, to_unicode from octoprint.util.version import get_python_version_string @@ -223,7 +224,9 @@ def login(): except Exception: _logger.exception("Error processing theming CSS, ignoring") - return render_template("login.jinja2", **render_kwargs) + resp = make_response(render_template("login.jinja2", **render_kwargs)) + add_csrf_cookie(resp) + return resp @app.route("/recovery") @@ -254,7 +257,9 @@ def recovery(): except Exception: _logger.exception("Error adding backup upload size info, ignoring") - return render_template("recovery.jinja2", **render_kwargs) + resp = make_response(render_template("recovery.jinja2", **render_kwargs)) + add_csrf_cookie(resp) + return resp @app.route("/cached.gif") @@ -694,6 +699,8 @@ def index(): if response is None: return abort(404) + + add_csrf_cookie(response) return response diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d598419a7..1735fcb41 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -228,7 +228,7 @@ default_settings = { "preemptiveCache": {"exceptions": [], "until": 7}, "ipCheck": {"enabled": True, "trustedSubnets": []}, "allowFraming": False, - "cookies": {"secure": False, "samesite": None}, + "cookies": {"secure": False, "samesite": "strict"}, }, "webcam": { "webcamEnabled": True, @@ -471,6 +471,7 @@ default_settings = { "sockJsConnectTimeout": 30, "pluginTimings": False, "enableRateLimiter": True, + "enableCsrfProtection": True, }, } """The default settings of the core application.""" @@ -891,6 +892,7 @@ class Settings: "logs", ] ) + self.warn_about_risky_settings() def _init_basedir(self, basedir): if basedir is not None: @@ -923,6 +925,16 @@ class Settings: if len(folder_map.values()) != len(set(folder_map.values())): raise DuplicateFolderPaths(folders) + def warn_about_risky_settings(self): + if not self.getBoolean(["devel", "enableRateLimiter"]): + self._logger.warning( + "Rate limiting is disabled, this is a security risk. Do not run this in production." + ) + if not self.getBoolean(["devel", "enableCsrfProtection"]): + self._logger.warning( + "CSRF Protection is disabled, this is a security risk. Do not run this in production." + ) + def _get_default_folder(self, type): folder = default_settings["folder"][type] if folder is None: diff --git a/src/octoprint/static/js/app/client/base.js b/src/octoprint/static/js/app/client/base.js index 607f2c845..1cbf2e871 100644 --- a/src/octoprint/static/js/app/client/base.js +++ b/src/octoprint/static/js/app/client/base.js @@ -107,14 +107,75 @@ return url; }; - OctoPrintClient.prototype.getRequestHeaders = function (additional) { + OctoPrintClient.prototype.getCookieSuffix = function () { + if (!this.options.baseurl) return ""; + + try { + var url = new URL(this.options.baseurl); + } catch (e) { + var parsed = new URL(window.location); + var path = this.options.baseurl; + if (!path || path[0] !== "/") { + path = "/" + (path ? path : ""); + } + var url = new URL(parsed.protocol + "//" + parsed.host + path); + } + + var port = url.port || (url.protocol === "https:" ? 443 : 80); + if (url.pathname && url.pathname !== "/") { + var path = url.pathname; + if (path.endsWith("/")) { + path = path.substring(0, path.length - 1); + } + return "_P" + port + "_R" + path.replace(/\//, "|"); + } else { + return "_P" + port; + } + }; + + OctoPrintClient.prototype.getCookieName = function (name) { + return name + this.getCookieSuffix(); + }; + + OctoPrintClient.prototype.getCookie = function (name) { + name = this.getCookieName(name); + return ("; " + document.cookie) + .split("; " + name + "=") + .pop() + .split(";")[0]; + }; + + OctoPrintClient.prototype.getRequestHeaders = function (method, additional, opts) { + if (arguments.length <= 1) { + // versions prior 1.8.3 don't know method and opts + if (!_.isString(method)) { + additional = method; + console.warn( + "Calling OctoPrintClient.getRequestHeaders with additional " + + "headers as the first parameter is deprecated. Please " + + "consult the docs about the current signature and adjust " + + "your code accordingly." + ); + } + } + + method = method || "GET"; additional = additional || {}; + opts = opts || {}; var headers = $.extend({}, additional); if (this.options.apikey) { headers["X-Api-Key"] = this.options.apikey; + } else { + // no API key, so browser context, so let's make sure the CSRF token + // header is set + var csrfToken = this.getCookie("csrf_token"); + if (!/^(GET|HEAD|OPTIONS)$/.test(method) && csrfToken && !opts.crossDomain) { + headers["X-CSRF-Token"] = csrfToken; + } } + if (this.options.locale !== undefined) { headers["X-Locale"] = this.options.locale; } @@ -134,7 +195,7 @@ opts.url = urlToCall; } - var headers = this.getRequestHeaders(opts.headers); + var headers = this.getRequestHeaders(method, opts.headers, opts); var params = $.extend({}, opts); params.type = method; @@ -292,14 +353,15 @@ deferred.notify({loaded: e.loaded, total: e.total}); }); - var headers = this.getRequestHeaders(); + var method = "POST"; + var headers = this.getRequestHeaders(method); var urlToCall = url; if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) { urlToCall = this.getBaseUrl() + url; } - request.open("POST", urlToCall); + request.open(method, urlToCall); _.each(headers, function (value, key) { request.setRequestHeader(key, value); }); diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index 3e284b2f0..327e9c4c8 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -202,6 +202,21 @@ $(function () { //~~ AJAX setup + $.ajaxSetup({ + beforeSend: function (xhr, settings) { + // we already do that in the js client lib, but a lot of plugins don't use + // that but rather use $.ajax directly, so we need to do it here as well + var csrfToken = OctoPrint.getCookie("csrf_token"); + if ( + !/^(GET|HEAD|OPTIONS)$/.test(settings.type) && + csrfToken && + !this.crossDomain + ) { + xhr.setRequestHeader("X-CSRF-Token", csrfToken); + } + } + }); + // work around a stupid iOS6 bug where ajax requests get cached and only work once, as described at // http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results $.ajaxPrefilter(function (options, originalOptions, jqXHR) { @@ -219,7 +234,8 @@ $(function () { $.widget("blueimp.fileupload", $.blueimp.fileupload, { options: { dropZone: null, - pasteZone: null + pasteZone: null, + headers: OctoPrint.getRequestHeaders("POST") } }); diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 4a4864164..fee08211e 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -770,7 +770,6 @@ $(function () { dataType: "json", maxNumberOfFiles: 1, autoUpload: false, - headers: OctoPrint.getRequestHeaders(), add: function (e, data) { if (data.files.length == 0) { return false;