diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index f15f1fc1f..776b13af5 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -794,7 +794,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): def get_ui_custom_etag(self): """ Allows to use a custom way to calculate the ETag, instead of the default method (hashing - OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value). + OctoPrint's version, tracked file paths and ``LastModified`` value). Returns: str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). @@ -1391,8 +1391,9 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): # noinspection PyMethodMayBeStatic def is_blueprint_protected(self): """ - Whether a valid API key is needed to access the blueprint (the default) or not. Note that this only restricts - access to the blueprint's dynamic methods, static files are always accessible without API key. + Whether a login session is needed to access the blueprint if the forcelogin plugin is enabled or not. Requiring + a session is the default. Note that this only restricts access to the blueprint's dynamic methods, static files + are always accessible. """ return True diff --git a/src/octoprint/plugins/forcelogin/__init__.py b/src/octoprint/plugins/forcelogin/__init__.py index 27c9b6642..a9f510cca 100644 --- a/src/octoprint/plugins/forcelogin/__init__.py +++ b/src/octoprint/plugins/forcelogin/__init__.py @@ -116,7 +116,7 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, # so we make it possible. If this should get abused long term we can always turn this into -inf. return 0 - def get_before_request_handlers(self): + def get_before_request_handlers(self, plugin=None, *args, **kwargs): def check_login_required(): if not self.active: # not active, no handling @@ -125,6 +125,9 @@ class ForceLoginPlugin(octoprint.plugin.UiPlugin, if flask.request.endpoint in ("api.login",): return + if plugin is not None and not plugin.is_blueprint_protected(): + return + user = flask_login.current_user if user is None or user.is_anonymous() or not user.is_active(): return flask.make_response("Forbidden", 403) diff --git a/src/octoprint/plugins/forcelogin/static/js/main.js b/src/octoprint/plugins/forcelogin/static/js/main.js index 18494709b..b053fafa6 100644 --- a/src/octoprint/plugins/forcelogin/static/js/main.js +++ b/src/octoprint/plugins/forcelogin/static/js/main.js @@ -41,19 +41,6 @@ $(function() { OctoPrint.options.baseurl = BASE_URL; - OctoPrint.socket.onMessage("connected", function(data) { - var payload = data.data; - OctoPrint.options.apikey = payload.apikey; - - // update the API key directly in jquery's ajax options too, - // to ensure the fileupload plugin and any plugins still using - // $.ajax directly still work fine too - UI_API_KEY = payload["apikey"]; - $.ajaxSetup({ - headers: {"X-Api-Key": UI_API_KEY} - }); - }); - OctoPrint.socket.onConnected = function() { buttonElement.prop("disabled", false); offlineElement.removeClass("in"); diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 35efadda6..6b90ca4af 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -76,14 +76,12 @@ import octoprint.util.net import octoprint.filemanager.storage import octoprint.filemanager.analysis import octoprint.slicing -from octoprint.server.util import enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, corsRequestHandler, \ +from octoprint.server.util import loginFromApiKeyRequestHandler, corsRequestHandler, \ corsResponseHandler from octoprint.server.util.flask import PreemptiveCache from . import util -UI_API_KEY = ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes)) - VERSION = __version__ BRANCH = __branch__ DISPLAY_VERSION = __display_version__ @@ -1149,6 +1147,9 @@ class Server(object): import octoprint.server.views # do not remove or the index view won't be found + self._add_plugin_request_handlers_to_blueprint(api) + self._add_plugin_request_handlers_to_blueprint(apps) + blueprints = OrderedDict() blueprints["/api"] = api blueprints["/apps"] = apps @@ -1159,9 +1160,6 @@ class Server(object): # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves blueprints.update(self._prepare_asset_plugins()) - # make sure all before/after_request hook results are attached as well - self._add_plugin_request_handlers_to_blueprints(*blueprints.values()) - # register everything with the system for url_prefix, blueprint in blueprints.items(): app.register_blueprint(blueprint, url_prefix=url_prefix) @@ -1208,15 +1206,11 @@ class Server(object): if blueprint is None: return - if plugin.is_blueprint_protected(): - blueprint.before_request(corsRequestHandler) - blueprint.before_request(enforceApiKeyRequestHandler) - blueprint.before_request(loginFromApiKeyRequestHandler) - blueprint.after_request(corsResponseHandler) - else: - blueprint.before_request(corsRequestHandler) - blueprint.before_request(loginFromApiKeyRequestHandler) - blueprint.after_request(corsResponseHandler) + blueprint.before_request(corsRequestHandler) + blueprint.before_request(loginFromApiKeyRequestHandler) + blueprint.after_request(corsResponseHandler) + + self._add_plugin_request_handlers_to_blueprint(blueprint, plugin=plugin) url_prefix = "/plugin/{name}".format(name=name) app.register_blueprint(blueprint, url_prefix=url_prefix) @@ -1238,29 +1232,27 @@ class Server(object): return blueprint, url_prefix - def _add_plugin_request_handlers_to_blueprints(self, *blueprints): + def _add_plugin_request_handlers_to_blueprint(self, blueprint, plugin=None): before_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.before_request") after_hooks = octoprint.plugin.plugin_manager().get_hooks("octoprint.server.api.after_request") - for plugin, hook in before_hooks.items(): - for blueprint in blueprints: - try: - result = hook() - if isinstance(result, (list, tuple)): - for h in result: - blueprint.before_request(h) - except: - self._logger.exception("Error processing before_request hooks from plugin {}".format(plugin)) + for name, hook in before_hooks.items(): + try: + result = hook(plugin=plugin) + if isinstance(result, (list, tuple)): + for h in result: + blueprint.before_request(h) + except: + self._logger.exception("Error processing before_request hooks from plugin {}".format(name)) - for plugin, hook in after_hooks.items(): - for blueprint in blueprints: - try: - result = hook() - if isinstance(result, (list, tuple)): - for h in result: - blueprint.after_request(h) - except: - self._logger.exception("Error processing after_request hooks from plugin {}".format(plugin)) + for name, hook in after_hooks.items(): + try: + result = hook(plugin=plugin) + if isinstance(result, (list, tuple)): + for h in result: + blueprint.after_request(h) + except: + self._logger.exception("Error processing after_request hooks from plugin {}".format(name)) def _setup_assets(self): global app diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index c084dc18e..e67529d8b 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -19,7 +19,7 @@ import octoprint.server import octoprint.plugin from octoprint.server import admin_permission, NO_CONTENT from octoprint.settings import settings as s, valid_boolean_trues -from octoprint.server.util import noCachingExceptGetResponseHandler, enforceApiKeyRequestHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler +from octoprint.server.util import noCachingExceptGetResponseHandler, loginFromApiKeyRequestHandler, loginFromAuthorizationHeaderRequestHandler, corsRequestHandler, corsResponseHandler from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login, get_remote_address @@ -45,7 +45,6 @@ VERSION = "0.1" api.after_request(noCachingExceptGetResponseHandler) api.before_request(corsRequestHandler) -api.before_request(enforceApiKeyRequestHandler) api.before_request(loginFromAuthorizationHeaderRequestHandler) api.before_request(loginFromApiKeyRequestHandler) api.after_request(corsResponseHandler) diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index d1cd232a7..6c41c333d 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -82,7 +82,6 @@ def getSettings(): data = { "api": { - "enabled": s.getBoolean(["api", "enabled"]), "key": s.get(["api", "key"]) if admin_permission.can() else None, "allowCrossOrigin": s.get(["api", "allowCrossOrigin"]) }, @@ -371,7 +370,6 @@ def _saveSettings(data): return make_response("One of the configured folders is invalid", 400) if "api" in data.keys(): - if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"]) if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"]) if "appearance" in data.keys(): diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index d6610864a..2595eb027 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -26,29 +26,9 @@ from . import tornado from . import watchdog +@deprecated("API keys are no longer needed for anonymous access and thus this is now obsolete") def enforceApiKeyRequestHandler(): - """ - ``before_request`` handler for blueprints which makes sure an API key is provided - """ - - import octoprint.server - - if _flask.request.method == 'OPTIONS': - # we ignore OPTIONS requests here - return - - if _flask.request.endpoint and (_flask.request.endpoint == "static" or _flask.request.endpoint.endswith(".static")): - # no further handling for static resources - return - - apikey = get_api_key(_flask.request) - - if not apikey: - return _flask.make_response("No API key provided", 403) - - if apikey != octoprint.server.UI_API_KEY and not settings().getBoolean(["api", "enabled"]): - # api disabled => 403 - return _flask.make_response("API disabled", 403) + pass apiKeyRequestHandler = deprecated("apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler")(enforceApiKeyRequestHandler) @@ -57,7 +37,7 @@ def loginFromApiKeyRequestHandler(): """ ``before_request`` handler for blueprints which creates a login session for the provided api key (if available) - UI_API_KEY and app session keys are handled as anonymous keys here and ignored. + App session keys are handled as anonymous keys here and ignored. """ try: if loginUserFromApiKey(): @@ -82,9 +62,6 @@ def loginUserFromApiKey(): if not apikey: return False - if apikey == octoprint.server.UI_API_KEY: - return False - if octoprint.server.appSessionManager.validate(apikey): return False @@ -193,7 +170,7 @@ def optionsAllowOrigin(request): def get_user_for_apikey(apikey): - if settings().getBoolean(["api", "enabled"]) and apikey is not None: + if apikey is not None: if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey): # master key or an app session key was used return ApiUser() diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index aee3b547e..004bc6578 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1201,12 +1201,11 @@ def get_flask_user_from_request(request): """ import octoprint.server.util import flask_login - from octoprint.settings import settings user = None apikey = octoprint.server.util.get_api_key(request) - if settings().getBoolean(["api", "enabled"]) and apikey is not None: + if apikey is not None: user = octoprint.server.util.get_user_for_apikey(apikey) if user is None: diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 9aaad5bdb..378d5cf22 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -133,7 +133,6 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, o # connected => update the API key, might be necessary if the client was left open while the server restarted self._emit("connected", dict( - apikey=octoprint.server.UI_API_KEY, version=octoprint.server.VERSION, display_version=octoprint.server.DISPLAY_VERSION, branch=octoprint.server.BRANCH, diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index aff3865e2..ece448ba4 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -17,7 +17,7 @@ from flask import request, g, url_for, make_response, render_template, send_from import octoprint.plugin from octoprint.server import app, userManager, pluginManager, gettext, \ - debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH, preemptiveCache, \ + debug, LOCALES, VERSION, DISPLAY_VERSION, BRANCH, preemptiveCache, \ NOT_MODIFIED from octoprint.settings import settings from octoprint.filemanager import full_extension_tree, get_all_extensions @@ -293,7 +293,6 @@ def index(): import hashlib hash = hashlib.sha1() hash.update(octoprint.__version__) - hash.update(octoprint.server.UI_API_KEY) hash.update(",".join(sorted(files))) if lastmodified: hash.update(lastmodified) @@ -440,7 +439,6 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now): debug=debug, firstRun=first_run, version=dict(number=VERSION, display=DISPLAY_VERSION, branch=BRANCH), - uiApiKey=UI_API_KEY, templates=templates, pluginNames=plugin_names, locales=locales, diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 03b0de911..e371dc8f8 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -346,7 +346,6 @@ default_settings = { "subscriptions": [] }, "api": { - "enabled": True, "key": None, "allowCrossOrigin": False, "apps": {} diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js index a7697b0b8..0e60076b7 100644 --- a/src/octoprint/static/js/app/main.js +++ b/src/octoprint/static/js/app/main.js @@ -11,26 +11,12 @@ $(function() { //~~ OctoPrint client setup OctoPrint.options.baseurl = BASEURL; - OctoPrint.options.apikey = UI_API_KEY; var l10n = getQueryParameterByName("l10n"); if (l10n) { OctoPrint.options.locale = l10n; } - OctoPrint.socket.onMessage("connected", function(data) { - var payload = data.data; - OctoPrint.options.apikey = payload.apikey; - - // update the API key directly in jquery's ajax options too, - // to ensure the fileupload plugin and any plugins still using - // $.ajax directly still work fine too - UI_API_KEY = payload["apikey"]; - $.ajaxSetup({ - headers: {"X-Api-Key": UI_API_KEY} - }); - }); - //~~ some CoreUI specific stuff we put into OctoPrint.coreui OctoPrint.coreui = (function() { @@ -170,11 +156,6 @@ $(function() { } }); - // send the current UI API key with any request - $.ajaxSetup({ - headers: {"X-Api-Key": UI_API_KEY} - }); - //~~ Initialize file upload plugin $.widget("blueimp.fileupload", $.blueimp.fileupload, { diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 637370671..2645c72f1 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -104,7 +104,6 @@ $(function() { }))); self.locale_languages = _.keys(AVAILABLE_LOCALES); - self.api_enabled = ko.observable(undefined); self.api_key = ko.observable(undefined); self.api_allowCrossOrigin = ko.observable(undefined); diff --git a/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 b/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 index afebcacb2..a1dae0f7d 100644 --- a/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 +++ b/src/octoprint/templates/dialogs/settings/accesscontrol.jinja2 @@ -9,7 +9,7 @@