From 398e10588c55185a1f7e37101422aa23e7a4f1e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 9 Nov 2017 18:54:51 +0100 Subject: [PATCH] Slight changes in permission resolution * We now use a set key (derived from name used for setting the attribute on Permissions or provided in permission definition from plugins) * We do a multipass resolution of combined plugin permissions (the former approach was limited to two passes) We also do logging on the permissions added through plugins. Also did some code deduplication while at it. --- src/octoprint/access/groups.py | 4 +- src/octoprint/access/permissions.py | 192 ++++++++++++------ src/octoprint/access/users.py | 6 +- .../plugins/announcements/__init__.py | 30 ++- .../announcements/static/js/announcements.js | 12 +- .../plugins/pluginmanager/__init__.py | 34 ++-- .../pluginmanager/static/js/pluginmanager.js | 16 +- .../plugins/softwareupdate/__init__.py | 33 +-- .../static/js/softwareupdate.js | 8 +- src/octoprint/server/__init__.py | 149 ++++++++------ src/octoprint/server/api/access.py | 3 +- .../static/js/app/viewmodels/access.js | 25 ++- .../settings/accesscontrol/groups.jinja2 | 2 +- .../settings/accesscontrol/users.jinja2 | 2 +- 14 files changed, 317 insertions(+), 199 deletions(-) diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index 8245b0ad9..c7ba164c3 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -116,7 +116,7 @@ class GroupManager(object): [Permissions.find(permission) for permission in permissions]) def _from_permissions(self, *permissions): - return [permission.get_name() for permission in permissions] + return [permission.key for permission in permissions] def _to_group(self, group): if isinstance(group, Group): @@ -400,7 +400,7 @@ class Group(object): return dict( name=self.get_name(), description=self.get_description(), - permissions=map(lambda p: p.get_name(), self._permissions), + permissions=map(lambda p: p.key, self._permissions), needs=OctoPrintPermission.convert_needs_to_dict(self.needs), defaultOn=self.get_default(), removable=self._removable, diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index ed4bc6c81..5497a4d25 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -9,7 +9,9 @@ __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms from flask import g, abort from flask_babel import gettext from flask_principal import Permission, PermissionDenied, RoleNeed, Need + from functools import wraps +from collections import OrderedDict from past.builtins import basestring @@ -31,15 +33,26 @@ class OctoPrintPermission(Permission): self._name = name self._description = description - Permission.__init__(self, *map(lambda x: RoleNeed(x) if not isinstance(x, Need) else x, needs)) + self._key = None + + Permission.__init__(self, *[RoleNeed(x) if not isinstance(x, Need) else x for x in needs]) def as_dict(self): return dict( + key=self.key, name=self.get_name(), description=self.get_description(), needs=self.convert_needs_to_dict(self.needs) ) + @property + def key(self): + return self._key + + @key.setter + def key(self, value): + self._key = value + def get_name(self): return self._name @@ -71,7 +84,7 @@ class OctoPrintPermission(Permission): if need.method == 'role': needs.append("RoleNeed('{0}')".format(need.value)) - return '{0}("{1}", "{2}", {3})'.format(self.__class__.__name__, self.get_name(), self.get_description(), ', '.join(needs)) + return '{}("{}", "{}", "{}", {})'.format(self.__class__.__name__, self.key, self.get_name(), self.get_description(), ', '.join(needs)) class CombinedOctoPrintPermission(OctoPrintPermission): @@ -160,98 +173,60 @@ class PluginPermissionDecorator(Permission): class PermissionsMetaClass(type): - plugin_permissions = dict() + permissions = OrderedDict() + + def __new__(mcs, name, bases, args): + cls = type.__new__(mcs, name, bases, args) + + for key, value in args.items(): + if isinstance(value, OctoPrintPermission): + value.key = key + mcs.permissions[key] = value + delattr(cls, key) + + return cls def __setattr__(cls, key, value): - if key.startswith("PLUGIN_"): - if key in cls.plugin_permissions: + if isinstance(value, OctoPrintPermission): + if key in cls.permissions: raise PermissionAlreadyExists(key) - cls.plugin_permissions[key] = value + value.key = key + cls.permissions[key] = value def __getattr__(cls, key): - if key.startswith("PLUGIN_"): - permission = cls.plugin_permissions.get(key, None) - if permission is None: - return PluginPermissionDecorator(key) - return permission + permission = cls.permissions.get(key) - return None + if key.startswith("PLUGIN_") and permission is None: + return PluginPermissionDecorator(key) + return permission -class Permissions(object): - __metaclass__ = PermissionsMetaClass - - # Special permission - ADMIN = OctoPrintPermission("Admin", gettext("Admin is allowed to do everything"), RoleNeed("admin")) - - STATUS = OctoPrintPermission("Status", - gettext("Allows to gather Statusinformations like, Connection, Printstate, Temperaturegraph"), - RoleNeed("status")) - CONNECTION = OctoPrintPermission("Connection", gettext("Allows to connect and disconnect to a printer"), RoleNeed("connection")) - WEBCAM = OctoPrintPermission("Webcam", gettext("Allows to watch the webcam stream"), RoleNeed("webcam")) - SYSTEM = OctoPrintPermission("System", gettext("Allows to run system commands, e.g. shutdown, reboot, restart octoprint"), - RoleNeed("system")) - UPLOAD = OctoPrintPermission("Upload", gettext("Allows users to upload new gcode files"), RoleNeed("upload")) - DOWNLOAD = OctoPrintPermission("Download", - gettext("Allows users to download gcode files, the gCodeViewer is affected by this too."), - RoleNeed("download")) - DELETE = OctoPrintPermission("Delete", gettext("Allows users to delete files in their folder"), RoleNeed("delete_file")) - SELECT = OctoPrintPermission("Select", gettext("Allows to select a file"), RoleNeed("select")) - PRINT = OctoPrintPermission("Print", gettext("Allows to start a print job, inherits the select permission"), - RoleNeed("print")) - TERMINAL = OctoPrintPermission("Terminal", gettext("Allows to watch the Terminaltab, without the ability to send any commands"), - RoleNeed("terminal")) - CONTROL = OctoPrintPermission("Control", - gettext("Allows to manually control the printer by using the controltab or sending gcodes through the terminal, this implies the terminal permission"), - RoleNeed("control")) - SLICE = OctoPrintPermission("Slice", gettext("Allows to slice stl files into gcode files"), RoleNeed("slice")) - TIMELAPSE = OctoPrintPermission("Timelapse", gettext("Allows to download timelapse videos"), RoleNeed("timelapse")) - TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin", - gettext("Allows to change the timelapse settings, remove timelapses, implies timelapse"), - RoleNeed("timelapse_admin")) - SETTINGS = OctoPrintPermission("Settings", gettext("Allows to open and change Settings"), RoleNeed("settings")) - LOGS = OctoPrintPermission("Logs", gettext("Allows to download and remove logs"), RoleNeed("logs")) - - CONTROL_ACCESS = CombinedOctoPrintPermission.from_permissions("Control Access", CONTROL, WEBCAM) - CONNECTION_ACCESS = CombinedOctoPrintPermission.from_permissions("Connection Access", CONNECTION, STATUS) - FILES_ACCESS = CombinedOctoPrintPermission.from_permissions("Files Access", UPLOAD, DOWNLOAD, DELETE, SELECT, PRINT, SLICE) - PRINTERPROFILES_ACCESS = CombinedOctoPrintPermission.from_permissions("Printerprofiles Access", CONNECTION, SETTINGS) - TIMELAPSE_ACCESS = CombinedOctoPrintPermission.from_permissions("Timelapse Access", TIMELAPSE, TIMELAPSE_ADMIN) - - @classmethod def all(cls): - return [getattr(Permissions, name) for name in Permissions.__dict__ - if not name.startswith("__") and isinstance(getattr(Permissions, name), OctoPrintPermission)] \ - + cls.__metaclass__.plugin_permissions.values() + return cls.permissions.values() - @classmethod def filter(cls, cb): return filter(cb, cls.all()) - @classmethod def regular(cls): return cls.filter(lambda x: not isinstance(x, CombinedOctoPrintPermission)) - @classmethod def combined(cls): return cls.filter(lambda x: isinstance(x, CombinedOctoPrintPermission)) - @classmethod def find(cls, p, filter=None): - name = None + key = None if isinstance(p, OctoPrintPermission): - name = p.get_name() + key = p.key elif isinstance(p, dict): - name = p.get("name") + key = p.get("key") elif isinstance(p, basestring): - name = p + key = p - if name is None: + if key is None: return None - return cls.match(lambda p: p.get_name() == name, filter=filter) + return cls.match(lambda p: p.key == key, filter=filter) - @classmethod def match(cls, match, filter=None): if callable(filter): permissions = cls.filter(filter) @@ -265,6 +240,89 @@ class Permissions(object): return None +class Permissions(object): + __metaclass__ = PermissionsMetaClass + + # Special permission + ADMIN = OctoPrintPermission("Admin", + gettext("Admin is allowed to do everything"), + RoleNeed("admin")) + + STATUS = OctoPrintPermission("Status", + gettext("Allows to gather status information, e.g. job progress, " + "printer state, temperatures, ..."), + RoleNeed("status")) + CONNECTION = OctoPrintPermission("Connection", + gettext("Allows to connect to and disconnect and from a printer"), + RoleNeed("connection")) + WEBCAM = OctoPrintPermission("Webcam", + gettext("Allows to watch the webcam stream"), + RoleNeed("webcam")) + SYSTEM = OctoPrintPermission("System", + gettext("Allows to run system commands, e.g. restart OctoPrint, " + "shutdown or reboot the system"), + RoleNeed("system")) + UPLOAD = OctoPrintPermission("Upload", + gettext("Allows users to upload new files"), + RoleNeed("upload")) + DOWNLOAD = OctoPrintPermission("Download", + gettext("Allows users to download files. The GCODE viewer is " + "affected by this as well."), + RoleNeed("download")) + GCODE_VIEWER = OctoPrintPermission("GCODE viewer", + gettext("Allowed access to the GCODE viewer. Includes the \"Download\"" + "permission."), + RoleNeed("gcodeviewer"), RoleNeed("download")) + DELETE = OctoPrintPermission("Delete", + gettext("Allows users to delete files"), + RoleNeed("delete_file")) + SELECT = OctoPrintPermission("Select", + gettext("Allows to select a file for printing"), + RoleNeed("select")) + PRINT = OctoPrintPermission("Print", + gettext("Allows to start a print job. Includes the \"Select\" " + "permission"), + RoleNeed("print"), RoleNeed("select")) + TERMINAL = OctoPrintPermission("Terminal", + gettext("Allows to watch the terminal tab but not to send commands " + "to the printer from it"), + RoleNeed("terminal")) + CONTROL = OctoPrintPermission("Control", + gettext("Allows to control of the printer by using the control tab or " + "sending commands through the terminal. Includes the " + "\"Terminal\" permission"), + RoleNeed("control"), RoleNeed("terminal")) + SLICE = OctoPrintPermission("Slice", + gettext("Allows to slice files"), + RoleNeed("slice")) + TIMELAPSE = OctoPrintPermission("Timelapse", + gettext("Allows to download timelapse videos"), + RoleNeed("timelapse")) + TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin", + gettext("Allows to change the timelapse settings, remove timelapses," + "render unrendered timelapses. Includes the \"Timelapse\"" + "permission"), + RoleNeed("timelapse_admin"), RoleNeed("timelapse")) + SETTINGS = OctoPrintPermission("Settings", + gettext("Allows to manage settings"), + RoleNeed("settings")) + LOGS = OctoPrintPermission("Logs", + gettext("Allows to download and remove logs"), + RoleNeed("logs")) + + CONTROL_ACCESS = CombinedOctoPrintPermission.from_permissions("Control Access", + CONTROL, WEBCAM) + CONNECTION_ACCESS = CombinedOctoPrintPermission.from_permissions("Connection Access", + CONNECTION, STATUS) + FILES_ACCESS = CombinedOctoPrintPermission.from_permissions("Files Access", + UPLOAD, DOWNLOAD, DELETE, SELECT, PRINT, + SLICE) + PRINTERPROFILES_ACCESS = CombinedOctoPrintPermission.from_permissions("Printerprofiles Access", + CONNECTION, SETTINGS) + TIMELAPSE_ACCESS = CombinedOctoPrintPermission.from_permissions("Timelapse Access", + TIMELAPSE, TIMELAPSE_ADMIN) + + class PermissionAlreadyExists(Exception): def __init__(self, permission): Exception.__init__(self, "Permission %s already exists" % permission) diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 5e64afe30..bc9a1ccd5 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -405,6 +405,8 @@ class FilebasedUserManager(UserManager): user = self._users[username] + permissions = self._to_permissions(*permissions) + removed_permissions = list(set(user._permissions) - set(permissions)) added_permissions = list(set(permissions) - set(user._permissions)) @@ -603,7 +605,7 @@ class FilebasedUserManager(UserManager): return [group.get_name() for group in groups] def _from_permissions(self, *permissions): - return [permission.get_name() for permission in permissions] + return [permission.key for permission in permissions] # ~~ Deprecated methods follow @@ -718,7 +720,7 @@ class User(UserMixin): return { "name": self._username, "active": bool(self.is_active), - "permissions": map(lambda p: p.get_name(), self._permissions), + "permissions": map(lambda p: p.key, self._permissions), "groups": map(lambda g: g.get_name(), self._groups), "needs": OctoPrintPermission.convert_needs_to_dict(self.needs), "apikey": self._apikey, diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index a9e65ec16..a5865a30e 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -25,13 +25,6 @@ from octoprint.server.util.flask import restricted_access, with_revalidation_che from flask_babel import gettext -# Access permissions hook - -def additional_permissions(components): - return [ - dict(name="Announcement", description=gettext("Allows to see announcements"), roles=["announcment"]), - ] - class AnnouncementPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.BlueprintPlugin, @@ -47,6 +40,21 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, self._slugify = Slugify() self._slugify.safe_chars = "-_." + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="READ", + name="Read announcements", + description=gettext("Allows to read announcements"), + roles=["read"]), + dict(key="MANAGE", + name="Manage announcement subscriptions", + description=gettext("Allows to manage announcement subscriptions. Includes \"Read announcements\" " + "permission"), + roles=["manage", "read"]) + ] + # StartupPlugin def on_after_startup(self): @@ -139,7 +147,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, @octoprint.plugin.BlueprintPlugin.route("/channels", methods=["GET"]) @restricted_access - @Permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT.require(403) + @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) def get_channel_data(self): from octoprint.settings import valid_boolean_trues @@ -198,7 +206,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, @octoprint.plugin.BlueprintPlugin.route("/channels/", methods=["POST"]) @restricted_access - @Permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT.require(403) + @Permissions.PLUGIN_ANNOUNCEMENTS_READ.require(403) def channel_command(self, channel): from octoprint.server.util.flask import get_json_command_from_request from octoprint.server import NO_CONTENT @@ -215,6 +223,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, self._mark_read_until(channel, until) elif command == "toggle": + if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can(): + return flask.make_response("Insufficient rights", 403) self._toggle(channel) return NO_CONTENT @@ -500,5 +510,5 @@ __plugin_license__ = "AGPLv3" __plugin_implementation__ = AnnouncementPlugin() __plugin_hooks__ = { - 'octoprint.access.permissions': additional_permissions + 'octoprint.access.permissions': __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index d7f911716..912b06f52 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -56,7 +56,7 @@ $(function() { }; self.markRead = function(channel, until) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; var url = PLUGIN_BASEURL + "announcements/channels/" + channel; @@ -78,7 +78,7 @@ $(function() { }; self.toggleChannel = function(channel) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_MANAGE)) return; var url = PLUGIN_BASEURL + "announcements/channels/" + channel; @@ -103,7 +103,7 @@ $(function() { }; self.retrieveData = function(force) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; var url = PLUGIN_BASEURL + "announcements/channels"; if (force) { @@ -121,7 +121,7 @@ $(function() { }; self.fromResponse = function(data) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; var currentTab = $("li.active a", self.announcementDialogTabs).attr("href"); @@ -142,7 +142,7 @@ $(function() { }; self.showAnnouncementDialog = function(channel) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; // lazy load images that still need lazy-loading $("#plugin_announcements_dialog_content article img").lazyload(); @@ -179,7 +179,7 @@ $(function() { }; self.displayAnnouncements = function(channels) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ)) return; var displayLimit = self.settings.settings.plugins.announcements.display_limit(); var maxLength = self.settings.settings.plugins.announcements.summary_limit(); diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index c6ace5006..2cbd6090f 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -35,16 +35,6 @@ import threading _DATA_FORMAT_VERSION = "v2" -# Access permissions hook -def additional_permissions(components): - return [ - dict(name="Manage Plugins", description=gettext("Allows to use the plugin manager to manage plugins"), - roles=["manage_plugins"]), - dict(name="Upload Archive", description=gettext("Allows to install plugins through an archive"), - roles=["manage_plugins", "upload_archive"]) - - ] - class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, @@ -109,6 +99,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, # set a maximum body size of 50 MB for plugin archive uploads return [("POST", r"/upload_archive", 50 * 1024 * 1024)] + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="MANAGE", + name="Manage plugins", + description=gettext("Allows to manage installed plugins"), + roles=["manage"]), + dict(key="INSTALL", + name="Install new plugins", + description=gettext("Allows to install new plugins. Includes the \"Manage plugins\" permission"), + roles=["install", "manage"]) + ] + ##~~ StartupPlugin def on_after_startup(self): @@ -179,7 +183,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, @octoprint.plugin.BlueprintPlugin.route("/upload_archive", methods=["POST"]) @restricted_access - @Permissions.PLUGIN_PLUGINMANAGER_UPLOAD_ARCHIVE.require(403) + @Permissions.PLUGIN_PLUGINMANAGER_INSTALL.require(403) def upload_archive(self): import flask @@ -233,7 +237,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, } def on_api_get(self, request): - if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE_PLUGINS.can(): + if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): return make_response("Insufficient rights", 403) from octoprint.server import safe_mode @@ -287,7 +291,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, unless=lambda: refresh_repository or refresh_notices)(view)() def on_api_command(self, command, data): - if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE_PLUGINS.can(): + if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): return make_response("Insufficient rights", 403) if self._printer.is_printing() or self._printer.is_paused(): @@ -295,6 +299,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return make_response("Printer is currently printing or paused", 409) if command == "install": + if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can(): + return make_response("Insufficient rights", 403) url = data["url"] plugin_name = data["plugin"] if "plugin" in data else None return self.command_install(url=url, @@ -998,5 +1004,5 @@ def __plugin_load__(): __plugin_hooks__ = { "octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize, "octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types, - "octoprint.access.permissions": additional_permissions + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 8f02972bb..94ab29e5a 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -416,7 +416,7 @@ $(function() { }; self.requestData = function(options) { - if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) { return; } @@ -440,7 +440,7 @@ $(function() { }; self.togglePlugin = function(data) { - if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) { return; } @@ -500,7 +500,7 @@ $(function() { }; self.installFromRepository = function(data) { - if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) { return; } @@ -512,7 +512,7 @@ $(function() { }; self.installPlugin = function(url, name, reinstall, followDependencyLinks) { - if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) { return; } @@ -574,7 +574,7 @@ $(function() { }; self.uninstallPlugin = function(data) { - if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) { return; } @@ -605,7 +605,7 @@ $(function() { }; self.refreshRepository = function() { - if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_INSTALL)) { return; } self.requestData({refresh_repo: true}); @@ -1060,7 +1060,7 @@ $(function() { }; self.onUserLoggedIn = function(user) { - if (self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) { self.requestData({eval_notices: true}); } else { self.onUserLoggedOut(); @@ -1099,7 +1099,7 @@ $(function() { return; } - if (!self.loginState.hasPermission(self.access.permissions.SETTINGS)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE)) { return; } diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 71c9b3458..3c6fad577 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -29,16 +29,6 @@ from octoprint.access.permissions import Permissions from octoprint.util import dict_merge, to_unicode import octoprint.settings - -# Access permissions hook - -def additional_permissions(components): - return [ - dict(name="Check", description=gettext("Allows to check for software updates"), roles=["check"]), - dict(name="Perform", description=gettext("Allows to perform a software updates"), roles=["perform"]), - dict(asCombined=True, name="Access", permissions=["Check", "Perform"]) - ] - ##~~ Plugin class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, @@ -83,6 +73,25 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks) self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks) + # Additional permissions hook + + def get_additional_permissions(self): + return [ + dict(key="CHECK", + name="Check", + description=gettext("Allows to check for software updates"), + roles=["check"]), + dict(key="UPDATE", + name="Update", + description=gettext("Allows to perform a software updates"), + roles=["update"]), + dict(key="ACCESS", + combined=True, + name="Access", + permissions=["PLUGIN_SOFTWAREUPDATE_CHECK", + "PLUGIN_SOFTWAREUPDATE_UPDATE"]) + ] + def on_startup(self, host, port): console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024) console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s")) @@ -526,7 +535,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, @octoprint.plugin.BlueprintPlugin.route("/update", methods=["POST"]) @restricted_access - @Permissions.PLUGIN_SOFTWAREUPDATE_PERFORM.require(403) + @Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403) def perform_update(self): if self._printer.is_printing() or self._printer.is_paused(): # do not update while a print job is running @@ -1157,7 +1166,7 @@ def __plugin_load__(): global __plugin_hooks__ __plugin_hooks__ = { "octoprint.cli.commands": cli.commands, - "octoprint.access.permissions": additional_permissions + "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index f9acfec5e..743dce4ee 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -313,7 +313,7 @@ $(function() { } } - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_PERFORM) && !self.settings.settings.plugins.softwareupdate.notify_users()) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE) && !self.settings.settings.plugins.softwareupdate.notify_users()) return; if (data.status == "updateAvailable" || data.status == "updatePossible") { var text = "
" + gettext("There are updates available for the following components:"); @@ -332,7 +332,7 @@ $(function() { text += "

" + gettext("Those components marked with can be updated directly.") + "

"; - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_PERFORM)) { + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) { text += "

" + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "

"; } @@ -346,7 +346,7 @@ $(function() { var eventListeners = {}; var singleButtonNotify = false; - if (data.status == "updatePossible" && self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_PERFORM)) { + if (data.status == "updatePossible" && self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) { // if update is possible and user is admin, add action buttons for ignore and update options["confirm"] = { confirm: true, @@ -503,7 +503,7 @@ $(function() { }; self.performUpdate = function(force, items) { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_PERFORM)) return; + if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_UPDATE)) return; self.updateInProgress = true; diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 21d0c83c9..613f44aab 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -319,7 +319,7 @@ class Server(object): #~~ setup access control # get additional permissions from plugins - self._setup_plugin_permissions(components) + self._setup_plugin_permissions() # create group manager instance group_manager_factories = pluginManager.get_hooks("octoprint.access.groups.factory") @@ -1482,79 +1482,110 @@ class Server(object): self._intermediary_server.server_close() self._logger.info("Intermediary server shut down") - def _setup_plugin_permissions(self, components): + def _setup_plugin_permissions(self): global pluginManager - postponed_combined_permissions = [] - from octoprint.access.permissions import OctoPrintPermission, CombinedOctoPrintPermission, UnknownPermission - permissions_initializers = pluginManager.get_hooks("octoprint.access.permissions") - for name, permissions_initializer in permissions_initializers.items(): + + def permission_key(plugin, definition): + return "PLUGIN_{}_{}".format(plugin.upper(), definition["key"].upper()) + + def permission_name(plugin, definition): + return "Plugin \"{}\": {}".format(plugin, definition["name"]) + + def permission_role(plugin, role): + return "plugin_{}_{}".format(plugin, role) + + def process_regular_permission(plugin, definition): + roles = definition["roles"] + description = definition.get("description", "") + + key = permission_key(plugin, definition) + setattr(octoprint.access.permissions.Permissions, + key, + OctoPrintPermission(permission_name(plugin, definition), + description, + *[permission_role(plugin, role) for role in roles])) + + self._logger.debug("Added new permission from plugin {}: {}".format(plugin, key)) + return True + + def process_combined_permission(plugin, definition): + resolved = [] + for key in definition["permissions"]: + permission = octoprint.access.permissions.Permissions.find(key) + + if permission is None: + # if there is still no permission found, postpone this - maybe it is a permission from + # another plugin that hasn't been loaded yet + return False + + resolved.append(permission) + + key = permission_key(plugin, definition) + setattr(octoprint.access.permissions.Permissions, + key, + CombinedOctoPrintPermission.from_permissions(permission_name(plugin, definition), + description=definition.get("description", ""), + *resolved)) + + self._logger.debug("Added new permission from plugin {}: {}".format(plugin, key)) + return True + + postponed = [] + + hooks = pluginManager.get_hooks("octoprint.access.permissions") + for name, factory in hooks.items(): try: - permission_list = permissions_initializer(components) + if isinstance(factory, (tuple, list)): + additional_permissions = list(factory) + elif callable(factory): + additional_permissions = factory() + else: + raise ValueError("factory must be either a callable, tuple or list") - regular_permission = filter( - lambda p: isinstance(p, dict) and ("asCombined" not in p or not p["asCombined"]), permission_list) - combined_permission = filter( - lambda p: isinstance(p, dict) and "asCombined" in p and p["asCombined"], permission_list) + if not isinstance(additional_permissions, (tuple, list)): + raise ValueError("factory result must be either a tuple or a list of permission definition dicts") - for p in regular_permission: - if "name" not in p or "description" not in p or "roles" not in p: + for p in additional_permissions: + if not isinstance(p, dict): continue - permission = OctoPrintPermission("Plugin {} {}".format(name, p["name"]), - gettext(p["description"]), - *["plugin_{}_{}".format(name, need) for need in p["roles"]]) - key = permission.get_name().replace(" ", "_").upper() - setattr(octoprint.access.permissions.Permissions, key, permission) - - for p in combined_permission: - if "name" not in p or "permissions" not in p: + if not "key" in p or not "name" in p: continue - permissions = [] - for permission_name in p["permissions"]: - perm = octoprint.access.permissions.Permissions.find(permission_name) - # If we can't find a permission by the name, try to add the plugins prefix and look again - if perm is None: - perm = octoprint.access.permissions.Permissions.find("Plugin {} {}".format(name, permission_name)) - - - if perm is None: - # if there is still no permission found, postpone this - maybe it is a permission from - # another plugin that hasn't been loaded yet - postponed_combined_permissions.append(p) - break - - permissions.append(perm) - - else: - # found all permissions we depend on, can continue - permission = CombinedOctoPrintPermission.from_permissions("Plugin {} {}".format(name, p["name"]), *permissions) - key = permission.get_name().replace(" ", "_").upper() - setattr(octoprint.access.permissions.Permissions, key, permission) - + if not p.get("combined", False) and "roles" in p: + process_regular_permission(name, p) + elif p.get("combined", False) and "permissions" in p: + if not process_combined_permission(name, p): + postponed.append((name, p)) except: self._logger.exception("Error while creating permission instance/s from {}".format(name)) - for p in postponed_combined_permissions: - try: - permissions = [] - for permission_name in p["permissions"]: - perm = octoprint.access.permissions.Permissions.find(permission_name) - # If we can't find a permission by the name, try to add the plugins prefix and look again - if perm is None: - perm = octoprint.access.permissions.Permissions.find("Plugin {} {}".format(name, permission_name)) + # final resolution passes + pass_number = 1 + still_postponed = [] + while len(postponed): + start_length = len(postponed) + self._logger.debug("Combined permission resolution pass #{}, " + "{} unresolved combined permissions...".format(pass_number, start_length)) - if perm is None: - # still no permission - we can't process this - raise UnknownPermission(permission_name) + for plugin, definition in postponed: + if not process_combined_permission(plugin, definition): + still_postponed.append((plugin, definition)) - permission = CombinedOctoPrintPermission("Plugin {} {}".format(name, p["name"]), *permissions) - key = permission.get_name().replace(" ", "_").upper() - setattr(octoprint.access.permissions.Permissions, key, permission) - except: - self._logger.exception("Error while creating permission instance/s from {}".format(name)) + self._logger.debug("... pass #{} done, {} combined " + "permissions left to resolve".format(pass_number, len(still_postponed))) + + if len(still_postponed) == start_length: + # no change, looks like some stuff is unresolvable - let's bail + for plugin, definition in still_postponed: + self._logger.warn("Unable to resolve combined permission from {}: {!r}".format(plugin, definition)) + break + + postponed = still_postponed + still_postponed = [] + pass_number += 1 class LifecycleManager(object): diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py index 31a925e94..72d83c3e9 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -21,8 +21,7 @@ from octoprint.access.permissions import Permissions @api.route("/access/permissions", methods=["GET"]) def get_permissions(): - return jsonify(permissions=Permissions.regular(), - combined_permissions=Permissions.combined()) + return jsonify(permissions=[permission.as_dict() for permission in Permissions.all()]) #~~ group api diff --git a/src/octoprint/static/js/app/viewmodels/access.js b/src/octoprint/static/js/app/viewmodels/access.js index 8f9b04d2b..68dee9562 100644 --- a/src/octoprint/static/js/app/viewmodels/access.js +++ b/src/octoprint/static/js/app/viewmodels/access.js @@ -399,7 +399,7 @@ $(function() { showConfirmationDialog({ title: gettext("Are you sure?"), - message: gettext("You are about to delete a group."), + message: _.sprintf(gettext("You are about to delete the group \"%(name)s\"."), {name: group.name}), proceed: gettext("Delete"), onproceed: function() { OctoPrint.access.groups.delete(group.name).done(function(response) { @@ -430,22 +430,20 @@ $(function() { self.roleNeed = function(value) { return self.need("role", value); }; self.permissionList = ko.observableArray([]); - - var sanitizeName = function(name) { return name.replace(new RegExp(" ", 'g'), "_"); }; + self.lookup = {}; var registeredPermissions = []; - var registerPermission = function(name, permission) { - var sanitized = sanitizeName(name).toUpperCase(); - Object.defineProperty(self, sanitized, { + var registerPermission = function(key, permission) { + Object.defineProperty(self, key, { value: permission, enumerable: true, configurable: true }); - registeredPermissions.push(sanitized); + registeredPermissions.push(key); }; var clearAllRegisteredPermissions = function() { - _.each(registeredPermissions, function(name) { - delete self[name]; + _.each(registeredPermissions, function(key) { + delete self[key]; }); registeredPermissions = []; }; @@ -454,6 +452,7 @@ $(function() { clearAllRegisteredPermissions(); var permissionList = []; + var lookup = {}; _.each(PERMISSIONS, function(permission) { var needs = []; _.each(permission.needs, function(value, key) { @@ -461,15 +460,17 @@ $(function() { }); if (needs.length > 0) { - registerPermission(permission.name, needs); + registerPermission(permission.key, needs); } if (!permission.combined) { permissionList.push(permission); } + lookup[permission.key] = permission; }); self.permissionList(permissionList); + self.lookup = lookup; }; return self; @@ -488,7 +489,9 @@ $(function() { if (data.permissions === undefined) return ""; - return data.permissions.join(", "); + return _.map(data.permissions, function(p) { + return access.permissions.lookup[p] ? access.permissions.lookup[p].name : p + }).join(", "); }; //~~ API Calls diff --git a/src/octoprint/templates/snippets/settings/accesscontrol/groups.jinja2 b/src/octoprint/templates/snippets/settings/accesscontrol/groups.jinja2 index 92fcb1bde..98c0fa0ed 100644 --- a/src/octoprint/templates/snippets/settings/accesscontrol/groups.jinja2 +++ b/src/octoprint/templates/snippets/settings/accesscontrol/groups.jinja2 @@ -37,7 +37,7 @@