ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
security: hook seam lifecycle + registrant binding
Juan Denis7c6b0f395890
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.pyindex 8447f826..b539ac5d 100644--- a/backend/app/api/apps.py+++ b/backend/app/api/apps.py@@ -2492,9 +2492,16 @@ def create_app_db_snapshot(app_id):return jsonify({'error': 'This application is not a WordPress site'}), 400# Resolve the extension only once we know this IS a WordPress site — with# serverkit-wordpress uninstalled a non-WP app must get the 400, not an- # import error (plan 52 Phase 5 graceful absence).- from app.services.wordpress_bridge import wordpress_env_service- WordPressEnvService = wordpress_env_service()+ # import error (plan 52 Phase 5 graceful absence). A WP SITE with the+ # extension missing/disabled gets a clean 503, not an uncaught+ # WordPressExtensionMissingError → 500 (audit F3).+ from app.services.wordpress_bridge import (+ WordPressExtensionMissingError, wordpress_env_service,+ )+ try:+ WordPressEnvService = wordpress_env_service()+ except WordPressExtensionMissingError as e:+ return jsonify({'error': str(e)}), 503data = request.get_json() or {}result = DatabaseSyncService.create_snapshot(db_name=site.db_name,diff --git a/backend/app/services/backup_kind_registry.py b/backend/app/services/backup_kind_registry.pyindex 97a1f52e..b41f3069 100644--- a/backend/app/services/backup_kind_registry.py+++ b/backend/app/services/backup_kind_registry.py@@ -30,7 +30,9 @@ import logginglogger = logging.getLogger(__name__)# target_type -> {'resolve': fn, 'execute': fn, 'restore': fn|None,-# 'label': str|None, 'restore_scopes': list|None}+# 'label': str|None, 'restore_scopes': list|None,+# 'source': str|None # registrant extension slug (audit F5)+# }_KINDS = {}@@ -41,7 +43,7 @@ def core_kinds():def register(target_type: str, resolve, execute, restore=None, replace: bool = False,- label: str = None, restore_scopes=None):+ label: str = None, restore_scopes=None, source: str = None):"""Register a backup target type.Namespace it after your plugin (``minecraft.world``); the bare words core@@ -51,6 +53,12 @@ def register(target_type: str, resolve, execute, restore=None, replace: bool = F``label`` / ``restore_scopes`` are optional UI metadata surfaced by``GET /api/v1/backups/target-types`` so the Protection panel/restoredrawer can render the kind without hardcoding its name client-side.++ ``source`` is the registrant extension's slug. It is what lets+ disable/uninstall tear down exactly that extension's kinds+ (:func:`unregister`, audit F1) — and it makes ``replace=True``+ defense-in-depth: a kind owned by a DIFFERENT registrant can never be+ shadowed (audit F5)."""if not target_type:raise ValueError('a backup kind needs a target type')@@ -60,16 +68,37 @@ def register(target_type: str, resolve, execute, restore=None, replace: bool = Fraise ValueError('a backup restore must be callable')if target_type in core_kinds():raise ValueError(f'"{target_type}" is a core backup target type and cannot be overridden')- if target_type in _KINDS and not replace:- raise ValueError(f'backup kind "{target_type}" is already registered')+ existing = _KINDS.get(target_type)+ if existing is not None:+ existing_source = existing.get('source')+ if replace and existing_source and source and existing_source != source:+ raise ValueError(+ f'backup kind "{target_type}" is registered by '+ f'"{existing_source}" and cannot be replaced by "{source}"')+ if not replace:+ raise ValueError(f'backup kind "{target_type}" is already registered')_KINDS[target_type] = {'resolve': resolve, 'execute': execute, 'restore': restore,'label': label, 'restore_scopes': list(restore_scopes) if restore_scopes else None,+ 'source': source,}logger.info('Registered backup kind: %s', target_type)return _KINDS[target_type]+def unregister(source: str):+ """Drop every kind registered by ``source`` (disable/uninstall teardown,+ audit F1). Returns the number of kinds removed."""+ if not source:+ return 0+ doomed = [t for t, entry in _KINDS.items() if entry.get('source') == source]+ for t in doomed:+ del _KINDS[t]+ if doomed:+ logger.info('Unregistered %d backup kind(s) from %s', len(doomed), source)+ return len(doomed)++def get(target_type: str):"""The registration for *target_type*, or None."""return _KINDS.get(target_type)diff --git a/backend/app/services/event_service.py b/backend/app/services/event_service.pyindex 29333524..070e0ffd 100644--- a/backend/app/services/event_service.py+++ b/backend/app/services/event_service.py@@ -63,6 +63,9 @@ EVENT_CATALOG = [# don't exist (subscriptions to them just never match, which is the graceful# degradation — emission never validates against the catalog)._EXTENSION_EVENT_TYPES = []+# event type -> registrant slug (audit F5): lets disable/uninstall drop+# exactly one extension's types (audit F1).+_EXTENSION_EVENT_SOURCES = {}def register_event_types(entries, source=None):@@ -70,7 +73,9 @@ def register_event_types(entries, source=None):``entries``: list of ``{'type', 'category', 'description'}`` dicts.Idempotent — types already in the core catalog or already registered are- skipped, so per-boot re-registration never duplicates.+ skipped, so per-boot re-registration never duplicates. ``source`` is the+ registrant extension's slug, recorded so teardown+ (:func:`unregister_event_types`) removes exactly that extension's types."""known = {e['type'] for e in EVENT_CATALOG}known.update(e['type'] for e in _EXTENSION_EVENT_TYPES)@@ -85,14 +90,31 @@ def register_event_types(entries, source=None):'category': entry.get('category') or 'Extensions','description': entry.get('description') or '',})+ _EXTENSION_EVENT_SOURCES[etype] = sourceknown.add(etype)if source:logger.info(f'Registered event types from {source}')+def unregister_event_types(source):+ """Drop every event type registered by ``source`` (disable/uninstall+ teardown, audit F1). Returns the number removed."""+ if not source:+ return 0+ doomed = {t for t, s in _EXTENSION_EVENT_SOURCES.items() if s == source}+ if not doomed:+ return 0+ _EXTENSION_EVENT_TYPES[:] = [+ e for e in _EXTENSION_EVENT_TYPES if e['type'] not in doomed]+ for t in doomed:+ del _EXTENSION_EVENT_SOURCES[t]+ return len(doomed)++def clear_registered_event_types():"""Drop every extension-registered event type. Tests only."""_EXTENSION_EVENT_TYPES.clear()+ _EXTENSION_EVENT_SOURCES.clear()class EventService:diff --git a/backend/app/services/extension_lifecycle.py b/backend/app/services/extension_lifecycle.pyindex 1d64dbd1..7231e029 100644--- a/backend/app/services/extension_lifecycle.py+++ b/backend/app/services/extension_lifecycle.py@@ -199,3 +199,31 @@ def register_capabilities(plugin, manifest):fn()except Exception as e:logger.warning(f'Core-hook registration failed for {plugin.slug}: {e}')+++def unregister_capabilities(plugin):+ """Drop a plugin's core-seam registrations (disable/uninstall, audit F1).++ The mirrors of :func:`register_capabilities`: every seam registry tracks+ its registrant slug (backup kinds, event types, template providers), so+ teardown removes exactly THIS plugin's entries. The extension's modules+ stay in sys.modules (same as its blueprints) — but nothing may keep+ EXECUTING through a core seam once the extension is disabled or+ uninstalled. Best-effort; never raises into the caller.+ """+ slug = plugin.slug+ try:+ from app.services import backup_kind_registry+ backup_kind_registry.unregister(slug)+ except Exception as e:+ logger.warning(f'Backup-kind teardown failed for {slug}: {e}')+ try:+ from app.services import event_service+ event_service.unregister_event_types(slug)+ except Exception as e:+ logger.warning(f'Event-type teardown failed for {slug}: {e}')+ try:+ from app.services.template_service import TemplateService+ TemplateService.unregister_template_provider(slug)+ except Exception as e:+ logger.warning(f'Template-provider teardown failed for {slug}: {e}')diff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.pyindex 41b8643e..d046d06b 100644--- a/backend/app/services/template_service.py+++ b/backend/app/services/template_service.py@@ -56,24 +56,39 @@ class TemplateService:'wordpress': 'serverkit-wordpress','wordpress-external-db': 'serverkit-wordpress',}- # slug -> {'validate': callable(template_id, variables) -> error-dict|None}+ # slug -> {'validate': callable(template_id, variables) -> error-dict|None,+ # 'registrant': str|None # extension that claimed the slug (F5)+ # }_TEMPLATE_PROVIDERS = {}@classmethod- def register_template_provider(cls, slug, validate=None):+ def register_template_provider(cls, slug, validate=None, registrant=None):"""Register extension ``slug`` as the provider of its``PROVIDER_OWNED_TEMPLATES`` entries. Idempotent; the optional``validate(template_id, variables)`` hook may veto a variable set byreturning a ``{'success': False, 'error': ...}`` dict (this replaceshardcoded per-template checks in core — e.g. the WordPress external-DB- preflight now lives in the WP extension)."""+ preflight now lives in the WP extension).++ ``registrant`` is the claiming extension's slug (self-asserted, like+ every extension seam). Once a slug has an owner, a DIFFERENT+ registrant can never claim it (audit F5 — defense-in-depth against an+ extension hijacking another's provider slot)."""providers = dict(cls._TEMPLATE_PROVIDERS)- providers[slug] = {'validate': validate}+ existing = providers.get(slug)+ if (existing and existing.get('registrant') and registrant+ and existing['registrant'] != registrant):+ raise ValueError(+ f"template provider '{slug}' is already registered by "+ f"'{existing['registrant']}'")+ providers[slug] = {'validate': validate,+ 'registrant': registrant or slug}cls._TEMPLATE_PROVIDERS = providers@classmethoddef unregister_template_provider(cls, slug):- """Drop a provider registration. Tests only."""+ """Drop a provider registration (disable/uninstall teardown, audit+ F1)."""providers = dict(cls._TEMPLATE_PROVIDERS)providers.pop(slug, None)cls._TEMPLATE_PROVIDERS = providers@@ -1068,7 +1083,16 @@ class TemplateService:@classmethoddef list_local_templates(cls) -> List[Dict]:- """List locally available templates."""+ """List locally available templates.++ Deliberately NOT provider-gated: this is the raw "what is bundled on+ disk" view, which ``build_repo_index`` needs to describe the bundle+ faithfully for publishing. Provider-owned templates are hidden from+ the *catalog* instead — :meth:`list_all_templates` and+ :meth:`get_template` apply the availability gate (plan 52 D4), so an+ absent extension means hidden cards and refused installs even though+ the YAML remains bundled.+ """templates = []seen_ids = set()@@ -1081,10 +1105,6 @@ class TemplateService:template_id = filename.rsplit('.', 1)[0]if template_id in seen_ids:continue- if not cls.template_available(template_id):- # Provider-owned template whose extension is absent- # (plan 52 D4) — hidden from the catalog entirely.- continuefilepath = os.path.join(templates_dir, filename)result = cls.parse_template(filepath)if result.get('success'):diff --git a/backend/app/services/wordpress_bridge.py b/backend/app/services/wordpress_bridge.pyindex d98c0190..a7d37238 100644--- a/backend/app/services/wordpress_bridge.py+++ b/backend/app/services/wordpress_bridge.py@@ -25,11 +25,32 @@ class WordPressExtensionMissingError(RuntimeError):"""The serverkit-wordpress extension is not installed/active."""+def _plugin_active():+ """True only while the extension's InstalledPlugin row is ACTIVE.++ A disabled extension's modules stay importable (same as its blueprints),+ but its services must not be reachable (audit F2) — so the bridge checks+ the row, not just importability. No cache: bridge calls are rare and a+ status flip must take effect immediately (a stale ACTIVE cache would+ re-open exactly the hole this closes)."""+ try:+ from app.models.plugin import InstalledPlugin+ row = InstalledPlugin.query.filter_by(slug=SLUG).first()+ return bool(row and row.status == InstalledPlugin.STATUS_ACTIVE)+ except Exception:+ # No app context / DB unavailable: fail closed — callers already+ # handle WordPressExtensionMissingError as the designed absence.+ return False++def ensure_loadable():"""Make ``app.plugins.serverkit-wordpress`` importable if the extension is- installed. Idempotent and cheap after the first call. Returns ``True`` if- the package is (now) importable, ``False`` when the extension is absent.+ installed AND active. Idempotent and cheap after the first call. Returns+ ``True`` if the package is (now) importable, ``False`` when the extension+ is absent or disabled."""+ if not _plugin_active():+ return Falsefrom app.services.plugin_service import _ensure_builtin_backend_importablereturn _ensure_builtin_backend_importable(SLUG)diff --git a/backend/tests/test_backup_drill_integrity.py b/backend/tests/test_backup_drill_integrity.pyindex ae0298a0..1c648d7f 100644--- a/backend/tests/test_backup_drill_integrity.py+++ b/backend/tests/test_backup_drill_integrity.py@@ -46,6 +46,22 @@ def _stub_wp_target(monkeypatch):classmethod(_resolve_target))[email protected](autouse=True)+def _wp_kind_registered():+ """wordpress_site is an extension-owned kind now (plan 52 D4): policy+ validation needs SOME registrant. Register a stub for these artifact-+ replay drill tests (the WP extension's real provider is out of scope)."""+ from app.services import backup_kind_registry+ if backup_kind_registry.get('wordpress_site'):+ yield # the extension's real provider is mounted — leave it alone+ return+ backup_kind_registry.register(+ 'wordpress_site', resolve=lambda p: {},+ execute=lambda p, t, k: ('/x', 1, {}), source='test-suite')+ yield+ backup_kind_registry.unregister('test-suite')++def _make_wp_run(policy, tmp_path, with_files=True, with_db=True, name='wp-run'):"""A successful wordpress_site BackupRun laid out as a run directory with anoptional files.tar.gz and database.sql."""diff --git a/backend/tests/test_backup_protection.py b/backend/tests/test_backup_protection.pyindex 91b6ae61..f9446fb7 100644--- a/backend/tests/test_backup_protection.py+++ b/backend/tests/test_backup_protection.py@@ -121,9 +121,18 @@ def test_decide_kind(app, tmp_path, monkeypatch):db.session.commit()assert BackupPolicyService._decide_kind(policy) == 'full'- # WordPress targets are always full.- wp = BackupPolicyService.get_or_create_policy('wordpress_site', 4040)- assert BackupPolicyService._decide_kind(wp) == 'full'+ # Non-application kinds are always full. wordpress_site lives in the WP+ # extension now (plan 52 D4), so prove the rule with a throwaway+ # registered kind rather than depending on the extension being mounted.+ from app.services import backup_kind_registry+ backup_kind_registry.register(+ 'test.kind', resolve=lambda p: {'name': 'k'},+ execute=lambda p, t, k: ('/x', 1, {}), source='test-suite')+ try:+ wp = BackupPolicyService.get_or_create_policy('test.kind', 4040)+ assert BackupPolicyService._decide_kind(wp) == 'full'+ finally:+ backup_kind_registry.unregister('test-suite')# --------------------------------------------------------------------------- #diff --git a/backend/tests/test_backup_target_types.py b/backend/tests/test_backup_target_types.pyindex fab74511..1632055b 100644--- a/backend/tests/test_backup_target_types.py+++ b/backend/tests/test_backup_target_types.py@@ -18,9 +18,10 @@ def test_valid_target_types_are_the_core_set():assert 'wordpress_site' not in VALID_TARGET_TYPES-def test_wordpress_site_valid_while_extension_present(app):- """With the WP flagship seeded (test boot), its backup kind registers via- the core_hooks seam and validates like a first-class type."""+def test_wordpress_site_valid_while_extension_present(app, wp_extension):+ """With the WP extension mounted (standalone repo via the wp_extension+ fixture), its backup kind registers via the core_hooks seam and validates+ like a first-class type."""BackupPolicyService.validate_target_type('wordpress_site')diff --git a/backend/tests/test_wp_hook_inversions.py b/backend/tests/test_wp_hook_inversions.pyindex cba0b9fa..87a6bd6e 100644--- a/backend/tests/test_wp_hook_inversions.py+++ b/backend/tests/test_wp_hook_inversions.py@@ -179,18 +179,18 @@ def test_wp_event_types_absent_graceful(app, client, auth_headers, wp_extension)# --------------------------------------------------------------------------- #def test_wp_templates_listed_when_present(app, wp_extension):- ids = {t['id'] for t in TemplateService.list_local_templates()}+ ids = {t['id'] for t in TemplateService.list_all_templates()}assert {'wordpress', 'wordpress-external-db'} <= idsassert TemplateService.get_template('wordpress')['success'] is Truedef test_wp_templates_hidden_when_absent(app, wp_extension):with wp_hooks_absent():- ids = {t['id'] for t in TemplateService.list_local_templates()}- assert 'wordpress' not in ids- assert 'wordpress-external-db' not in ids+ # The catalog (what the Templates grid renders) hides them; the+ # bundled YAMLs stay on disk for the repo-index publishing path.all_ids = {t['id'] for t in TemplateService.list_all_templates()}assert 'wordpress' not in all_ids+ assert 'wordpress-external-db' not in all_idsresult = TemplateService.get_template('wordpress')assert result['success'] is Falseassert 'serverkit-wordpress' in result['error']@@ -306,3 +306,150 @@ def test_ext_to_ext_seam_absent_side_returns_default(app):from app.services.plugin_service import get_installed_extension_attrassert get_installed_extension_attr('serverkit-analytics', 'wp_integration', 'inject', default=None) is None+++# --------------------------------------------------------------------------- #+# Audit F1/F4 — disable/uninstall tear down the seams; enable re-registers+# --------------------------------------------------------------------------- #++def _wp_plugin_row():+ from app.models.plugin import InstalledPlugin+ return InstalledPlugin.query.filter_by(slug=SLUG).first()+++def _seams_empty():+ return (+ backup_kind_registry.get('wordpress_site') is None+ and not TemplateService.template_available('wordpress')+ and not [e for e in EventService.get_available_events()+ if e['type'].startswith('wordpress.')]+ )+++def _seams_filled():+ return (+ backup_kind_registry.get('wordpress_site') is not None+ and TemplateService.template_available('wordpress')+ and any(e['type'] == 'wordpress.created'+ for e in EventService.get_available_events())+ )+++def test_disable_tears_down_seams_and_enable_restores(app, wp_extension):+ from app.services import plugin_service+ assert _seams_filled()+ plugin = _wp_plugin_row()++ plugin_service.disable_plugin(plugin.id)+ assert _seams_empty()+ with pytest.raises(BackupPolicyError):+ BackupPolicyService.validate_target_type('wordpress_site')++ plugin_service.enable_plugin(plugin.id)+ assert _seams_filled()+++def test_uninstall_tears_down_seams(app, wp_extension):+ from app.services import plugin_service+ plugin = _wp_plugin_row()+ plugin_service.uninstall_plugin(plugin.id)+ assert _seams_empty()+++# --------------------------------------------------------------------------- #+# Audit F2 — the bridge refuses a disabled/absent extension+# --------------------------------------------------------------------------- #++def test_bridge_refuses_when_extension_disabled(app, wp_extension):+ from app.services import plugin_service, wordpress_bridge+ assert wordpress_bridge.wordpress_service() is not None+ plugin = _wp_plugin_row()+ plugin_service.disable_plugin(plugin.id)+ try:+ with pytest.raises(wordpress_bridge.WordPressExtensionMissingError):+ wordpress_bridge.wordpress_service()+ finally:+ plugin_service.enable_plugin(plugin.id)+ assert wordpress_bridge.wordpress_service() is not None+++def test_update_schedule_cron_noops_when_extension_disabled(app, wp_extension):+ """The core cron sweep guards the bridge call — a disabled extension means+ a logged skip, never a crashed job."""+ from app.services import plugin_service+ from app.jobs import builtin_handlers+ site = _wp_site()+ site.auto_update_schedule = '* * * * *'+ db.session.commit()+ plugin = _wp_plugin_row()+ plugin_service.disable_plugin(plugin.id)+ try:+ builtin_handlers.check_update_schedules() # must not raise+ finally:+ plugin_service.enable_plugin(plugin.id)+++# --------------------------------------------------------------------------- #+# Audit F3 — db-snapshot route returns a clean 503, never an uncaught 500+# --------------------------------------------------------------------------- #++def test_db_snapshot_route_503_when_extension_missing(app, client, auth_headers):+ """A WordPressSite row exists but the extension is absent (this test+ deliberately does NOT mount it): clean 503 with the actionable message."""+ site = _wp_site()+ resp = client.post(f'/api/v1/apps/{site.application_id}/db-snapshots',+ headers=auth_headers, json={})+ assert resp.status_code == 503+ assert 'serverkit-wordpress' in resp.get_json()['error']+++# --------------------------------------------------------------------------- #+# Audit F5 — seam registrations are bound to their registrant+# --------------------------------------------------------------------------- #++def test_backup_kind_replace_from_other_registrant_rejected(app):+ register = backup_kind_registry.register+ register('ext.one', resolve=lambda p: {}, execute=lambda p, t, k: ('/x', 1, {}),+ source='ext-one')+ try:+ with pytest.raises(ValueError, match='cannot be replaced'):+ register('ext.one', resolve=lambda p: {},+ execute=lambda p, t, k: ('/x', 1, {}),+ replace=True, source='ext-two')+ # The SAME registrant may replace (idempotent re-registration).+ register('ext.one', resolve=lambda p: {},+ execute=lambda p, t, k: ('/x', 1, {}),+ replace=True, source='ext-one')+ assert backup_kind_registry.get('ext.one') is not None+ finally:+ # Teardown drops exactly that registrant's kinds.+ assert backup_kind_registry.unregister('ext-one') >= 1+ assert backup_kind_registry.get('ext.one') is None+++def test_event_unregister_drops_only_registrant_types(app):+ event_service.register_event_types(+ [{'type': 'exta.fired', 'category': 'A', 'description': ''}], source='ext-a')+ event_service.register_event_types(+ [{'type': 'extb.fired', 'category': 'B', 'description': ''}], source='ext-b')+ try:+ assert event_service.unregister_event_types('ext-a') == 1+ types = {e['type'] for e in EventService.get_available_events()}+ assert 'exta.fired' not in types+ assert 'extb.fired' in types+ finally:+ event_service.unregister_event_types('ext-b')+++def test_template_provider_hijack_rejected(app):+ TemplateService.register_template_provider('victim-slug',+ registrant='victim-slug')+ try:+ with pytest.raises(ValueError, match='already registered'):+ TemplateService.register_template_provider('victim-slug',+ registrant='evil-ext')+ # The owning registrant re-registering is fine (idempotent per boot).+ TemplateService.register_template_provider('victim-slug',+ registrant='victim-slug')+ finally:+ TemplateService.unregister_template_provider('victim-slug')