fix(audit): P0-P3 audit fixes — 838 ruff errors → 0, 30 F821 bugs fixed, 118 files changed
- P0: hooks.py 3-tuple fix, trigger_dispatcher Contract, contacts/plugin unregister_actions_by_owner - P0: 5 test files — check_permission mocks removed, hardcoded DB credential → env var - P1: attachment_service DmsFile via Contract helper, restore_registry/history_hooks dedup - P1: mail/plugin restore unregister, mcp_client datetime.now(UTC), saved_views/filters patterns - P1: ProtectedRoute fail-closed, 13 test assertion fixes (bcrypt, DB-URLs, SECRET_KEYs) - P2: deprecated notifications → post_system_message (3 files), forgejo Base, report_generator lazy import - P2: webhooks permissions, deps.py/roles.py plugin perms removed, import_export default - P2: address/tags/entity_links patterns removed, worker.py Contract-Umgehungen fixed - P2: 28 frontend TODOs (hardcoded constants, deprecated notification API) - P3: dead code, duplicates, deprecated imports, private attr, __import__ inline - P3: 8 frontend TODOs (LucideIcons, inline styles, XSS, i18n) - ruff: 838 → 0 (612 auto-fix + 246 manual + 27 F821 regression fix) - F821: 30 → 0 (AutomationDefinition, DmsFile, user_id, Path, Any, String) - Contract-Umgehungen: 2 neue gefunden (worker.py:169, worker.py:280) und gefixt
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
"""Calendar commands — create, update, delete entries via Command pattern."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.commands.base import BaseCommand, CommandResult
|
||||
from app.core.outbox import enqueue_outbox_event
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CreateCalendarEntryCommand(BaseCommand):
|
||||
"""Create a new calendar entry (appointment, task, reminder)."""
|
||||
|
||||
permission = "calendar:write"
|
||||
|
||||
def __init__(self, calendar_id: str, title: str, start_at: str, end_at: str | None = None,
|
||||
description: str | None = None, location: str | None = None,
|
||||
entry_type: str = "appointment", status: str = "open"):
|
||||
self.calendar_id = calendar_id
|
||||
self.title = title
|
||||
self.start_at = start_at
|
||||
self.end_at = end_at
|
||||
self.description = description
|
||||
self.location = location
|
||||
self.entry_type = entry_type
|
||||
self.status = status
|
||||
|
||||
async def run(self, db: AsyncSession, redis: aioredis.Redis, current_user: dict[str, Any]) -> CommandResult:
|
||||
from app.plugins.builtins.calendar.models import Calendar, CalendarEntry
|
||||
|
||||
tenant_id = self._tenant_id(current_user)
|
||||
user_id = self._user_id(current_user)
|
||||
|
||||
try:
|
||||
cal_id = uuid.UUID(self.calendar_id)
|
||||
except ValueError:
|
||||
return CommandResult.fail("Invalid calendar_id")
|
||||
|
||||
# Verify calendar belongs to tenant
|
||||
cal_result = await db.execute(
|
||||
select(Calendar).where(Calendar.id == cal_id, Calendar.tenant_id == tenant_id)
|
||||
)
|
||||
if cal_result.scalar_one_or_none() is None:
|
||||
return CommandResult.fail("Calendar not found")
|
||||
|
||||
entry_id = uuid.uuid4()
|
||||
entry = CalendarEntry(
|
||||
id=entry_id,
|
||||
tenant_id=tenant_id,
|
||||
calendar_id=cal_id,
|
||||
title=self.title,
|
||||
description=self.description,
|
||||
location=self.location,
|
||||
start_at=datetime.fromisoformat(self.start_at),
|
||||
end_at=datetime.fromisoformat(self.end_at) if self.end_at else None,
|
||||
entry_type=self.entry_type,
|
||||
status=self.status,
|
||||
created_by=user_id,
|
||||
)
|
||||
db.add(entry)
|
||||
await db.flush()
|
||||
|
||||
await enqueue_outbox_event(db, tenant_id, "calendar.entry.created", {
|
||||
"entry_id": str(entry_id),
|
||||
"title": self.title,
|
||||
"start_at": self.start_at,
|
||||
})
|
||||
|
||||
return CommandResult.ok({
|
||||
"id": str(entry_id),
|
||||
"title": self.title,
|
||||
"start_at": self.start_at,
|
||||
"status": self.status,
|
||||
})
|
||||
|
||||
async def audit(self, db: AsyncSession, current_user: dict[str, Any]) -> None:
|
||||
from app.core.audit import log_audit
|
||||
await log_audit(
|
||||
db, self._tenant_id(current_user), self._user_id(current_user),
|
||||
action="calendar.entry.create", entity_type="calendar_entry",
|
||||
changes={"title": self.title, "start_at": self.start_at},
|
||||
)
|
||||
|
||||
|
||||
class UpdateCalendarEntryCommand(BaseCommand):
|
||||
"""Update an existing calendar entry."""
|
||||
|
||||
permission = "calendar:write"
|
||||
|
||||
def __init__(self, entry_id: str, data: dict[str, Any]):
|
||||
self.entry_id = entry_id
|
||||
self.data = data
|
||||
|
||||
async def run(self, db: AsyncSession, redis: aioredis.Redis, current_user: dict[str, Any]) -> CommandResult:
|
||||
from app.plugins.builtins.calendar.models import CalendarEntry
|
||||
|
||||
tenant_id = self._tenant_id(current_user)
|
||||
try:
|
||||
eid = uuid.UUID(self.entry_id)
|
||||
except ValueError:
|
||||
return CommandResult.fail("Invalid entry_id")
|
||||
|
||||
result = await db.execute(
|
||||
select(CalendarEntry).where(CalendarEntry.id == eid, CalendarEntry.tenant_id == tenant_id)
|
||||
)
|
||||
entry = result.scalar_one_or_none()
|
||||
if entry is None:
|
||||
return CommandResult.fail("Calendar entry not found")
|
||||
|
||||
# Apply updates
|
||||
for key, value in self.data.items():
|
||||
if hasattr(entry, key) and key not in ("id", "tenant_id", "created_at"):
|
||||
if key in ("start_at", "end_at") and isinstance(value, str):
|
||||
value = datetime.fromisoformat(value)
|
||||
setattr(entry, key, value)
|
||||
|
||||
await db.flush()
|
||||
|
||||
await enqueue_outbox_event(db, tenant_id, "calendar.entry.updated", {
|
||||
"entry_id": self.entry_id,
|
||||
"changes": self.data,
|
||||
})
|
||||
|
||||
return CommandResult.ok({"id": self.entry_id, "updated": True})
|
||||
|
||||
async def audit(self, db: AsyncSession, current_user: dict[str, Any]) -> None:
|
||||
from app.core.audit import log_audit
|
||||
await log_audit(
|
||||
db, self._tenant_id(current_user), self._user_id(current_user),
|
||||
action="calendar.entry.update", entity_type="calendar_entry",
|
||||
changes={"entry_id": self.entry_id, "fields": list(self.data.keys())},
|
||||
)
|
||||
|
||||
|
||||
class DeleteCalendarEntryCommand(BaseCommand):
|
||||
"""Delete a calendar entry."""
|
||||
|
||||
permission = "calendar:delete"
|
||||
|
||||
def __init__(self, entry_id: str):
|
||||
self.entry_id = entry_id
|
||||
|
||||
async def run(self, db: AsyncSession, redis: aioredis.Redis, current_user: dict[str, Any]) -> CommandResult:
|
||||
from app.plugins.builtins.calendar.models import CalendarEntry
|
||||
|
||||
tenant_id = self._tenant_id(current_user)
|
||||
try:
|
||||
eid = uuid.UUID(self.entry_id)
|
||||
except ValueError:
|
||||
return CommandResult.fail("Invalid entry_id")
|
||||
|
||||
result = await db.execute(
|
||||
select(CalendarEntry).where(CalendarEntry.id == eid, CalendarEntry.tenant_id == tenant_id)
|
||||
)
|
||||
entry = result.scalar_one_or_none()
|
||||
if entry is None:
|
||||
return CommandResult.fail("Calendar entry not found")
|
||||
|
||||
await db.delete(entry)
|
||||
await db.flush()
|
||||
|
||||
await enqueue_outbox_event(db, tenant_id, "calendar.entry.deleted", {"entry_id": self.entry_id})
|
||||
|
||||
return CommandResult.ok({"id": self.entry_id, "deleted": True})
|
||||
|
||||
async def audit(self, db: AsyncSession, current_user: dict[str, Any]) -> None:
|
||||
from app.core.audit import log_audit
|
||||
await log_audit(
|
||||
db, self._tenant_id(current_user), self._user_id(current_user),
|
||||
action="calendar.entry.delete", entity_type="calendar_entry",
|
||||
changes={"entry_id": self.entry_id},
|
||||
)
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.plugins.builtins.contracts import get_contract_registry
|
||||
from app.plugins.builtins.calendar.models import Calendar, CalendarEntry, CalendarEntryLink
|
||||
from app.plugins.builtins.contracts import get_contract_registry
|
||||
|
||||
|
||||
class CalendarContract:
|
||||
|
||||
@@ -3,7 +3,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendDetailTab
|
||||
from app.plugins.manifest import (
|
||||
FrontendDetailTab,
|
||||
FrontendMenuItem,
|
||||
FrontendPageRoute,
|
||||
PluginManifest,
|
||||
PluginRouteDef,
|
||||
)
|
||||
|
||||
|
||||
class CalendarPlugin(BasePlugin):
|
||||
@@ -56,11 +62,45 @@ class CalendarPlugin(BasePlugin):
|
||||
contract_version="1.0.0",
|
||||
)
|
||||
|
||||
async def on_activate(self, db, service_container, event_bus) -> None:
|
||||
"""Activate plugin: register restore config + history hooks."""
|
||||
await super().on_activate(db, service_container, event_bus)
|
||||
|
||||
# Register restore config for CalendarEntry entities (P0-7 fix)
|
||||
from app.core.restore_registry import RestoreConfig, get_restore_registry
|
||||
from app.plugins.builtins.calendar.models import CalendarEntry
|
||||
get_restore_registry().register(RestoreConfig(
|
||||
entity_type="calendar_entry",
|
||||
model_class=CalendarEntry,
|
||||
restore_permission="calendar:write",
|
||||
excluded_fields=frozenset({"calendar_id", "created_by", "assigned_to", "source_mail_id"}),
|
||||
))
|
||||
|
||||
# Register history hooks for CalendarEntry entities (P0-8 fix)
|
||||
from app.core.history_hooks import register_history_hooks
|
||||
from app.core.hooks import get_hook_registry
|
||||
register_history_hooks(
|
||||
get_hook_registry(), "calendar_entry",
|
||||
"calendar_entry.after_create", "calendar_entry.after_update", "calendar_entry.after_delete",
|
||||
owner_tag="calendar",
|
||||
)
|
||||
|
||||
async def on_deactivate(
|
||||
self, db, service_container, event_bus
|
||||
) -> None:
|
||||
"""Deactivate plugin: unregister contract and event listeners."""
|
||||
"""Deactivate plugin: unregister contract, restore, history, events."""
|
||||
# Contract abmelden
|
||||
from app.plugins.builtins.contracts import get_contract_registry
|
||||
get_contract_registry().unregister(self.manifest.name)
|
||||
|
||||
# Unregister restore config (P0-7 fix)
|
||||
from app.core.restore_registry import get_restore_registry
|
||||
get_restore_registry().unregister("calendar_entry")
|
||||
|
||||
# Unregister history hooks (free functions, not bound methods)
|
||||
from app.core.hooks import get_hook_registry
|
||||
get_hook_registry().unregister_actions_by_owner("calendar_entry.after_create", "calendar")
|
||||
get_hook_registry().unregister_actions_by_owner("calendar_entry.after_update", "calendar")
|
||||
get_hook_registry().unregister_actions_by_owner("calendar_entry.after_delete", "calendar")
|
||||
|
||||
await super().on_deactivate(db, service_container, event_bus)
|
||||
|
||||
@@ -22,7 +22,6 @@ from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.db import get_db
|
||||
from app.core.visibility import apply_visibility_filter, check_single_entity_access
|
||||
from app.deps import get_current_user, require_admin, require_permission
|
||||
from app.plugins.builtins.calendar.ics_utils import (
|
||||
export_entries_to_ics,
|
||||
@@ -292,8 +291,8 @@ async def share_calendar(
|
||||
|
||||
# Grant calendar:read (or calendar:write) permission to the shared user's role
|
||||
if body.user_id:
|
||||
from app.models.user import UserTenant
|
||||
from app.models.role import Role
|
||||
from app.models.user import UserTenant
|
||||
shared_user_id = _parse_uuid(body.user_id, "user_id")
|
||||
ut_q = await db.execute(
|
||||
select(UserTenant).where(
|
||||
|
||||
Reference in New Issue
Block a user