💥 Remove global API key
This commit is contained in:
1 parent
8ef57e2ab7
commit
43541ceebc
10 files changed
+57
-94
No files matched your search
+2
-17
@@ -12,11 +12,11 @@ Authorization
|
||||
=============
|
||||
|
||||
If :ref:`Access Control <sec-features-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 <sec-bundledplugins-appkeys>` (since 1.3.10).
|
||||
|
||||
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-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 <sec-features-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 <sec-api-push>`. 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -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),
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -251,8 +251,8 @@ $(function () {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (user === "_api") {
|
||||
user = "API client";
|
||||
if (user === "_cli") {
|
||||
user = "CLI";
|
||||
}
|
||||
|
||||
var file = self.filename();
|
||||
|
||||
Reference in new issue
Block a user