fix: BUG-080/082 (20 unused frontend components deleted), BUG-083 (useTenant.ts deleted), BUG-011 (playwright baseURL), BUG-069 (unused python modules deleted), BUG-065 (already has eager loading), BUG-026 (already fixed 422), BUG-023 (no sync I/O found)
Check Cross-Plugin Imports / check (push) Has been cancelled
Check Cross-Plugin Imports / check (push) Has been cancelled
This commit is contained in:
@@ -1,172 +0,0 @@
|
||||
"""CustomFieldDefinition service — CRUD with tenant isolation and visibility filter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.visibility import apply_visibility_filter, check_single_entity_access
|
||||
from app.models.custom_field_definition import CustomFieldDefinition
|
||||
|
||||
|
||||
def _definition_to_dict(d: CustomFieldDefinition) -> dict[str, Any]:
|
||||
"""Serialize a CustomFieldDefinition ORM object to dict."""
|
||||
return {
|
||||
"id": str(d.id),
|
||||
"entity": d.entity,
|
||||
"name": d.name,
|
||||
"label": d.label,
|
||||
"field_type": d.field_type,
|
||||
"options": d.options,
|
||||
"default_value": d.default_value,
|
||||
"required": d.required,
|
||||
"is_active": d.is_active,
|
||||
"sort_order": d.sort_order,
|
||||
"owner_id": str(d.owner_id) if d.owner_id else None,
|
||||
"created_by": str(d.created_by) if d.created_by else None,
|
||||
"updated_by": str(d.updated_by) if d.updated_by else None,
|
||||
}
|
||||
|
||||
|
||||
async def list_custom_field_definitions(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
entity: str | None = None,
|
||||
user_id: uuid.UUID | None = None,
|
||||
is_system_admin: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""List custom field definitions for a tenant, optionally filtered by entity."""
|
||||
q = select(CustomFieldDefinition).where(
|
||||
CustomFieldDefinition.tenant_id == tenant_id,
|
||||
CustomFieldDefinition.is_active == True, # noqa: E712
|
||||
)
|
||||
if entity:
|
||||
q = q.where(CustomFieldDefinition.entity == entity)
|
||||
if user_id and not is_system_admin:
|
||||
q = await apply_visibility_filter(
|
||||
db, q, "custom_field_definition", CustomFieldDefinition, user_id, tenant_id, is_system_admin
|
||||
)
|
||||
q = q.order_by(CustomFieldDefinition.sort_order, CustomFieldDefinition.name)
|
||||
result = await db.execute(q)
|
||||
return [_definition_to_dict(d) for d in result.scalars().all()]
|
||||
|
||||
|
||||
async def get_custom_field_definition(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
definition_id: uuid.UUID,
|
||||
user_id: uuid.UUID | None = None,
|
||||
is_system_admin: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Get a single custom field definition by ID."""
|
||||
q = select(CustomFieldDefinition).where(
|
||||
CustomFieldDefinition.id == definition_id,
|
||||
CustomFieldDefinition.tenant_id == tenant_id,
|
||||
)
|
||||
result = await db.execute(q)
|
||||
definition = result.scalar_one_or_none()
|
||||
if definition is None:
|
||||
return None
|
||||
if user_id and not is_system_admin:
|
||||
has_access = await check_single_entity_access(
|
||||
db, "custom_field_definition", definition.id, user_id, tenant_id, "read", is_system_admin
|
||||
)
|
||||
if not has_access:
|
||||
raise PermissionError("No access")
|
||||
return _definition_to_dict(definition)
|
||||
|
||||
|
||||
async def create_custom_field_definition(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
data: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new custom field definition."""
|
||||
definition = CustomFieldDefinition(
|
||||
tenant_id=tenant_id,
|
||||
entity=data["entity"],
|
||||
name=data["name"],
|
||||
label=data["label"],
|
||||
field_type=data["field_type"],
|
||||
options=data.get("options"),
|
||||
default_value=data.get("default_value"),
|
||||
required=data.get("required", False),
|
||||
is_active=data.get("is_active", True),
|
||||
sort_order=data.get("sort_order", 0),
|
||||
created_by=user_id,
|
||||
updated_by=user_id,
|
||||
owner_id=user_id,
|
||||
)
|
||||
db.add(definition)
|
||||
await db.flush()
|
||||
await db.refresh(definition)
|
||||
return _definition_to_dict(definition)
|
||||
|
||||
|
||||
async def update_custom_field_definition(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
definition_id: uuid.UUID,
|
||||
data: dict[str, Any],
|
||||
is_system_admin: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Update an existing custom field definition."""
|
||||
q = select(CustomFieldDefinition).where(
|
||||
CustomFieldDefinition.id == definition_id,
|
||||
CustomFieldDefinition.tenant_id == tenant_id,
|
||||
)
|
||||
result = await db.execute(q)
|
||||
definition = result.scalar_one_or_none()
|
||||
if definition is None:
|
||||
return None
|
||||
|
||||
if not is_system_admin:
|
||||
has_access = await check_single_entity_access(
|
||||
db, "custom_field_definition", definition.id, user_id, tenant_id, "write", is_system_admin
|
||||
)
|
||||
if not has_access:
|
||||
raise PermissionError("No access")
|
||||
|
||||
update_fields = ["label", "field_type", "options", "default_value", "required", "is_active", "sort_order"]
|
||||
for field in update_fields:
|
||||
if field in data:
|
||||
setattr(definition, field, data[field])
|
||||
|
||||
definition.updated_by = user_id
|
||||
await db.flush()
|
||||
await db.refresh(definition)
|
||||
return _definition_to_dict(definition)
|
||||
|
||||
|
||||
async def delete_custom_field_definition(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
definition_id: uuid.UUID,
|
||||
is_system_admin: bool = False,
|
||||
) -> bool:
|
||||
"""Delete a custom field definition."""
|
||||
q = select(CustomFieldDefinition).where(
|
||||
CustomFieldDefinition.id == definition_id,
|
||||
CustomFieldDefinition.tenant_id == tenant_id,
|
||||
)
|
||||
result = await db.execute(q)
|
||||
definition = result.scalar_one_or_none()
|
||||
if definition is None:
|
||||
return False
|
||||
|
||||
if not is_system_admin:
|
||||
has_access = await check_single_entity_access(
|
||||
db, "custom_field_definition", definition.id, user_id, tenant_id, "admin", is_system_admin
|
||||
)
|
||||
if not has_access:
|
||||
raise PermissionError("No access")
|
||||
|
||||
await db.delete(definition)
|
||||
await db.flush()
|
||||
return True
|
||||
@@ -1,187 +0,0 @@
|
||||
"""Plugin install service — business logic for plugin installation from ZIP/URL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.services.plugin_service import get_plugin_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PluginInstallService:
|
||||
"""Service layer for plugin installation operations.
|
||||
|
||||
Handles ZIP extraction, security validation, and plugin registration.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def validate_manifest_name(name: str) -> str:
|
||||
"""Validate plugin name is alphanumeric with underscores only."""
|
||||
if not re.match(r"^[a-zA-Z][a-zA-Z0-9_]*$", name):
|
||||
raise ValueError(
|
||||
f"Invalid plugin name '{name}': must start with a letter and contain only "
|
||||
f"alphanumeric characters and underscores"
|
||||
)
|
||||
return name
|
||||
|
||||
@staticmethod
|
||||
def check_dangerous_imports(source_code: str) -> list[str]:
|
||||
"""Check plugin source for dangerous imports/patterns.
|
||||
|
||||
Returns a list of dangerous patterns found (empty if safe).
|
||||
"""
|
||||
dangerous_patterns = [
|
||||
(r"\bos\.system\b", "os.system call"),
|
||||
(r"\bsubprocess\.", "subprocess module"),
|
||||
(r"\beval\s*\(", "eval() call"),
|
||||
(r"\bexec\s*\(", "exec() call"),
|
||||
(r"\b__import__\s*\(", "__import__() call"),
|
||||
(r"\bcompile\s*\(", "compile() call"),
|
||||
]
|
||||
found: list[str] = []
|
||||
for pattern, description in dangerous_patterns:
|
||||
if re.search(pattern, source_code):
|
||||
found.append(description)
|
||||
return found
|
||||
|
||||
@staticmethod
|
||||
def check_migration_sql(sql_content: str) -> list[str]:
|
||||
"""Basic SQL validation for migration files.
|
||||
|
||||
Returns a list of issues found (empty if OK).
|
||||
"""
|
||||
issues: list[str] = []
|
||||
lines = sql_content.strip().split("\n")
|
||||
for i, line in enumerate(lines, 1):
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("--"):
|
||||
continue
|
||||
if stripped.count("(") != stripped.count(")"):
|
||||
issues.append(f"Line {i}: unbalanced parentheses")
|
||||
if re.search(r"\bDROP\s+TABLE\b", stripped, re.IGNORECASE):
|
||||
issues.append(f"Line {i}: DROP TABLE is not allowed in plugin migrations")
|
||||
return issues
|
||||
|
||||
@staticmethod
|
||||
def find_plugin_class_in_module(module: Any) -> type[BasePlugin] | None:
|
||||
"""Find a BasePlugin subclass in a module."""
|
||||
for attr_name in dir(module):
|
||||
attr = getattr(module, attr_name)
|
||||
if (
|
||||
isinstance(attr, type)
|
||||
and issubclass(attr, BasePlugin)
|
||||
and attr is not BasePlugin
|
||||
):
|
||||
return attr
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def extract_plugin_from_zip(zip_path: str) -> tuple[Path, str, type[BasePlugin]]:
|
||||
"""Extract a ZIP file and find the plugin class.
|
||||
|
||||
Returns (extract_dir, plugin_name, plugin_class).
|
||||
"""
|
||||
extract_dir = Path(tempfile.mkdtemp(prefix="plugin_upload_"))
|
||||
try:
|
||||
with zipfile.ZipFile(zip_path, "r") as zf:
|
||||
bad_files = [f for f in zf.namelist() if f.startswith("..") or f.startswith("/")]
|
||||
if bad_files:
|
||||
raise ValueError(f"ZIP contains files with unsafe paths: {bad_files}")
|
||||
zf.extractall(extract_dir)
|
||||
|
||||
plugin_py_path: Path | None = None
|
||||
for fpath in extract_dir.rglob("plugin.py"):
|
||||
plugin_py_path = fpath
|
||||
break
|
||||
|
||||
if plugin_py_path is None:
|
||||
raise ValueError("ZIP does not contain a plugin.py file")
|
||||
|
||||
source_code = plugin_py_path.read_text(encoding="utf-8")
|
||||
dangerous = PluginInstallService.check_dangerous_imports(source_code)
|
||||
if dangerous:
|
||||
raise ValueError(
|
||||
f"Plugin contains dangerous patterns: {', '.join(dangerous)}"
|
||||
)
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"uploaded_plugin", plugin_py_path
|
||||
)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ValueError("Could not load plugin.py module")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
plugin_class = PluginInstallService.find_plugin_class_in_module(module)
|
||||
if plugin_class is None:
|
||||
raise ValueError(
|
||||
"plugin.py does not contain a BasePlugin subclass"
|
||||
)
|
||||
|
||||
plugin_instance = plugin_class()
|
||||
plugin_name = plugin_instance.name
|
||||
|
||||
manifest = plugin_instance.manifest
|
||||
if not manifest.name or not manifest.version or not manifest.display_name:
|
||||
raise ValueError(
|
||||
"Plugin manifest must include name, version, and display_name"
|
||||
)
|
||||
|
||||
PluginInstallService.validate_manifest_name(manifest.name)
|
||||
|
||||
migrations_dir = plugin_py_path.parent / "migrations"
|
||||
if migrations_dir.exists():
|
||||
for sql_file in sorted(migrations_dir.glob("*.sql")):
|
||||
sql_content = sql_file.read_text(encoding="utf-8")
|
||||
issues = PluginInstallService.check_migration_sql(sql_content)
|
||||
if issues:
|
||||
raise ValueError(
|
||||
f"Migration file {sql_file.name} has issues: {'; '.join(issues)}"
|
||||
)
|
||||
|
||||
return extract_dir, plugin_name, plugin_class
|
||||
|
||||
except Exception:
|
||||
shutil.rmtree(extract_dir, ignore_errors=True)
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def install_plugin_from_dir(
|
||||
extract_dir: Path,
|
||||
plugin_name: str,
|
||||
plugin_class: type[BasePlugin],
|
||||
) -> None:
|
||||
"""Copy plugin directory to builtins and register it.
|
||||
|
||||
Copies the extracted plugin directory to app/plugins/builtins/{plugin_name}/.
|
||||
"""
|
||||
builtins_dir = Path(__file__).parent.parent / "plugins" / "builtins" / plugin_name
|
||||
builtins_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for item in extract_dir.iterdir():
|
||||
dest = builtins_dir / item.name
|
||||
if item.is_dir():
|
||||
if dest.exists():
|
||||
shutil.rmtree(dest)
|
||||
shutil.copytree(item, dest)
|
||||
else:
|
||||
shutil.copy2(item, dest)
|
||||
|
||||
registry = get_plugin_service().registry
|
||||
instance = plugin_class()
|
||||
registry.register_plugin(instance)
|
||||
|
||||
logger.info(
|
||||
"Installed plugin '%s' from uploaded ZIP to %s",
|
||||
plugin_name,
|
||||
builtins_dir,
|
||||
)
|
||||
@@ -1,162 +0,0 @@
|
||||
"""SavedView service — CRUD with tenant isolation and visibility filter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.visibility import apply_visibility_filter, check_single_entity_access
|
||||
from app.models.saved_view import SavedView
|
||||
|
||||
|
||||
def _view_to_dict(v: SavedView) -> dict[str, Any]:
|
||||
"""Serialize a SavedView ORM object to dict."""
|
||||
return {
|
||||
"id": str(v.id),
|
||||
"name": v.name,
|
||||
"entity_type": v.entity_type,
|
||||
"view_config": v.view_config,
|
||||
"user_id": str(v.user_id),
|
||||
"created_at": v.created_at.isoformat() if v.created_at else None,
|
||||
"updated_at": v.updated_at.isoformat() if v.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
async def list_saved_views(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
entity_type: str | None = None,
|
||||
user_id: uuid.UUID | None = None,
|
||||
is_system_admin: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""List saved views for a tenant, optionally filtered by entity_type."""
|
||||
q = select(SavedView).where(
|
||||
SavedView.tenant_id == tenant_id,
|
||||
SavedView.deleted_at.is_(None),
|
||||
)
|
||||
if entity_type:
|
||||
q = q.where(SavedView.entity_type == entity_type)
|
||||
if user_id and not is_system_admin:
|
||||
q = await apply_visibility_filter(
|
||||
db, q, "saved_view", SavedView, user_id, tenant_id, is_system_admin
|
||||
)
|
||||
q = q.order_by(SavedView.name)
|
||||
result = await db.execute(q)
|
||||
return [_view_to_dict(v) for v in result.scalars().all()]
|
||||
|
||||
|
||||
async def get_saved_view(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
view_id: uuid.UUID,
|
||||
user_id: uuid.UUID | None = None,
|
||||
is_system_admin: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Get a single saved view by ID."""
|
||||
q = select(SavedView).where(
|
||||
SavedView.id == view_id,
|
||||
SavedView.tenant_id == tenant_id,
|
||||
SavedView.deleted_at.is_(None),
|
||||
)
|
||||
result = await db.execute(q)
|
||||
saved = result.scalar_one_or_none()
|
||||
if saved is None:
|
||||
return None
|
||||
if user_id and not is_system_admin:
|
||||
has_access = await check_single_entity_access(
|
||||
db, "saved_view", saved.id, user_id, tenant_id, "read", is_system_admin
|
||||
)
|
||||
if not has_access:
|
||||
raise PermissionError("No access")
|
||||
return _view_to_dict(saved)
|
||||
|
||||
|
||||
async def create_saved_view(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
data: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Create a new saved view."""
|
||||
saved = SavedView(
|
||||
tenant_id=tenant_id,
|
||||
user_id=user_id,
|
||||
name=data["name"],
|
||||
entity_type=data["entity_type"],
|
||||
view_config=data.get("view_config", {}),
|
||||
owner_id=user_id,
|
||||
)
|
||||
db.add(saved)
|
||||
await db.flush()
|
||||
await db.refresh(saved)
|
||||
return _view_to_dict(saved)
|
||||
|
||||
|
||||
async def update_saved_view(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
view_id: uuid.UUID,
|
||||
data: dict[str, Any],
|
||||
is_system_admin: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Update a saved view."""
|
||||
q = select(SavedView).where(
|
||||
SavedView.id == view_id,
|
||||
SavedView.tenant_id == tenant_id,
|
||||
SavedView.deleted_at.is_(None),
|
||||
)
|
||||
result = await db.execute(q)
|
||||
saved = result.scalar_one_or_none()
|
||||
if saved is None:
|
||||
return None
|
||||
|
||||
if not is_system_admin:
|
||||
has_access = await check_single_entity_access(
|
||||
db, "saved_view", saved.id, user_id, tenant_id, "write", is_system_admin
|
||||
)
|
||||
if not has_access:
|
||||
raise PermissionError("No access")
|
||||
|
||||
if "name" in data and data["name"] is not None:
|
||||
saved.name = data["name"]
|
||||
if "view_config" in data and data["view_config"] is not None:
|
||||
saved.view_config = data["view_config"]
|
||||
|
||||
await db.flush()
|
||||
await db.refresh(saved)
|
||||
return _view_to_dict(saved)
|
||||
|
||||
|
||||
async def delete_saved_view(
|
||||
db: AsyncSession,
|
||||
tenant_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
view_id: uuid.UUID,
|
||||
is_system_admin: bool = False,
|
||||
) -> bool:
|
||||
"""Soft-delete a saved view."""
|
||||
q = select(SavedView).where(
|
||||
SavedView.id == view_id,
|
||||
SavedView.tenant_id == tenant_id,
|
||||
SavedView.deleted_at.is_(None),
|
||||
)
|
||||
result = await db.execute(q)
|
||||
saved = result.scalar_one_or_none()
|
||||
if saved is None:
|
||||
return False
|
||||
|
||||
if not is_system_admin:
|
||||
has_access = await check_single_entity_access(
|
||||
db, "saved_view", saved.id, user_id, tenant_id, "admin", is_system_admin
|
||||
)
|
||||
if not has_access:
|
||||
raise PermissionError("No access")
|
||||
|
||||
saved.deleted_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
return True
|
||||
Reference in New Issue
Block a user