diff --git a/docs/docs/settings/error_codes.md b/docs/docs/settings/error_codes.md index 68b0c71a62..72a63f443e 100644 --- a/docs/docs/settings/error_codes.md +++ b/docs/docs/settings/error_codes.md @@ -288,6 +288,15 @@ The `middleware` or `authentication_backends` list provided in the configuration The class has been removed automatically. To remove this warning, remove it from the list in your configuration file. +#### INVE-W22 +**Plugin integration is disabled - Backend** + +An active plugin makes use of a plugin integration (mixin) which is disabled in the global settings. The affected functionality of the plugin (e.g. custom URLs, scheduled tasks, event handling or user interface elements) will not work until the integration is enabled. + +The message lists each affected plugin, together with the plugin settings which need to be enabled. Enable the listed settings in the [plugin settings](./global.md#plugin-settings) (a server restart may be required), or deactivate the plugin if it is not needed. + +If the check itself fails, the message "Unable to check plugin integrations" is shown instead. Check the server log for details. + ### INVE-I (InvenTree Information) Information — These are not errors but information messages. They might point out potential issues or just provide information. diff --git a/src/backend/InvenTree/InvenTree/helpers.py b/src/backend/InvenTree/InvenTree/helpers.py index 7000fd4d5d..d51da8809d 100644 --- a/src/backend/InvenTree/InvenTree/helpers.py +++ b/src/backend/InvenTree/InvenTree/helpers.py @@ -1232,6 +1232,74 @@ def plugins_info(*args, **kwargs): ] +def plugins_disabled_mixins() -> list[dict]: + """Return information about active plugins which rely on a globally disabled integration. + + Some plugin mixins only have an effect if the matching global setting is enabled + (e.g. a plugin which uses the UrlsMixin requires the 'ENABLE_PLUGINS_URL' setting). + If the setting is disabled, the plugin silently "does nothing" for that mixin - + which is hard to diagnose for an administrator. + + Returns: + list: One entry for each (plugin, mixin) combination which is not operational + """ + from common.settings import get_global_setting + from plugin import PluginMixinEnum, registry + + # Check if plugins are even enabled + if not settings.PLUGINS_ENABLED: + return [] + + # Map each "gated" mixin to the global setting which enables it + mixin_settings = { + PluginMixinEnum.APP: 'ENABLE_PLUGINS_APP', + PluginMixinEnum.EVENTS: 'ENABLE_PLUGINS_EVENTS', + PluginMixinEnum.MAIL: 'ENABLE_PLUGINS_MAILS', + PluginMixinEnum.NAVIGATION: 'ENABLE_PLUGINS_NAVIGATION', + PluginMixinEnum.SCHEDULE: 'ENABLE_PLUGINS_SCHEDULE', + PluginMixinEnum.URLS: 'ENABLE_PLUGINS_URL', + PluginMixinEnum.USER_INTERFACE: 'ENABLE_PLUGINS_INTERFACE', + } + + # Use the "effective" setting value (which respects any overrides), + # to match the value which is used when the mixins are activated + enabled_settings = { + setting + for setting in mixin_settings.values() + if str2bool(get_global_setting(setting, False, create=False)) + } + + disabled_mixins = { + mixin: setting + for mixin, setting in mixin_settings.items() + if setting not in enabled_settings + } + + if not disabled_mixins: + return [] + + results = [] + + # Only active plugins which actually make use of the mixin are reported + for plg in registry.with_mixin(PluginMixinEnum.BASE, active=True): + for mixin, setting in disabled_mixins.items(): + try: + if not plg.mixin_enabled(mixin): + continue + except Exception: + continue + + results.append({ + 'plugin': plg.slug, + # The plugin name may be a lazily translated string + 'name': str(plg.name), + 'mixin': str(mixin.value), + 'setting': setting, + }) + + return results + + def sanitize_token(token_value: str, front=8, back=12) -> str: """Sanitize a token by replacing the middle characters with asterisks. diff --git a/src/backend/InvenTree/common/admin_messages.py b/src/backend/InvenTree/common/admin_messages.py index abee996e3d..684dda8afe 100644 --- a/src/backend/InvenTree/common/admin_messages.py +++ b/src/backend/InvenTree/common/admin_messages.py @@ -98,12 +98,58 @@ def _pending_migrations() -> int: return 0 +def _disabled_plugin_integrations() -> Optional[list[str]]: + """Return the active plugins which rely on a disabled plugin integration. + + Returns: + A list of plugin names, each with the settings which need to be enabled, + or None if the check could not be performed + """ + from InvenTree.helpers import plugins_disabled_mixins + + try: + entries = plugins_disabled_mixins() + except Exception: + # This check must never prevent the other messages from being reported + logger.exception('Failed to check for disabled plugin integrations') + return None + + from common.models import InvenTreeSetting + + # Group the settings which need to be enabled by plugin + # (a plugin may be affected by multiple disabled integrations) + required: dict[str, set[str]] = {} + + for entry in entries: + plugin = str(entry['name'] or entry['plugin']) + setting = str( + InvenTreeSetting.get_setting_name(entry['setting']) or entry['setting'] + ) + required.setdefault(plugin, set()).add(setting) + + # e.g. "Auto Create Builds (Enable event integration)" + return [ + f'{plugin} ({", ".join(sorted(names))})' + for plugin, names in sorted(required.items()) + ] + + def get_core_admin_messages() -> list[AdminMessage]: """Return the set of core InvenTree system messages.""" # Imported here to avoid circular imports at app load from InvenTree.helpers_email import is_email_configured from InvenTree.status import is_worker_running + disabled_integrations = _disabled_plugin_integrations() + + if disabled_integrations is None: + # The check failed: do not report it as successful + plugin_integration_message = _('Unable to check plugin integrations') + else: + plugin_integration_message = _( + 'Active plugins require a plugin integration which is disabled. Enable the listed plugin settings: {plugins}' + ).format(plugins=', '.join(disabled_integrations)) + return [ _check( 'debug', @@ -154,6 +200,13 @@ def get_core_admin_messages() -> list[AdminMessage]: bool(settings.BASIC_AUTH_ENABLED), code='INVE-W18', ), + _check( + 'plugin_integration', + _('Plugin Integration'), + plugin_integration_message, + disabled_integrations is None or len(disabled_integrations) > 0, + code='INVE-W22', + ), ] diff --git a/src/backend/InvenTree/common/test_api.py b/src/backend/InvenTree/common/test_api.py index 2eae604ded..03af2604b4 100644 --- a/src/backend/InvenTree/common/test_api.py +++ b/src/backend/InvenTree/common/test_api.py @@ -3607,6 +3607,7 @@ class AdminMessageAPITests(InvenTreeAPITestCase): 'migrations', 'cors', 'basic_auth', + 'plugin_integration', } @property @@ -3686,6 +3687,123 @@ class AdminMessageAPITests(InvenTreeAPITestCase): self.assertEqual(messages['migrations']['classifier'], 'success') self.assertEqual(messages['restart']['classifier'], 'success') + def test_plugin_integration(self): + """Active plugins which rely on a disabled plugin integration are reported.""" + from plugin import registry + + self.ensurePluginsLoaded() + + def message() -> dict: + return self._messages()['plugin_integration'] + + # The 'sample' plugin makes use of the (gated) URL integration + registry.set_plugin_state('sample', True) + + for key in [ + 'ENABLE_PLUGINS_APP', + 'ENABLE_PLUGINS_NAVIGATION', + 'ENABLE_PLUGINS_URL', + ]: + set_global_setting(key, True, None) + + self.assertNotIn('SampleIntegrationPlugin', message()['message']) + + # Disable the URL integration: the plugin is reported + set_global_setting('ENABLE_PLUGINS_URL', False, None) + + msg = message() + self.assertEqual(msg['classifier'], 'warning') + self.assertEqual(msg['code'], 'INVE-W22') + self.assertIn('SampleIntegrationPlugin', msg['message']) + + # The setting which needs to be enabled is named + self.assertIn( + 'SampleIntegrationPlugin (Enable URL integration)', msg['message'] + ) + + # A setting override (environment / config file) takes priority over the stored value + with override_settings(GLOBAL_SETTINGS_OVERRIDES={'ENABLE_PLUGINS_URL': True}): + self.assertNotIn('SampleIntegrationPlugin', message()['message']) + + set_global_setting('ENABLE_PLUGINS_URL', True, None) + + with override_settings(GLOBAL_SETTINGS_OVERRIDES={'ENABLE_PLUGINS_URL': False}): + self.assertIn('SampleIntegrationPlugin', message()['message']) + + # An inactive plugin is not reported + set_global_setting('ENABLE_PLUGINS_URL', False, None) + registry.set_plugin_state('sample', False) + + self.assertNotIn('SampleIntegrationPlugin', message()['message']) + + # A plugin with a (lazily) translated name is reported correctly + registry.set_plugin_state('autocreatebuilds', True) + set_global_setting('ENABLE_PLUGINS_EVENTS', False, None) + + self.assertIn( + 'Auto Create Builds (Enable event integration)', message()['message'] + ) + + registry.set_plugin_state('autocreatebuilds', False) + + def test_plugin_integration_edge_cases(self): + """Edge cases of the plugin integration check.""" + from unittest import mock + + from InvenTree.helpers import plugins_disabled_mixins + from plugin import PluginMixinEnum, registry + from plugin._internal.base import MixinBase + + self.ensurePluginsLoaded() + registry.set_plugin_state('sample', True) + set_global_setting('ENABLE_PLUGINS_URL', False, None) + + self.assertGreater(len(plugins_disabled_mixins()), 0) + + # Nothing is reported if plugins are disabled entirely + with override_settings(PLUGINS_ENABLED=False): + self.assertEqual(plugins_disabled_mixins(), []) + + # A plugin which fails to report its mixin state is skipped + def broken_mixin_enabled(key): + if key == PluginMixinEnum.BASE: + return True + raise ValueError('broken plugin') + + with mock.patch.object( + MixinBase, 'mixin_enabled', side_effect=broken_mixin_enabled + ): + self.assertEqual(plugins_disabled_mixins(), []) + + # Nothing is reported if all of the integrations are enabled + for key in [ + 'ENABLE_PLUGINS_APP', + 'ENABLE_PLUGINS_EVENTS', + 'ENABLE_PLUGINS_MAILS', + 'ENABLE_PLUGINS_NAVIGATION', + 'ENABLE_PLUGINS_SCHEDULE', + 'ENABLE_PLUGINS_URL', + 'ENABLE_PLUGINS_INTERFACE', + ]: + set_global_setting(key, True, None) + + self.assertEqual(plugins_disabled_mixins(), []) + + registry.set_plugin_state('sample', False) + + # A failed check is not reported as successful, and other messages are still provided + with mock.patch( + 'InvenTree.helpers.plugins_disabled_mixins', + side_effect=RuntimeError('check failed'), + ): + messages = self._messages() + + msg = messages['plugin_integration'] + self.assertEqual(msg['classifier'], 'warning') + self.assertEqual(msg['code'], 'INVE-W22') + self.assertEqual(msg['message'], 'Unable to check plugin integrations') + self.assertTrue(self.CORE_KEYS.issubset(messages.keys())) + def test_plugin_messages(self): """Plugin-provided messages are merged in and sorted by severity.""" from unittest import mock