From 43541ceebc30a1ac40b5f98a31c800ab63546f59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 25 Nov 2020 15:43:06 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=A5=20Remove=20global=20API=20key?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/api/general.rst | 19 ++------------- docs/api/settings.rst | 17 ------------- src/octoprint/access/users.py | 12 ++++++---- src/octoprint/cli/client.py | 16 +++++++++---- src/octoprint/server/__init__.py | 18 ++++++++++++-- src/octoprint/server/api/settings.py | 19 +-------------- src/octoprint/server/util/__init__.py | 17 +++++++++---- src/octoprint/server/util/flask.py | 5 +++- src/octoprint/settings.py | 24 ++----------------- .../static/js/app/viewmodels/printerstate.js | 4 ++-- 10 files changed, 57 insertions(+), 94 deletions(-) diff --git a/docs/api/general.rst b/docs/api/general.rst index 0dacead1d..d2cbe3bd9 100644 --- a/docs/api/general.rst +++ b/docs/api/general.rst @@ -12,11 +12,11 @@ Authorization ============= If :ref:`Access Control ` is enabled OctoPrint's API expects an API key to be supplied with each request. This API -key can be either the globally configured one, a user specific one or an app and user specific one as generated by the +key can be either a user specific one or an app and user specific one as generated by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin ` (since 1.3.10). Clients are advised to implement the :ref:`Application Keys Plugin workflow ` first and -fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used. +fallback on directing the user to manually supply the the user specific API key. The API key must either be supplied in the custom HTTP header ``X-Api-Key``, e.g. @@ -53,21 +53,6 @@ will be denied with a :http:statuscode:`403`. If :ref:`Access Control ` is disabled, OctoPrint will treat any unauthenticated anonymous requests and thus also requests with an invalid or outright missing API key as requests with full admin rights! -.. note:: - - The API key requirements changed in 1.3.11. Up to that version, even if Access Control was disabled, all requests needed to - be supplied with an API Key. To make the webinterface work under these circumstances, an unauthenticated anonymous API key was injected into the - HTML page and also available on the :ref:`Push API `. The presence and ready availability of this unauthenticated - anonymous "UI API key" caused confusion and false alarm among users and didn't contribute to the security of the platform in a - meaningful way, so it was finally abandoned in 1.3.11. - -.. _fig-api-general-globalapikey: -.. figure:: ../images/settings-global-api-key.png - :align: center - :alt: Global API key in the API settings - - The global API key can be found in the "API" settings - .. _fig-api-general-userapikey: .. figure:: ../images/settings-user-api-key.png :align: center diff --git a/docs/api/settings.rst b/docs/api/settings.rst index ab2b89602..458c01ea3 100644 --- a/docs/api/settings.rst +++ b/docs/api/settings.rst @@ -71,23 +71,6 @@ Save settings } } -.. _sec-api-settings-generateapikey: - -Regenerate the system wide API key -================================== - -.. http:post:: /api/settings/apikey - - Generates a new system wide API key. - - Does not expect a body. Will return the generated API key as ``apikey`` - property in the JSON object contained in the response body. - - Requires admin rights. - - :status 200: No error - :status 403: No admin rights - .. _sec-api-settings-fetchtemplaatedata: Fetch template data diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index a0a6dc15e..62b61959f 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -45,8 +45,10 @@ class UserManager(GroupChangeListener): def anonymous_user_factory(self): return AnonymousUser([self._group_manager.guest_group]) - def api_user_factory(self): - return ApiUser([self._group_manager.admin_group, self._group_manager.user_group]) + def cli_user_factory(self): + return LocalCliUser( + [self._group_manager.admin_group, self._group_manager.user_group] + ) @property def enabled(self): @@ -1427,9 +1429,9 @@ class SessionUser(wrapt.ObjectProxy): ) -##~~ User object to use when global api key is used to access the API +##~~ User object to use when CLI key is used -class ApiUser(User): +class LocalCliUser(User): def __init__(self, groups): - User.__init__(self, "_api", "", True, [], groups) + User.__init__(self, "_cli", "", True, [], groups) diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 25d2b1b6b..e0d6f809f 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -3,6 +3,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import io import json +import os import click @@ -33,18 +34,23 @@ def create_client( https=False, prefix=None, ): - assert host is not None or settings is not None assert port is not None or settings is not None assert apikey is not None or settings is not None if not host: - host = settings.get(["server", "host"]) - host = host if host != "0.0.0.0" else "127.0.0.1" + host = "127.0.0.1" if not port: port = settings.getInt(["server", "port"]) if not apikey: - apikey = settings.get(["api", "key"]) + cli_key_file = os.path.join(settings.getBaseFolder("generated"), "cli.key") + try: + with io.open(cli_key_file, "r", encoding="utf8") as f: + apikey = f.readline() + except Exception: + raise FatalStartupError( + "Can not authenticate with server at {}:{}, no key".format(host, port) + ) baseurl = octoprint_client.build_base_url( https=https, @@ -84,7 +90,7 @@ def client(ctx, apikey, host, port, httpuser, httppass, https, prefix): """Basic API client.""" try: settings = None - if not host or not port or not apikey: + if not port or not apikey: settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 35b90a75e..f72857004 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -88,6 +88,8 @@ jsonDecoder = None connectivityChecker = None environmentDetector = None +cli_key = None + principals = Principal(app) import octoprint.access.groups as groups # noqa: E402 @@ -174,8 +176,8 @@ def load_user(id): if id is None: return None - if id == "_api": - return userManager.api_user_factory() + if id == "_cli": + return userManager.cli_user_factory() if session and "usersession.id" in session: sessionid = session["usersession.id"] @@ -292,6 +294,7 @@ class Server: global environmentDetector global debug global safe_mode + global cli_key from tornado.ioloop import IOLoop from tornado.web import Application @@ -335,6 +338,7 @@ class Server: util.tornado.fix_websocket_check_origin() util.flask.fix_flask_jsonify() + cli_key = self._setup_cli_key() self._setup_mimetypes() additional_translation_folders = [] @@ -1786,6 +1790,16 @@ class Server: extra={"plugin": name}, ) + def _setup_cli_key(self): + from octoprint.util import generate_api_key + + cli_key_file = os.path.join(self._settings.getBaseFolder("generated"), "cli.key") + cli_key = generate_api_key() + with io.open(cli_key_file, "w", encoding="utf8") as f: + f.write(cli_key) + + return cli_key + def _setup_mimetypes(self): # Safety measures for Windows... apparently the mimetypes module takes its translation from the windows # registry, and if for some weird reason that gets borked the reported MIME types can be all over the place. diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 0c64d550a..8b51d1681 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -12,7 +12,7 @@ import octoprint.plugin import octoprint.util from octoprint.access.permissions import Permissions from octoprint.server import pluginManager, printer, userManager -from octoprint.server.api import NO_CONTENT, api +from octoprint.server.api import api from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking from octoprint.settings import settings, valid_boolean_trues @@ -99,7 +99,6 @@ def getSettings(): data = { "api": { - "key": s.get(["api", "key"]) if Permissions.ADMIN.can() else None, "allowCrossOrigin": s.get(["api", "allowCrossOrigin"]), }, "appearance": { @@ -388,22 +387,6 @@ def setSettings(): return getSettings() -@api.route("/settings/apikey", methods=["POST"]) -@no_firstrun_access -@Permissions.SETTINGS.require(403) -def generateApiKey(): - apikey = settings().generateApiKey() - return jsonify(apikey=apikey) - - -@api.route("/settings/apikey", methods=["DELETE"]) -@no_firstrun_access -@Permissions.SETTINGS.require(403) -def deleteApiKey(): - settings().deleteApiKey() - return NO_CONTENT - - @api.route("/settings/templates", methods=["GET"]) @no_firstrun_access @Permissions.SETTINGS.require(403) diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index f8dc4cf2f..b7bc9537e 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -10,6 +10,7 @@ PY3 = sys.version_info[0] == 3 # keeping this for backwards compatibility import flask as _flask import flask_login +import netaddr import octoprint.server import octoprint.timelapse @@ -66,7 +67,8 @@ def loginUserFromApiKey(): if not apikey: return False - user = get_user_for_apikey(apikey) + remote_address = flask.get_remote_address(_flask.request) + user = get_user_for_apikey(apikey, remote_address=remote_address) if user is None: # invalid API key = no API key return False @@ -199,11 +201,16 @@ def optionsAllowOrigin(request): return resp -def get_user_for_apikey(apikey): +def get_user_for_apikey(apikey, remote_address=None): if apikey is not None: - if apikey == settings().get(["api", "key"]): - # master key was used - return octoprint.server.userManager.api_user_factory() + if apikey == octoprint.server.cli_key and remote_address: + try: + remote_address = netaddr.IPAddress(remote_address) + if remote_address.is_loopback(): + # CLI key was used on loopback + return octoprint.server.userManager.cli_user_factory() + except Exception: + pass user = octoprint.server.userManager.find_user(apikey=apikey) if user is not None: diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index ea7f55470..0bef467e6 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1459,9 +1459,12 @@ def get_flask_user_from_request(request): user = None apikey = octoprint.server.util.get_api_key(request) + remote_address = get_remote_address(request) if apikey is not None: # user from api key? - user = octoprint.server.util.get_user_for_apikey(apikey) + user = octoprint.server.util.get_user_for_apikey( + apikey, remote_address=remote_address + ) if user is None: # user still None -> current session user diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 4aae4da91..fed548588 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -33,13 +33,7 @@ from collections.abc import KeysView import yaml import yaml.parser -from octoprint.util import ( - CaseInsensitiveSet, - atomic_write, - dict_merge, - generate_api_key, - is_hidden_path, -) +from octoprint.util import CaseInsensitiveSet, atomic_write, dict_merge, is_hidden_path _APPNAME = "OctoPrint" @@ -385,7 +379,7 @@ default_settings = { }, "slicing": {"enabled": True, "defaultSlicer": None, "defaultProfiles": None}, "events": {"enabled": True, "subscriptions": []}, - "api": {"key": None, "allowCrossOrigin": False, "apps": {}}, + "api": {"allowCrossOrigin": False, "apps": {}}, "terminalFilters": [ { "name": "Suppress temperature messages", @@ -672,10 +666,6 @@ class Settings: self._configfile = os.path.join(self._basedir, "config.yaml") self.load(migrate=True) - apikey = self.get(["api", "key"]) - if not apikey or apikey == "n/a": - self.generateApiKey() - self._script_env = self._init_script_templating() self.sanity_check_folders( @@ -2127,16 +2117,6 @@ class Settings: with atomic_write(filename, mode="wt", max_permissions=0o666) as f: f.write(script) - def generateApiKey(self): - apikey = generate_api_key() - self.set(["api", "key"], apikey) - self.save(force=True) - return apikey - - def deleteApiKey(self): - self.set(["api", "key"], None) - self.save(force=True) - def _default_basedir(applicationName): # taken from http://stackoverflow.com/questions/1084697/how-do-i-store-desktop-application-data-in-a-cross-platform-way-for-python diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 515c6fa71..64e519825 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -251,8 +251,8 @@ $(function () { return ""; } - if (user === "_api") { - user = "API client"; + if (user === "_cli") { + user = "CLI"; } var file = self.filename();