feat(N1): Scope-Registry via Contract — workspace_scopes() Deklarationen + /scope-definitions Endpoint (#365)
Check Cross-Plugin Imports / check (push) Has been cancelled
Check Cross-Plugin Imports / check (push) Has been cancelled
- workspace_scopes() Contract-Hook (document_placeholders-Muster): Plugins deklarieren Scope-Dimensionen inkl. Wertequellen
- Deklarationen: contacts (Ordner/Typen/Saved-View), dms (Ordner/Datei-Typen), mail (Postfächer), calendar (Kalender/Standard-Ansicht)
- Pydantic fail-closed (schemas/workspace.py): ScopeOption, ScopeValueSource (nur interne /api/v1-Pfade, SSRF-sicher), WorkspaceScopeDimension, WorkspaceModuleScopes
- Aggregator workspace_scope_service.py: discovered-Plugins, ARCH-014-safe, Crash-sicher, ungültige Deklarationen verworfen
- GET /api/v1/workspaces/scope-definitions (workspaces:configure_modules) vor /{workspace_id} registriert
- Security-Invariante: Scope = reine UND-Einschränkung (Workspace ∧ RLS ∧ ABAC ∧ Permissions)
- Tests: 18/18 neu (TDD rot→grün), Regression 17/17, Checker 0 Verstöße, Ruff clean
- Doku: api-documentation.md Workspaces-Sektion, PROGRESS.md Phase N1
This commit is contained in:
@@ -47,6 +47,41 @@ class CalendarContract:
|
||||
]
|
||||
}
|
||||
|
||||
# ─── Workspace Scopes contribution (Phase N1, #359 pattern) ───
|
||||
|
||||
@staticmethod
|
||||
def workspace_scopes() -> list[dict]:
|
||||
"""Scope-Dimensionen des calendar-Moduls für den Workspace-Editor (N1)."""
|
||||
return [
|
||||
{
|
||||
"module_key": "calendar",
|
||||
"dimensions": [
|
||||
{
|
||||
"key": "calendar_ids",
|
||||
"label": "Kalender",
|
||||
"control": "multiselect",
|
||||
"value_source": {
|
||||
"endpoint": "/api/v1/calendars",
|
||||
"items_path": "",
|
||||
"value_key": "id",
|
||||
"label_key": "name",
|
||||
},
|
||||
},
|
||||
{
|
||||
"key": "default_view",
|
||||
"label": "Standard-Ansicht",
|
||||
"control": "select",
|
||||
"options": [
|
||||
{"value": "day", "label": "Tag"},
|
||||
{"value": "week", "label": "Woche"},
|
||||
{"value": "month", "label": "Monat"},
|
||||
{"value": "range", "label": "Zeitraum"},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def get_function(cls, name: str):
|
||||
"""Return a callable exposed by this contract, or None if absent."""
|
||||
|
||||
@@ -349,6 +349,53 @@ class ContactsContract:
|
||||
data[key] = value if value is not None else ""
|
||||
return data
|
||||
|
||||
# ─── Workspace Scopes contribution (Phase N1, #359 pattern) ───
|
||||
# Declares the scope dimensions the contacts module supports; the N2
|
||||
# workspace editor renders its filter UI from these definitions. Scope
|
||||
# VALUES live per workspace in workspace_modules.config (JSONB).
|
||||
|
||||
@staticmethod
|
||||
def workspace_scopes() -> list[dict]:
|
||||
"""Scope-Dimensionen des contacts-Moduls für den Workspace-Editor."""
|
||||
return [
|
||||
{
|
||||
"module_key": "contacts",
|
||||
"dimensions": [
|
||||
{
|
||||
"key": "folder_ids",
|
||||
"label": "Kontakt-Ordner",
|
||||
"control": "multiselect",
|
||||
"value_source": {
|
||||
"endpoint": "/api/v1/contact-folders",
|
||||
"items_path": "items",
|
||||
"value_key": "id",
|
||||
"label_key": "name",
|
||||
},
|
||||
},
|
||||
{
|
||||
"key": "contact_types",
|
||||
"label": "Kontakt-Typen",
|
||||
"control": "multiselect",
|
||||
"options": [
|
||||
{"value": "company", "label": "Firmen"},
|
||||
{"value": "person", "label": "Personen"},
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "default_saved_view_id",
|
||||
"label": "Standard-Ansicht",
|
||||
"control": "select",
|
||||
"value_source": {
|
||||
"endpoint": "/api/v1/saved-views?entity_type=contact",
|
||||
"items_path": "",
|
||||
"value_key": "id",
|
||||
"label_key": "name",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def get_function(cls, name: str):
|
||||
"""Return a callable exposed by this contract, or None if absent."""
|
||||
|
||||
@@ -15,6 +15,40 @@ class DmsContract:
|
||||
DmsFile = DmsFile
|
||||
Folder = Folder
|
||||
|
||||
@staticmethod
|
||||
def workspace_scopes() -> list[dict]:
|
||||
"""Scope-Dimensionen des dms-Moduls für den Workspace-Editor (N1)."""
|
||||
return [
|
||||
{
|
||||
"module_key": "dms",
|
||||
"dimensions": [
|
||||
{
|
||||
"key": "folder_ids",
|
||||
"label": "DMS-Ordner",
|
||||
"control": "multiselect",
|
||||
"value_source": {
|
||||
"endpoint": "/api/v1/dms/folders",
|
||||
"items_path": "",
|
||||
"value_key": "id",
|
||||
"label_key": "name",
|
||||
},
|
||||
},
|
||||
{
|
||||
"key": "file_types",
|
||||
"label": "Datei-Typen",
|
||||
"control": "multiselect",
|
||||
"options": [
|
||||
{"value": "application/pdf", "label": "PDF"},
|
||||
{"value": "image/", "label": "Bilder"},
|
||||
{"value": "spreadsheet", "label": "Tabellen"},
|
||||
{"value": "word", "label": "Dokumente"},
|
||||
{"value": "other", "label": "Sonstige"},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def get_function(cls, name: str):
|
||||
"""Return a callable exposed by this contract, or None if absent."""
|
||||
|
||||
@@ -64,6 +64,30 @@ class MailContract:
|
||||
]
|
||||
}
|
||||
|
||||
# ─── Workspace Scopes contribution (Phase N1, #359 pattern) ───
|
||||
|
||||
@staticmethod
|
||||
def workspace_scopes() -> list[dict]:
|
||||
"""Scope-Dimensionen des mail-Moduls für den Workspace-Editor (N1)."""
|
||||
return [
|
||||
{
|
||||
"module_key": "mail",
|
||||
"dimensions": [
|
||||
{
|
||||
"key": "account_ids",
|
||||
"label": "Postfächer",
|
||||
"control": "multiselect",
|
||||
"value_source": {
|
||||
"endpoint": "/api/v1/mail/accounts",
|
||||
"items_path": "",
|
||||
"value_key": "id",
|
||||
"label_key": "email",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def get_function(cls, name: str):
|
||||
"""Return a callable exposed by this contract, or None if absent."""
|
||||
|
||||
@@ -126,6 +126,25 @@ async def workspace_context(
|
||||
return ctx
|
||||
|
||||
|
||||
@router.get("/scope-definitions")
|
||||
async def workspace_scope_definitions(
|
||||
current_user: dict = Depends(require_permission("workspaces:configure_modules")),
|
||||
):
|
||||
"""N1: Scope-Dimensionen aller Module für den Workspace-Editor.
|
||||
|
||||
Aggregiert ``workspace_scopes()``-Contract-Beiträge der Plugins
|
||||
(document_placeholders-Muster): pro module_key die filterbaren
|
||||
Dimensionen inkl. Wertequellen. Der N2-Editor rendert daraus das
|
||||
Filter-UI; die Werte landen in ``workspace_modules.config``.
|
||||
|
||||
Admin-only: Scope-Definitionen konfigurieren Module-Teilmengen —
|
||||
das ist Workspace-Admin-Kontext (configure_modules), kein Lesen.
|
||||
"""
|
||||
from app.services.workspace_scope_service import get_scope_definitions
|
||||
|
||||
return {"modules": get_scope_definitions()}
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_workspace(
|
||||
body: WorkspaceCreate,
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
|
||||
class WorkspaceBase(BaseModel):
|
||||
@@ -34,6 +36,72 @@ class WorkspaceResponse(WorkspaceBase):
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
|
||||
# ─── N1: Workspace-Scope-Registry (Phase N) ───────────────────
|
||||
|
||||
|
||||
class ScopeOption(BaseModel):
|
||||
"""Ein auswählbarer Wert einer Scope-Dimension."""
|
||||
|
||||
value: str
|
||||
label: str
|
||||
|
||||
|
||||
class ScopeValueSource(BaseModel):
|
||||
"""Deklariert, woher der Editor wählbare Werte lädt.
|
||||
|
||||
Security (fail-closed): nur interne ``/api/v1/...``-Pfade sind
|
||||
erlaubt — keine absoluten URLs, keine protokoll-relativen Pfade,
|
||||
keine externen Hosts (SSRF-sicher per Konstruktion).
|
||||
"""
|
||||
|
||||
endpoint: str
|
||||
items_path: str = "items"
|
||||
value_key: str = "id"
|
||||
label_key: str = "name"
|
||||
|
||||
@field_validator("endpoint")
|
||||
@classmethod
|
||||
def _must_be_internal_api_path(cls, v: str) -> str:
|
||||
if not v.startswith("/api/v1/"):
|
||||
raise ValueError(
|
||||
"value_source endpoint must be an internal /api/v1/ path"
|
||||
)
|
||||
return v
|
||||
|
||||
|
||||
class WorkspaceScopeDimension(BaseModel):
|
||||
"""Eine filterbare Dimension eines Moduls im Workspace (N1).
|
||||
|
||||
``multiselect``/``select`` brauchen zwingend ``options`` oder
|
||||
``value_source`` (fail-closed gegen leere Filter-UI); ``toggle``
|
||||
ist ein reiner Schalter mit ``default``.
|
||||
"""
|
||||
|
||||
key: str = Field(..., min_length=1, max_length=100)
|
||||
label: str = Field(..., min_length=1, max_length=200)
|
||||
control: Literal["multiselect", "select", "toggle"]
|
||||
options: list[ScopeOption] = Field(default_factory=list)
|
||||
value_source: ScopeValueSource | None = None
|
||||
default: bool | str | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _options_or_source_required(self) -> WorkspaceScopeDimension:
|
||||
if self.control in ("multiselect", "select"):
|
||||
if not self.options and self.value_source is None:
|
||||
raise ValueError(
|
||||
f"scope dimension '{self.key}': control '{self.control}' "
|
||||
"requires options or value_source"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class WorkspaceModuleScopes(BaseModel):
|
||||
"""Scope-Contribution eines Plugins für ein Modul."""
|
||||
|
||||
module_key: str = Field(..., min_length=1, max_length=100)
|
||||
dimensions: list[WorkspaceScopeDimension] = Field(..., min_length=1)
|
||||
|
||||
|
||||
class WorkspaceModuleResponse(BaseModel):
|
||||
id: str
|
||||
workspace_id: str
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Workspace-Scope-Registry aggregation (Phase N1, Roadmap Phase N).
|
||||
|
||||
Plugins declare the scope dimensions their modules support via the contract
|
||||
hook ``workspace_scopes()`` — same aggregation pattern as
|
||||
``document_placeholders()`` (#359 philosophy): the module owns its domain,
|
||||
the generic consumer stays module-agnostic.
|
||||
|
||||
The N2 workspace editor renders filter UI from these definitions; scope
|
||||
VALUES are stored per workspace in ``workspace_modules.config`` (JSONB).
|
||||
N3 list filtering applies them as pure AND-restrictions.
|
||||
|
||||
Security-Invariante (Phase N): a workspace can never GRANT visibility —
|
||||
effective visibility is always Workspace-Scope ∧ RLS ∧ ABAC ∧ Permissions.
|
||||
Without an active workspace there is no filter (backward compatible).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.schemas.workspace import WorkspaceModuleScopes
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _parse_contribution(plugin_name: str, contribution: Any) -> WorkspaceModuleScopes | None:
|
||||
"""Validate a single raw contribution; ``None`` when invalid (fail-closed).
|
||||
|
||||
Every declaration must pass the Pydantic schema — invalid dimensions
|
||||
(e.g. a multiselect without options AND value_source) are dropped with a
|
||||
warning instead of breaking the editor endpoint.
|
||||
"""
|
||||
if not isinstance(contribution, dict):
|
||||
return None
|
||||
try:
|
||||
return WorkspaceModuleScopes.model_validate(contribution)
|
||||
except ValidationError as exc:
|
||||
logger.warning(
|
||||
"Invalid workspace_scopes contribution from plugin '%s': %s",
|
||||
plugin_name,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def get_scope_definitions() -> dict[str, list[dict[str, Any]]]:
|
||||
"""Aggregate ``workspace_scopes()`` contributions from all discovered plugins.
|
||||
|
||||
Returns ``module_key -> [dimension, ...]`` for the N2 editor. Contracts
|
||||
of explicitly deactivated plugins stay gone (ARCH-014 unregister marker);
|
||||
never-loaded contracts lazy-load on first access (document_placeholders
|
||||
precedent). A plugin crash while declaring scopes never fails the
|
||||
endpoint — its contribution is simply skipped.
|
||||
"""
|
||||
from app.plugins.builtins.contracts import get_contract_registry
|
||||
from app.plugins.registry import get_registry
|
||||
|
||||
modules: dict[str, list[dict[str, Any]]] = {}
|
||||
for plugin_name in get_registry().list_discovered():
|
||||
contract = get_contract_registry().get_contract(plugin_name)
|
||||
if contract is None:
|
||||
continue
|
||||
fn = getattr(contract, "workspace_scopes", None)
|
||||
if fn is None:
|
||||
continue
|
||||
try:
|
||||
contributions = fn() or []
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception(
|
||||
"workspace_scopes() raised for plugin '%s' — skipping", plugin_name
|
||||
)
|
||||
continue
|
||||
for contribution in contributions:
|
||||
parsed = _parse_contribution(plugin_name, contribution)
|
||||
if parsed is None:
|
||||
continue
|
||||
modules.setdefault(parsed.module_key, []).extend(
|
||||
dimension.model_dump() for dimension in parsed.dimensions
|
||||
)
|
||||
return modules
|
||||
Reference in New Issue
Block a user