feat: Plugin-System Umbau — 6 Phasen komplett abgeschlossen
Check Cross-Plugin Imports / check (push) Has been cancelled

Phase 1: Contracts konsequent nutzen
- 12 neue contracts.py erstellt (alle 19 Plugins haben jetzt contracts)
- 4 bestehende contracts.py an zentrale ContractRegistry angepasst
- Alle 19 Plugins haben on_deactivate mit Contract-Unregister
- 0 echte problematische INTER-Plugin Imports

Phase 2: Hooks/Filters-System
- app/core/hooks.py (HookRegistry mit actions + filters)
- 15 Hook-Punkte in Core-Services (contact, auth, mail, calendar, user, dms)
- BasePlugin.on_deactivate meldet alle Hooks ab

Phase 3: Plugin-Isolation
- scripts/check_cross_plugin_imports.py (Linting-Regel)
- .github/workflows/check-cross-plugin-imports.yml (CI/CD)
- .pre-commit-cross-plugin.yaml (Pre-commit Hook)
- 155 Dateien geprueft, 0 Verstoesse

Phase 4: Plugin-Versioning
- app/plugins/semver.py (SemVer mit Parse, Compare, Pre-release)
- migration_runner.py erweitert: run_migration_down, rollback_to_version
- manifest.py: min_app_version Feld
- registry.py: App-Version-Compatibility-Check bei Installation
- GET /api/v1/plugins/updates Endpoint

Phase 5: Marketplace-Vorbereitung
- app/plugins/signature.py (Ed25519 Signatur-Validierung)
- app/plugins/quarantine.py (Plugin-Quarantine mit Validierung)
- app/models/plugin_allowlist.py + Migration 0046
- manifest.py: author, license, homepage, icon, screenshots, changelog, marketplace_tags, price
- registry.py: discover_external(), discover_all()
- POST /api/v1/plugins/install-marketplace (deaktiviert)

Phase 6: Manifest-Anpassung
- manifest.py: 12 neue Felder + SemVer/Hook-Name Validierung
- MANIFEST_SCHEMA_DOC aktualisiert
- Alle 19 Plugin-Manifeste aktualisiert
- Frontend PluginUiManifest Typ erweitert

Zusaetzliche Bug-Fixes:
- test_sample-Modul erstellt
- conftest.py Deadlock-Prevention
- SESSION_COOKIE_SECURE=true
- dump.rdb aus Git entfernt + .gitignore
- backup.py datetime.utcnow -> func.now()
- system_settings.py JSONB-Import nach oben
- tax.py Mapped[float] -> Mapped[Decimal]
- notification.py type_key-Laengen vereinheitlicht

Tests: 91 neue Tests, alle bestanden
This commit is contained in:
Agent Zero
2026-07-26 23:15:34 +02:00
parent 744d595cae
commit 98eb1d0d89
62 changed files with 3284 additions and 18 deletions
+194
View File
@@ -0,0 +1,194 @@
"""Tests for the WordPress-style hooks/filters system."""
from __future__ import annotations
import asyncio
import pytest
from app.core.hooks import (
HookRegistry,
get_hook_registry,
do_action,
apply_filters,
reset_hook_registry_for_testing,
)
@pytest.fixture(autouse=True)
def clean_registry():
"""Reset the hook registry before each test."""
reset_hook_registry_for_testing()
yield
reset_hook_registry_for_testing()
class TestHookRegistry:
def test_singleton_identity(self):
"""HookRegistry is a singleton."""
reg1 = get_hook_registry()
reg2 = get_hook_registry()
assert reg1 is reg2
def test_register_action(self):
"""Actions can be registered and listed."""
reg = get_hook_registry()
called = []
reg.register_action("test.action", lambda: called.append(True))
assert reg.has_action("test.action")
assert "test.action" in reg.list_actions()
def test_register_filter(self):
"""Filters can be registered and listed."""
reg = get_hook_registry()
reg.register_filter("test.filter", lambda v: v + "!")
assert reg.has_filter("test.filter")
assert "test.filter" in reg.list_filters()
@pytest.mark.asyncio
async def test_do_action_calls_callback(self):
"""do_action executes registered callbacks."""
reg = get_hook_registry()
called = []
reg.register_action("test.action", lambda: called.append("yes"))
await do_action("test.action")
assert called == ["yes"]
@pytest.mark.asyncio
async def test_do_action_with_args(self):
"""do_action passes arguments to callbacks."""
reg = get_hook_registry()
received = []
reg.register_action("test.action", lambda x, y: received.append((x, y)))
await do_action("test.action", 1, 2)
assert received == [(1, 2)]
@pytest.mark.asyncio
async def test_do_action_async_callback(self):
"""do_action supports async callbacks."""
reg = get_hook_registry()
called = []
async def async_cb():
called.append("async")
reg.register_action("test.action", async_cb)
await do_action("test.action")
assert called == ["async"]
@pytest.mark.asyncio
async def test_do_action_priority_order(self):
"""Actions execute in priority order (lower first)."""
reg = get_hook_registry()
order = []
reg.register_action("test.action", lambda: order.append("low"), priority=20)
reg.register_action("test.action", lambda: order.append("high"), priority=5)
reg.register_action("test.action", lambda: order.append("mid"), priority=10)
await do_action("test.action")
assert order == ["high", "mid", "low"]
@pytest.mark.asyncio
async def test_do_action_no_callbacks(self):
"""do_action with no registered callbacks does nothing."""
await do_action("nonexistent.action")
@pytest.mark.asyncio
async def test_do_action_swallows_exceptions(self):
"""do_action logs but does not raise on callback errors."""
reg = get_hook_registry()
called = []
reg.register_action("test.action", lambda: (_ for _ in ()).throw(ValueError("boom")))
reg.register_action("test.action", lambda: called.append("after_error"))
await do_action("test.action")
assert called == ["after_error"]
@pytest.mark.asyncio
async def test_apply_filters_modifies_value(self):
"""apply_filters passes value through callbacks."""
reg = get_hook_registry()
reg.register_filter("test.filter", lambda v: v.upper())
result = await apply_filters("test.filter", "hello")
assert result == "HELLO"
@pytest.mark.asyncio
async def test_apply_filters_chains_multiple(self):
"""apply_filters chains multiple callbacks in priority order."""
reg = get_hook_registry()
reg.register_filter("test.filter", lambda v: v + " B", priority=20)
reg.register_filter("test.filter", lambda v: v + " A", priority=10)
result = await apply_filters("test.filter", "start")
assert result == "start A B"
@pytest.mark.asyncio
async def test_apply_filters_no_callbacks(self):
"""apply_filters with no callbacks returns original value."""
result = await apply_filters("nonexistent.filter", "original")
assert result == "original"
@pytest.mark.asyncio
async def test_apply_filters_async_callback(self):
"""apply_filters supports async callbacks."""
reg = get_hook_registry()
async def async_upper(v: str) -> str:
return v.upper()
reg.register_filter("test.filter", async_upper)
result = await apply_filters("test.filter", "hello")
assert result == "HELLO"
def test_unregister_specific_callback(self):
"""unregister removes a specific callback."""
reg = get_hook_registry()
cb1 = lambda: None
cb2 = lambda: None
reg.register_action("test.action", cb1)
reg.register_action("test.action", cb2)
assert reg.has_action("test.action")
reg.unregister("test.action", cb1)
assert reg.has_action("test.action")
reg.unregister("test.action", cb2)
assert not reg.has_action("test.action")
def test_unregister_all_for_plugin(self):
"""unregister_all_for_plugin removes hooks owned by a plugin instance."""
reg = get_hook_registry()
class FakePlugin:
class manifest:
name = "fake_plugin"
def __init__(self):
self.manifest = type("m", (), {"name": "fake_plugin"})()
def my_action(self):
pass
def my_filter(self, v):
return v
plugin = FakePlugin()
reg.register_action("test.action", plugin.my_action)
reg.register_filter("test.filter", plugin.my_filter)
assert reg.has_action("test.action")
assert reg.has_filter("test.filter")
reg.unregister_all_for_plugin("fake_plugin")
assert not reg.has_action("test.action")
assert not reg.has_filter("test.filter")
@pytest.mark.asyncio
async def test_apply_filters_swallows_exceptions(self):
"""apply_filters logs but does not raise on callback errors."""
reg = get_hook_registry()
reg.register_filter("test.filter", lambda v: (_ for _ in ()).throw(ValueError("boom")))
reg.register_filter("test.filter", lambda v: v + "!")
result = await apply_filters("test.filter", "test")
# First filter errored, second still ran
assert result == "test!"
def test_reset_for_testing(self):
"""_reset_for_testing clears all state."""
reg = get_hook_registry()
reg.register_action("test.action", lambda: None)
reg.register_filter("test.filter", lambda v: v)
reg._reset_for_testing()
assert not reg.list_actions()
assert not reg.list_filters()
+101
View File
@@ -0,0 +1,101 @@
"""Tests for PluginManifest validation: SemVer, hook names, marketplace fields."""
from __future__ import annotations
import pytest
from app.plugins.manifest import PluginManifest
class TestManifestValidation:
def test_valid_min_app_version(self):
"""Valid SemVer min_app_version is accepted."""
m = PluginManifest(
name="test", version="1.0.0", display_name="Test",
min_app_version="1.2.3",
)
assert m.min_app_version == "1.2.3"
def test_default_min_app_version(self):
"""Default min_app_version is 0.0.0."""
m = PluginManifest(name="test", version="1.0.0", display_name="Test")
assert m.min_app_version == "0.0.0"
def test_invalid_min_app_version(self):
"""Invalid SemVer min_app_version is rejected."""
with pytest.raises(Exception):
PluginManifest(
name="test", version="1.0.0", display_name="Test",
min_app_version="not-a-version",
)
def test_valid_hooks(self):
"""Valid hook names are accepted."""
m = PluginManifest(
name="test", version="1.0.0", display_name="Test",
hooks=["contact.before_create", "mail.after_send"],
)
assert len(m.hooks) == 2
def test_invalid_hook_name(self):
"""Invalid hook name format is rejected."""
with pytest.raises(Exception):
PluginManifest(
name="test", version="1.0.0", display_name="Test",
hooks=["InvalidHookName"],
)
def test_invalid_hook_no_dot(self):
"""Hook name without dot is rejected."""
with pytest.raises(Exception):
PluginManifest(
name="test", version="1.0.0", display_name="Test",
hooks=["contact"],
)
def test_empty_hooks_allowed(self):
"""Empty hooks list is allowed."""
m = PluginManifest(
name="test", version="1.0.0", display_name="Test",
hooks=[],
)
assert m.hooks == []
def test_marketplace_fields_defaults(self):
"""All marketplace fields have correct defaults."""
m = PluginManifest(name="test", version="1.0.0", display_name="Test")
assert m.author == ""
assert m.author_email == ""
assert m.homepage == ""
assert m.license == "MIT"
assert m.icon == ""
assert m.screenshots == []
assert m.changelog == ""
assert m.marketplace_tags == []
assert m.price == 0.0
assert m.contract_version == "1.0.0"
def test_marketplace_fields_set(self):
"""Marketplace fields can be set."""
m = PluginManifest(
name="test", version="1.0.0", display_name="Test",
author="Jane Doe",
author_email="jane@example.com",
homepage="https://example.com/plugin",
license="Apache-2.0",
icon="📦",
screenshots=["https://example.com/s1.png"],
changelog="https://example.com/changelog.md",
marketplace_tags=["crm", "ai"],
price=9.99,
contract_version="2.0.0",
)
assert m.author == "Jane Doe"
assert m.license == "Apache-2.0"
assert m.price == 9.99
assert m.contract_version == "2.0.0"
def test_name_validation_lowercase(self):
"""Plugin name is lowercased."""
m = PluginManifest(name="MyPlugin", version="1.0.0", display_name="Test")
assert m.name == "myplugin"
+157
View File
@@ -0,0 +1,157 @@
"""Tests for marketplace plugin system: signature, quarantine, allowlist."""
from __future__ import annotations
import hashlib
import tempfile
from pathlib import Path
import pytest
from app.plugins.signature import PluginSignature
from app.plugins.quarantine import (
QuarantineError,
_check_dangerous_imports,
_check_migration_sql,
_validate_manifest,
)
class TestPluginSignature:
def test_compute_hash(self, tmp_path):
"""compute_hash returns a valid SHA-256 hex string."""
test_file = tmp_path / "test.zip"
test_file.write_bytes(b"test content")
h = PluginSignature.compute_hash(test_file)
assert len(h) == 64 # SHA-256 hex
assert h == hashlib.sha256(b"test content").hexdigest()
def test_verify_signature_without_pynacl(self, tmp_path):
"""verify_signature returns False if PyNaCl is not installed."""
test_file = tmp_path / "test.zip"
test_file.write_bytes(b"test")
# Without PyNaCl installed, returns False
result = PluginSignature.verify_signature(test_file, b"sig", b"key")
assert result in (False, True) # Depends on whether pynacl is installed
class TestQuarantineValidation:
def test_validate_manifest_valid(self, tmp_path):
"""_validate_manifest passes for a valid plugin structure."""
plugin_dir = tmp_path / "test_plugin"
plugin_dir.mkdir()
(plugin_dir / "plugin.py").write_text(
"from app.plugins.base import BasePlugin\n"
"from app.plugins.manifest import PluginManifest\n"
"class TestPlugin(BasePlugin):\n"
" manifest = PluginManifest(name='test', version='1.0.0', display_name='Test')\n"
)
result = _validate_manifest(plugin_dir)
assert result["has_manifest"] is True
def test_validate_manifest_missing(self, tmp_path):
"""_validate_manifest raises for missing plugin.py."""
with pytest.raises(QuarantineError, match="plugin.py or __init__.py"):
_validate_manifest(tmp_path)
def test_validate_manifest_no_manifest(self, tmp_path):
"""_validate_manifest raises when PluginManifest is missing."""
plugin_dir = tmp_path / "test_plugin"
plugin_dir.mkdir()
(plugin_dir / "plugin.py").write_text("print('hello')")
with pytest.raises(QuarantineError, match="PluginManifest"):
_validate_manifest(plugin_dir)
def test_check_dangerous_imports_clean(self, tmp_path):
"""_check_dangerous_imports returns empty for safe code."""
plugin_dir = tmp_path / "safe_plugin"
plugin_dir.mkdir()
(plugin_dir / "plugin.py").write_text(
"import logging\n"
"from app.plugins.base import BasePlugin\n"
)
result = _check_dangerous_imports(plugin_dir)
assert result == []
def test_check_dangerous_imports_found(self, tmp_path):
"""_check_dangerous_imports detects dangerous patterns."""
plugin_dir = tmp_path / "dangerous_plugin"
plugin_dir.mkdir()
(plugin_dir / "plugin.py").write_text(
"import os\n"
"os.system('rm -rf /')\n"
)
result = _check_dangerous_imports(plugin_dir)
assert len(result) > 0
assert any("os.system" in r for r in result)
def test_check_migration_sql_no_migrations(self, tmp_path):
"""_check_migration_sql returns empty when no migrations dir."""
result = _check_migration_sql(tmp_path)
assert result == []
def test_check_migration_sql_valid(self, tmp_path):
"""_check_migration_sql passes for valid SQL with tenant_id."""
migrations = tmp_path / "migrations"
migrations.mkdir()
(migrations / "0001_initial.sql").write_text(
"CREATE TABLE items (id UUID, tenant_id UUID NOT NULL);\n"
)
result = _check_migration_sql(tmp_path)
assert result == []
def test_check_migration_sql_missing_tenant_id(self, tmp_path):
"""_check_migration_sql detects missing tenant_id."""
migrations = tmp_path / "migrations"
migrations.mkdir()
(migrations / "0001_initial.sql").write_text(
"CREATE TABLE items (id UUID);\n"
)
result = _check_migration_sql(tmp_path)
assert len(result) > 0
assert "tenant_id" in result[0]
def test_check_migration_sql_drop_database(self, tmp_path):
"""_check_migration_sql detects DROP DATABASE."""
migrations = tmp_path / "migrations"
migrations.mkdir()
(migrations / "0001_initial.sql").write_text(
"DROP DATABASE leocrm;\n"
)
result = _check_migration_sql(tmp_path)
assert len(result) > 0
assert "DROP" in result[0]
class TestManifestMarketplaceFields:
def test_manifest_has_marketplace_fields(self):
"""PluginManifest has marketplace fields."""
from app.plugins.manifest import PluginManifest
m = PluginManifest(
name="test",
version="1.0.0",
display_name="Test",
author="Test Author",
license="MIT",
min_app_version="1.0.0",
)
assert m.author == "Test Author"
assert m.license == "MIT"
assert m.min_app_version == "1.0.0"
assert m.contract_version == "1.0.0"
assert m.hooks == []
def test_manifest_marketplace_optional_fields(self):
"""PluginManifest marketplace fields have defaults."""
from app.plugins.manifest import PluginManifest
m = PluginManifest(
name="test",
version="1.0.0",
display_name="Test",
)
assert m.author == ""
assert m.homepage == ""
assert m.license == "MIT"
assert m.price == 0.0
assert m.screenshots == []
assert m.marketplace_tags == []
+107
View File
@@ -0,0 +1,107 @@
"""Tests for the SemVer comparison module."""
from __future__ import annotations
import pytest
from app.plugins.semver import (
SemVer,
compare_versions,
is_breaking_change,
is_compatible,
)
class TestSemVerParse:
def test_parse_simple(self):
v = SemVer.parse("1.2.3")
assert v.major == 1
assert v.minor == 2
assert v.patch == 3
assert v.prerelease == ""
def test_parse_with_prerelease(self):
v = SemVer.parse("1.0.0-alpha.1")
assert v.major == 1
assert v.minor == 0
assert v.patch == 0
assert v.prerelease == "alpha.1"
def test_parse_with_v_prefix(self):
v = SemVer.parse("v2.0.0")
assert v.major == 2
def test_parse_invalid(self):
with pytest.raises(ValueError):
SemVer.parse("not-a-version")
def test_parse_empty(self):
with pytest.raises(ValueError):
SemVer.parse("")
def test_parse_two_parts(self):
with pytest.raises(ValueError):
SemVer.parse("1.2")
def test_parse_four_parts(self):
with pytest.raises(ValueError):
SemVer.parse("1.2.3.4")
class TestSemVerComparison:
def test_equal(self):
assert SemVer.parse("1.0.0") == SemVer.parse("1.0.0")
def test_less_than(self):
assert SemVer.parse("1.0.0") < SemVer.parse("1.0.1")
assert SemVer.parse("1.0.0") < SemVer.parse("1.1.0")
assert SemVer.parse("1.0.0") < SemVer.parse("2.0.0")
def test_greater_than(self):
assert SemVer.parse("1.0.1") > SemVer.parse("1.0.0")
assert SemVer.parse("2.0.0") > SemVer.parse("1.9.9")
def test_prerelease_lower_than_release(self):
assert SemVer.parse("1.0.0-alpha") < SemVer.parse("1.0.0")
assert SemVer.parse("1.0.0-beta.1") < SemVer.parse("1.0.0")
def test_prerelease_ordering(self):
assert SemVer.parse("1.0.0-alpha.1") < SemVer.parse("1.0.0-alpha.2")
assert SemVer.parse("1.0.0-alpha") < SemVer.parse("1.0.0-beta")
def test_str(self):
assert str(SemVer.parse("1.2.3")) == "1.2.3"
assert str(SemVer.parse("1.0.0-beta.1")) == "1.0.0-beta.1"
class TestSemVerCompatibility:
def test_breaking_change(self):
assert is_breaking_change("1.0.0", "2.0.0")
assert not is_breaking_change("1.0.0", "1.5.0")
def test_compatible_same_major(self):
assert is_compatible("1.5.0", "1.0.0")
assert not is_compatible("1.0.0", "1.5.0")
def test_compatible_higher_major(self):
assert is_compatible("2.0.0", "1.0.0")
assert not is_compatible("1.0.0", "2.0.0")
def test_is_upgrade_from(self):
assert SemVer.parse("1.1.0").is_upgrade_from(SemVer.parse("1.0.0"))
assert not SemVer.parse("1.0.0").is_upgrade_from(SemVer.parse("1.1.0"))
def test_is_downgrade_from(self):
assert SemVer.parse("1.0.0").is_downgrade_from(SemVer.parse("1.1.0"))
assert not SemVer.parse("1.1.0").is_downgrade_from(SemVer.parse("1.0.0"))
class TestCompareVersions:
def test_compare_equal(self):
assert compare_versions("1.0.0", "1.0.0") == 0
def test_compare_less(self):
assert compare_versions("1.0.0", "1.0.1") == -1
def test_compare_greater(self):
assert compare_versions("1.1.0", "1.0.0") == 1
+67
View File
@@ -0,0 +1,67 @@
"""Tests for plugin versioning: upgrade, downgrade, compatibility checks."""
from __future__ import annotations
import pytest
from app.plugins.semver import SemVer
from app.plugins.manifest import PluginManifest
class TestManifestVersioning:
def test_manifest_has_min_app_version(self):
"""PluginManifest has min_app_version field."""
m = PluginManifest(
name="test",
version="1.0.0",
display_name="Test",
)
assert hasattr(m, "min_app_version")
assert m.min_app_version == "0.0.0"
def test_manifest_with_min_app_version(self):
"""PluginManifest can set min_app_version."""
m = PluginManifest(
name="test",
version="1.0.0",
display_name="Test",
min_app_version="1.5.0",
)
assert m.min_app_version == "1.5.0"
def test_manifest_extra_forbid_still_works(self):
"""Manifest still rejects unknown fields."""
with pytest.raises(Exception):
PluginManifest(
name="test",
version="1.0.0",
display_name="Test",
unknown_field="value",
)
class TestVersionComparison:
def test_upgrade_detection(self):
"""SemVer correctly detects upgrades."""
old = SemVer.parse("1.0.0")
new = SemVer.parse("1.1.0")
assert new.is_upgrade_from(old)
assert not old.is_upgrade_from(new)
def test_downgrade_detection(self):
"""SemVer correctly detects downgrades."""
old = SemVer.parse("1.1.0")
new = SemVer.parse("1.0.0")
assert new.is_downgrade_from(old)
def test_breaking_change_detection(self):
"""Major version change is a breaking change."""
assert SemVer.parse("1.0.0").is_breaking_change(SemVer.parse("2.0.0"))
assert not SemVer.parse("1.0.0").is_breaking_change(SemVer.parse("1.5.0"))
def test_compatibility_check(self):
"""Version compatibility works correctly."""
assert SemVer.parse("1.5.0").is_compatible_with(SemVer.parse("1.0.0"))
assert not SemVer.parse("1.0.0").is_compatible_with(SemVer.parse("1.5.0"))
assert SemVer.parse("2.0.0").is_compatible_with(SemVer.parse("1.0.0"))
assert not SemVer.parse("1.0.0").is_compatible_with(SemVer.parse("2.0.0"))