fix(arch): externes Audit — 13 Backend-Fixes (Workspace-Modules, Tenant-Manifeste, Lifecycle, Contracts, Permissions)
Check Cross-Plugin Imports / check (push) Has been cancelled

Verifikation: Alle 17 Audit-Findings gegen den Code geprueft — alle bestaetigt.
Backend-Lifecycle-Fixes umgesetzt; 4 Frontend-Plugin-Architektur-Punkte
als Phase Q in die Roadmap eingeplant.

- P1 list_workspaces: Module + User-Counts gebuendelt laden (Editor-Overwrite-Bug)
- P1 active-manifests: Tenant-Deaktivierung (tenant_plugin_activation) filtern
- P1 uninstall: volle Service-Deactivation VOR registry.uninstall()
- P1 ContractRegistry: DB-Aktivstatus-Guard (Restart-Edge-Case) + Re-Activate
- P1/P2 Field-Definitions: voller Lifecycle (register/unregister) im Service
- P1/P2 Contact-Felddefinitionen (39) ins ContactsPlugin-Manifest verschoben
- P1 12 fehlende Permission-Keys registriert (AST-Scan: 0 fehlend)
- P2 contact_folder -> ContactsPlugin; ENTITY_PLUGIN_OWNERS wird befuellt
- P2 Entity-Permission-Fallback fail-closed statt contacts:read
- P2 forgejo_error_reporter is_core=False; DMS is_core=True (ADR-020)
- P2 Worker: Contacts-Trash-Cleanup ins Plugin (get_job_modules-Discovery)
- P1/P2 DSGVO-Export delegiert an DSAR-Collector (kein Core->Contacts)
- P2 False-green Tests korrigiert (or True, veraltete Route-Count-Assertion)

Verifikation: tests/test_audit_architecture_fixes.py 17/17; Regressionen
gruen (contacts_lifecycle, entity_registry, workspace_scopes, rbac,
lifecycle_service); Combo-Order-Test 35/35; Cross-Plugin-Checker 497/0;
compileall sauber; ruff auf 7-Error-Baseline.

Doku: PROGRESS.md Audit-Section, PLATFORM_ROADMAP.md Phase Q (Q1-Q4),
plugin-development-guide.md Lifecycle, permissions.md Katalog.
This commit is contained in:
Agent Zero
2026-09-13 02:25:01 +02:00
parent 86cea5d6c4
commit 4a25ac1379
25 changed files with 1020 additions and 141 deletions
+11 -3
View File
@@ -29,7 +29,9 @@ from app.core.notifications import post_system_message
from app.models.address import Address
from app.models.attachment import Attachment
from app.models.bank_account import BankAccount
from app.models.contact_folder import ContactFolder
# NOTE (audit P2): ContactFolder moved to ContactsPlugin.get_entity_models() —
# the core entity registry no longer imports contact domain models.
from app.models.custom_field_definition import CustomFieldDefinition
from app.models.entity_permission import EntityPermission
from app.models.group import Group, UserGroup
@@ -66,7 +68,8 @@ ENTITY_MODELS: dict[str, type] = {
"webhook": Webhook,
"notification": Notification,
"custom_field_definition": CustomFieldDefinition,
"contact_folder": ContactFolder,
# Audit P2: contact_folder moved to ContactsPlugin.get_entity_models()
# (it is plugin-owned domain data, not a core entity).
}
# W4b: Tracks which plugin registered which entity_type — used to derive
@@ -92,7 +95,12 @@ def get_entity_read_permission(entity_type: str) -> str:
candidates = _core_module_keys(module, "read")
if candidates:
return candidates[0]
return "contacts:read"
# Audit P2: fail closed. An entity that cannot be mapped to an owning
# module must NOT silently default to contacts:read — the sentinel is
# not grantable to any role, so check_entity_read_permission() denies.
# Unknown entity types are already rejected earlier by
# validate_entity_type() (422) before this fallback can matter.
return "__unmapped__:read"
def _core_module_keys(module: str, action: str) -> list[str]:
+42 -4
View File
@@ -118,7 +118,19 @@ class PluginService:
if plugin:
from app.services.entity_permission_service import register_entity_model
for entity_type, model_class in plugin.get_entity_models().items():
register_entity_model(entity_type, model_class)
register_entity_model(entity_type, model_class, plugin_name=name)
# Register field definitions for field-level permissions
# (audit: contribution type now fully lifecycle-integrated)
if plugin:
field_defs = plugin.get_field_definitions()
if field_defs:
get_permission_registry().register_field_definitions(name, field_defs)
# Contract registry: clear inactive markers so contracts of
# a re-activated plugin are served again (audit P1).
from app.plugins.builtins.contracts import get_contract_registry
get_contract_registry().mark_plugin_active(name)
if tenant_id and user_id:
await log_audit(
@@ -188,6 +200,15 @@ class PluginService:
for entity_type in plugin.get_entity_models():
unregister_entity_model(entity_type)
# Unregister field definitions (audit: full lifecycle)
get_permission_registry().unregister_field_definitions(name)
# Contract registry: fail closed for the deactivated plugin
# (ARCH-014 / audit P1 — central, so every plugin is covered
# even if its own on_deactivate forgets the unregister).
from app.plugins.builtins.contracts import get_contract_registry
get_contract_registry().unregister(name)
if tenant_id and user_id:
await log_audit(
db,
@@ -225,6 +246,16 @@ class PluginService:
Deactivates, calls on_uninstall hook, optionally drops tables, removes DB record.
"""
try:
# Audit P1 (uninstall lifecycle): run the FULL service-level
# deactivation first. registry.uninstall()'s internal fallback
# (registry.deactivate) does NOT clean PermissionRegistry,
# _active_plugins or ENTITY_MODELS — an active plugin uninstalled
# directly through the registry left stale registrations behind.
pre = await self._registry._get_plugin_record(db, name)
if pre is not None and pre.active:
await self.deactivate_plugin(
db, name, tenant_id=tenant_id, user_id=user_id
)
record = await self._registry.uninstall(db, name, remove_data=remove_data)
dropped_tables = getattr(record, "dropped_tables", [])
if tenant_id and user_id:
@@ -305,9 +336,16 @@ class PluginService:
return MANIFEST_SCHEMA_DOC.model_dump()
async def get_active_manifests(self, db: AsyncSession) -> list[dict[str, Any]]:
"""Return UI manifests for all active plugins."""
return await self._registry.get_active_manifests(db)
async def get_active_manifests(
self, db: AsyncSession, tenant_id: uuid.UUID | None = None
) -> list[dict[str, Any]]:
"""Return UI manifests for all active plugins.
Audit P1 (tenant manifests): *tenant_id* filters out plugins that are
deactivated for the caller's tenant (tenant_plugin_activation),
mirroring require_active_plugin() so UI and backend agree.
"""
return await self._registry.get_active_manifests(db, tenant_id=tenant_id)
# Global service instance
+36 -8
View File
@@ -52,16 +52,44 @@ async def list_workspaces(
result = await db.execute(q)
workspaces = result.scalars().all()
items = []
for ws in workspaces:
# Count users
count_q = select(func.count()).select_from(WorkspaceUser).where(
WorkspaceUser.workspace_id == ws.id,
if not workspaces:
return {"items": [], "total": 0}
# Audit P1 (Workspace-Editor): load modules for ALL workspaces in one
# query. Previously list_workspaces() returned modules: [] for every
# workspace, so the WorkspaceManager module editor showed all modules
# as hidden (is_visible=false) and saving OVERWROTE the existing config.
ws_ids = [ws.id for ws in workspaces]
mod_result = await db.execute(
select(WorkspaceModule).where(
WorkspaceModule.workspace_id.in_(ws_ids),
WorkspaceModule.tenant_id == tenant_id,
).order_by(WorkspaceModule.menu_order)
)
modules_by_ws: dict[uuid.UUID, list[WorkspaceModule]] = {}
for mod in mod_result.scalars().all():
modules_by_ws.setdefault(mod.workspace_id, []).append(mod)
# User counts for all workspaces in one query (avoids N+1)
count_result = await db.execute(
select(WorkspaceUser.workspace_id, func.count())
.where(
WorkspaceUser.workspace_id.in_(ws_ids),
WorkspaceUser.tenant_id == tenant_id,
)
count_result = await db.execute(count_q)
user_count = count_result.scalar() or 0
items.append(_workspace_to_dict(ws, user_count=user_count))
.group_by(WorkspaceUser.workspace_id)
)
counts_by_ws: dict[uuid.UUID, int] = dict(count_result.all())
items = []
for ws in workspaces:
items.append(
_workspace_to_dict(
ws,
modules=modules_by_ws.get(ws.id, []),
user_count=counts_by_ws.get(ws.id, 0),
)
)
return {"items": items, "total": len(items)}