♻ Remove UI_API_KEY & API disabling

With the inclusion of the ForceLogin plugin that doesn't serve a real
purpose anymore in most cases, and it was only ever more of a rate
limiting feature than an actual security measure anyhow. Plus it lead to
a ton of false security alarms along the lines of "OMG UI_API_KEY IN THE
SOCKET HANDSHAKE, PWNED!!1!".

On stock installations, the behaviour will be unchanged since the
ForceLogin plugin prevents any kind of API access without authentication
that isn't the login request itself, including access to blueprint
plugin endpoints that do not specify that they are unprotected.

If a user decides to disable the ForceLogin plugin but keep access
control enabled, anonymous API access will now be possible without API
key or the need to fetch the current UI API Key from the server via the
websocket or the source code of the index page. This is a change
compared to earlier behaviour, but with a very limited impact as as
mentioned the UI API Key was so far also easily obtainable either via
the websocket or by parsing a fresh copy of the HTML page.

If the user decides to disable access control, there's no change
compared to previous behaviour.

Disabling the API - which was so far the only real use case for having
the UI API Key in the first place apart from basic rate limiting - has
also been removed. Allowing this only made things horribly complex as
the default frontend fully depends on the API's availability. Users
who do not wish third parties to have access to the API should
simply leave the ForceLogin plugin enabled.
This commit is contained in:
Gina Häußge committed 2019-03-19 17:14:19 +01:00
1 parent 0069c94d35
commit 17a7e508c3
16 files changed
+43 -119

No files matched your search

+4 -3
View File
@@ -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
+4 -1
View File
@@ -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)
@@ -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");
+26 -34
View File
@@ -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
+1 -2
View File
@@ -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)
-2
View File
@@ -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():
+4 -27
View File
@@ -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()
+1 -2
View File
@@ -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:
-1
View File
@@ -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,
+1 -3
View File
@@ -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,
-1
View File
@@ -346,7 +346,6 @@ default_settings = {
"subscriptions": []
},
"api": {
"enabled": True,
"key": None,
"allowCrossOrigin": False,
"apps": {}
-19
View File
@@ -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, {
@@ -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);
@@ -9,7 +9,7 @@
</thead>
<tbody data-bind="foreach: users.listHelper.paginatedItems">
<tr>
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: $root.api_enabled() && apikey"><br /><small>{{ _('API Key') }}: <span data-bind="text: apikey"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(apikey) }"><i class="fa fa-copy"></i></a></small></span></td>
<td class="settings_users_name"><span data-bind="text: name"></span><span class="muted" data-bind="visible: apikey"><br /><small>{{ _('API Key') }}: <span data-bind="text: apikey"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(apikey) }"><i class="fa fa-copy"></i></a></small></span></td>
<td class="settings_users_active"><i class="fa" data-bind="css: { 'fa-check-square-o': active, 'fa-square-o': !active }"></i></td>
<td class="settings_users_admin"><i class="fa" data-bind="css: { 'fa-check-square-o': admin, 'fa-square-o': !admin }"></i></td>
<td class="settings_users_actions">
@@ -131,7 +131,7 @@
<span class="help-inline" data-bind="visible: $root.users.editorPasswordMismatch()">{{ _('Passwords do not match') }}</span>
</div>
</div>
<fieldset data-bind="visible: api_enabled">
<fieldset>
<legend>API Key</legend>
<div class="control-group">
<label class="control-label">{{ _('Current API Key') }}</label>
@@ -1,11 +1,4 @@
<form class="form-horizontal" onsubmit="return false;">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="settings-apiEnabled" data-bind="checked: api_enabled"> {{ _('Enable') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -25,7 +25,6 @@
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
var SOCKJS_CLOSE_NORMAL = 1000;
var UI_API_KEY = "{{ uiApiKey|e }}";
var VERSION = "{{ version.number|e }}";
var DISPLAY_VERSION = "{{ version.display|e }}";
var BRANCH = "{{ version.branch|e }}";