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:
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
# Known block types and their expected schema
|
||||
BLOCK_TYPES: dict[str, dict[str, Any]] = {
|
||||
"text": {
|
||||
|
||||
@@ -36,6 +36,7 @@ from app.plugins.builtins.kommunikation.services import (
|
||||
parse_mentions,
|
||||
send_message,
|
||||
)
|
||||
from app.plugins.builtins.kommunikation.services import post_system_message as _post_system_message
|
||||
|
||||
|
||||
class KommunikationContract:
|
||||
@@ -64,6 +65,7 @@ class KommunikationContract:
|
||||
MiniAppDef = MiniAppDef
|
||||
get_miniapp_registry = staticmethod(get_miniapp_registry)
|
||||
reset_miniapp_registry = staticmethod(reset_miniapp_registry)
|
||||
post_system_message = staticmethod(_post_system_message)
|
||||
|
||||
# ─── models (read-only for queries) ───
|
||||
CommConversation = CommConversation
|
||||
|
||||
@@ -8,12 +8,12 @@ import uuid
|
||||
from typing import Any
|
||||
|
||||
import aiofiles
|
||||
|
||||
from fastapi import UploadFile
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.plugins.builtins.dms.contracts import get_contract as get_dms_contract
|
||||
|
||||
_dms = get_dms_contract()
|
||||
DmsFile = _dms.DmsFile
|
||||
Folder = _dms.Folder
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Callable, Awaitable
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
@@ -17,7 +17,8 @@ from sqlalchemy import (
|
||||
UniqueConstraint,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID as PGUUID
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.db import Base, TenantMixin
|
||||
|
||||
@@ -6,7 +6,7 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from app.plugins.base import BasePlugin
|
||||
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute
|
||||
from app.plugins.manifest import FrontendMenuItem, FrontendPageRoute, PluginManifest, PluginRouteDef
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -60,6 +60,10 @@ class KommunikationPlugin(BasePlugin):
|
||||
contract_version="1.0.0",
|
||||
)
|
||||
|
||||
def get_entity_models(self) -> dict[str, type]:
|
||||
from app.plugins.builtins.kommunikation.models import CommConversation
|
||||
return {"comm_conversation": CommConversation}
|
||||
|
||||
async def on_activate(self, db, service_container, event_bus) -> None:
|
||||
"""Register participant registry and WebSocket manager."""
|
||||
await super().on_activate(db, service_container, event_bus)
|
||||
|
||||
@@ -5,25 +5,34 @@ from __future__ import annotations
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File, WebSocket, WebSocketDisconnect, status
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
File,
|
||||
HTTPException,
|
||||
Query,
|
||||
UploadFile,
|
||||
WebSocket,
|
||||
WebSocketDisconnect,
|
||||
)
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.db import get_db
|
||||
from app.core.visibility import apply_visibility_filter
|
||||
from app.deps import get_current_user, require_permission
|
||||
from app.plugins.builtins.kommunikation.content_types import list_block_types
|
||||
from app.plugins.builtins.kommunikation.dms_bridge import DmsBridge
|
||||
from app.plugins.builtins.kommunikation.rbac import CommRBAC
|
||||
from app.plugins.builtins.kommunikation.schemas import (
|
||||
ConversationCreate,
|
||||
ConversationUpdate,
|
||||
MessageCreate,
|
||||
MessageUpdate,
|
||||
MiniAppStartRequest,
|
||||
ParticipantAdd,
|
||||
ParticipantRoleUpdate,
|
||||
ReactionCreate,
|
||||
ReadStateUpdate,
|
||||
MiniAppStartRequest,
|
||||
)
|
||||
from app.plugins.builtins.kommunikation.services import (
|
||||
add_participant,
|
||||
@@ -45,8 +54,6 @@ from app.plugins.builtins.kommunikation.services import (
|
||||
unpin_conversation,
|
||||
update_conversation,
|
||||
)
|
||||
from app.plugins.builtins.kommunikation.content_types import list_block_types
|
||||
from app.plugins.builtins.kommunikation.dms_bridge import DmsBridge
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -57,7 +64,7 @@ def _parse_uuid(val: str, field: str = "id") -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(val)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(400, detail={"detail": f"Invalid {field}", "code": "invalid_id"})
|
||||
raise HTTPException(400, detail={"detail": f"Invalid {field}", "code": "invalid_id"}) from None
|
||||
|
||||
|
||||
# ─── Conversations ───
|
||||
@@ -102,8 +109,8 @@ async def get_single_conversation(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Get a single conversation with participants."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
conv = await get_conversation(db, tenant_id, conv_id, user_id)
|
||||
if conv is None:
|
||||
@@ -119,8 +126,8 @@ async def update_single_conversation(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Update a conversation (title, archive)."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
conv = await update_conversation(db, tenant_id, conv_id, user_id, title=body.title, is_archived=body.is_archived)
|
||||
if conv is None:
|
||||
@@ -135,7 +142,6 @@ async def leave_or_delete_conversation(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Leave (member) or delete (admin) a conversation."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
# For now: just leave (set left_at)
|
||||
@@ -152,8 +158,8 @@ async def pin_conv(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Pin a conversation for the current user."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
await pin_conversation(db, tenant_id, conv_id, user_id)
|
||||
return {"success": True}
|
||||
@@ -179,8 +185,8 @@ async def mute_conv(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Mute a conversation."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
await mute_conversation(db, tenant_id, conv_id, user_id)
|
||||
return {"success": True}
|
||||
@@ -270,8 +276,8 @@ async def get_conv_messages(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Get paginated messages for a conversation."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
if not await CommRBAC.is_participant(db, conv_id, user_id):
|
||||
raise HTTPException(403, detail={"detail": "Not a participant", "code": "forbidden"})
|
||||
@@ -287,8 +293,8 @@ async def send_conv_message(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Send a message to a conversation."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
if not await CommRBAC.can_user_write(db, conv_id, current_user):
|
||||
raise HTTPException(403, detail={"detail": "Cannot write to this conversation", "code": "forbidden"})
|
||||
@@ -359,6 +365,7 @@ async def upload_attachment(
|
||||
)
|
||||
# Get conversation_id from message
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.plugins.builtins.kommunikation.models import CommMessage
|
||||
result = await db.execute(select(CommMessage).where(CommMessage.id == msg_id))
|
||||
msg = result.scalar_one_or_none()
|
||||
@@ -367,7 +374,7 @@ async def upload_attachment(
|
||||
try:
|
||||
return await DmsBridge.store_attachment(db, tenant_id, msg.conversation_id, user_id, file)
|
||||
except ValueError as e:
|
||||
raise HTTPException(413, detail={"detail": str(e), "code": "file_too_large"})
|
||||
raise HTTPException(413, detail={"detail": str(e), "code": "file_too_large"}) from e
|
||||
|
||||
|
||||
# ─── Reactions ───
|
||||
@@ -415,8 +422,8 @@ async def mark_conv_read(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Mark a conversation as read."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
await mark_read(db, tenant_id, conv_id, user_id, body.last_read_msg_id)
|
||||
return {"success": True}
|
||||
@@ -445,8 +452,8 @@ async def start_miniapp(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Start a mini-app in a conversation."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
conv_id = _parse_uuid(conversation_id, "conversation_id")
|
||||
if not await CommRBAC.can_user_write(db, conv_id, current_user):
|
||||
raise HTTPException(403, detail={"detail": "Cannot write", "code": "forbidden"})
|
||||
@@ -500,9 +507,11 @@ async def websocket_endpoint(
|
||||
tenant_id = auth["tenant_id"]
|
||||
|
||||
# Plugin-Gate: check if kommunikation plugin is active (global + tenant)
|
||||
from app.core.permission_registry import get_permission_registry
|
||||
from sqlalchemy import text as sa_text
|
||||
import uuid as _uuid
|
||||
|
||||
from sqlalchemy import text as sa_text
|
||||
|
||||
from app.core.permission_registry import get_permission_registry
|
||||
try:
|
||||
registry = get_permission_registry()
|
||||
if not registry.is_plugin_active("kommunikation"):
|
||||
@@ -533,8 +542,9 @@ async def websocket_endpoint(
|
||||
conv_id = msg.get("conversation_id")
|
||||
if conv_id:
|
||||
# P1.9 fix: Check if user is a participant of this conversation
|
||||
from app.core.db import async_session_maker
|
||||
from sqlalchemy import text as sql_text
|
||||
|
||||
from app.core.db import async_session_maker
|
||||
try:
|
||||
async with async_session_maker() as db:
|
||||
await db.execute(sql_text("SELECT set_config('app.current_tenant_id', :tid, true)"), {"tid": tenant_id})
|
||||
|
||||
@@ -2,13 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# ─── Conversation Schemas ───
|
||||
|
||||
class ParticipantResponse(BaseModel):
|
||||
|
||||
@@ -6,7 +6,8 @@ import logging
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, func, or_, text as sql_text
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import text as sql_text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.plugins.builtins.kommunikation.models import (
|
||||
@@ -15,6 +16,7 @@ from app.plugins.builtins.kommunikation.models import (
|
||||
CommParticipant,
|
||||
)
|
||||
from app.plugins.builtins.unified_search.contracts import get_contract as get_search_contract
|
||||
|
||||
_search = get_search_contract()
|
||||
generate_embedding = _search.generate_embedding
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, update, func, and_, or_
|
||||
from sqlalchemy import and_, func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.event_bus import get_event_bus
|
||||
@@ -20,8 +20,8 @@ from app.plugins.builtins.kommunikation.models import (
|
||||
CommMessageAttachment,
|
||||
CommMessageBlock,
|
||||
CommMessageEdit,
|
||||
CommMessageRead,
|
||||
CommMessageReaction,
|
||||
CommMessageRead,
|
||||
CommParticipant,
|
||||
)
|
||||
from app.plugins.builtins.kommunikation.participant_registry import get_participant_registry
|
||||
@@ -518,7 +518,7 @@ async def remove_participant(
|
||||
p = result.scalar_one_or_none()
|
||||
if p is None:
|
||||
return False
|
||||
p.left_at = datetime.now(timezone.utc)
|
||||
p.left_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
|
||||
event_bus = get_event_bus()
|
||||
@@ -711,7 +711,7 @@ async def send_message(
|
||||
update(CommConversation)
|
||||
.where(CommConversation.id == conversation_id)
|
||||
.values(
|
||||
last_msg_at=datetime.now(timezone.utc),
|
||||
last_msg_at=datetime.now(UTC),
|
||||
last_msg_preview=content[:200] if content else "",
|
||||
last_msg_sender_type=sender_type,
|
||||
)
|
||||
@@ -883,7 +883,7 @@ async def edit_message(
|
||||
|
||||
# Update message
|
||||
msg.content = new_content
|
||||
msg.edited_at = datetime.now(timezone.utc)
|
||||
msg.edited_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
await do_action("comm.after_edit", message_id=message_id, tenant_id=tenant_id, user_id=user_id)
|
||||
|
||||
@@ -903,7 +903,7 @@ async def delete_message(
|
||||
return False
|
||||
from app.core.hooks import do_action
|
||||
await do_action("comm.before_delete", message_id=message_id)
|
||||
msg.deleted_at = datetime.now(timezone.utc)
|
||||
msg.deleted_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
await do_action("comm.after_delete", message_id=message_id)
|
||||
return True
|
||||
@@ -1007,7 +1007,7 @@ async def mark_read(
|
||||
db.add(read)
|
||||
else:
|
||||
read.last_read_msg_id = msg_id
|
||||
read.last_read_at = datetime.now(timezone.utc)
|
||||
read.last_read_at = datetime.now(UTC)
|
||||
|
||||
await db.flush()
|
||||
return True
|
||||
@@ -1064,7 +1064,7 @@ async def create_plugin_room(
|
||||
select(CommConversation).where(
|
||||
CommConversation.tenant_id == tenant_id,
|
||||
CommConversation.title == title,
|
||||
CommConversation.is_locked == True,
|
||||
CommConversation.is_locked.is_(True),
|
||||
CommConversation.locked_by == plugin_name,
|
||||
CommConversation.deleted_at.is_(None),
|
||||
).join(CommParticipant, CommParticipant.conversation_id == CommConversation.id).where(
|
||||
@@ -1313,13 +1313,13 @@ async def post_system_message(
|
||||
await db.flush()
|
||||
|
||||
# Update conversation last_msg
|
||||
from datetime import datetime, timezone as dt_timezone
|
||||
from datetime import datetime
|
||||
|
||||
await db.execute(
|
||||
update(CommConversation)
|
||||
.where(CommConversation.id == conv.id)
|
||||
.values(
|
||||
last_msg_at=datetime.now(dt_timezone.utc),
|
||||
last_msg_at=datetime.now(UTC),
|
||||
last_msg_preview=content[:200],
|
||||
last_msg_sender_type="system",
|
||||
)
|
||||
|
||||
@@ -8,6 +8,7 @@ import uuid
|
||||
from typing import Any
|
||||
|
||||
from fastapi import WebSocket
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.ws_helpers import (
|
||||
authenticate_ws,
|
||||
@@ -21,7 +22,6 @@ from app.core.ws_pubsub import (
|
||||
get_tenant_channel,
|
||||
subscribe_to_channel,
|
||||
)
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -106,7 +106,7 @@ class WebSocketManager:
|
||||
|
||||
# Remove from subscriptions if no more connections
|
||||
if user_id not in self._connections:
|
||||
for conv_id, users in self._subscriptions.items():
|
||||
for _conv_id, users in self._subscriptions.items():
|
||||
users.discard(user_id)
|
||||
|
||||
logger.debug(f"WebSocket disconnected: user={user_id}")
|
||||
|
||||
Reference in New Issue
Block a user