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:
Agent Zero
2026-08-16 01:17:18 +02:00
parent 3d9b76cea4
commit abbe7a18fc
306 changed files with 5912 additions and 1827 deletions
@@ -9,14 +9,9 @@ from __future__ import annotations
import json
import logging
import uuid
from typing import Any
import httpx
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
from app.core.db import get_session_factory
logger = logging.getLogger(__name__)
@@ -11,7 +11,7 @@ import logging
import uuid
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import StreamingResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -61,7 +61,7 @@ async def run_agent_external(
try:
aid = uuid.UUID(agent_id)
except (ValueError, TypeError):
raise HTTPException(status_code=400, detail="Invalid agent ID")
raise HTTPException(status_code=400, detail="Invalid agent ID") from None
# Find the agent
from app.plugins.builtins.ai_assistant.models import AIAgent
@@ -79,8 +79,8 @@ async def run_agent_external(
raise HTTPException(status_code=400, detail="Agent is not active")
# Create or find a session for this external interaction
from app.plugins.builtins.ai_assistant.models import AIChatSession, AIChatMessage
from datetime import datetime, timezone
from app.plugins.builtins.ai_assistant.models import AIChatMessage, AIChatSession
session = AIChatSession(
user_id=uuid.UUID(current_user["user_id"]),
@@ -168,7 +168,7 @@ async def get_agent_status_external(
try:
aid = uuid.UUID(agent_id)
except (ValueError, TypeError):
raise HTTPException(status_code=400, detail="Invalid agent ID")
raise HTTPException(status_code=400, detail="Invalid agent ID") from None
from app.plugins.builtins.ai_assistant.models import AIAgent
@@ -183,9 +183,10 @@ async def get_agent_status_external(
raise HTTPException(status_code=404, detail="Agent not found")
# Get recent run stats
from app.plugins.builtins.automation.contracts import AutomationContract
from sqlalchemy import func
from app.plugins.builtins.automation.contracts import AutomationContract
recent_runs = await db.execute(
select(func.count())
.select_from(AutomationContract.AgentRun)
@@ -232,7 +233,7 @@ async def stream_agent_external(
try:
aid = uuid.UUID(agent_id)
except (ValueError, TypeError):
raise HTTPException(status_code=400, detail="Invalid agent ID")
raise HTTPException(status_code=400, detail="Invalid agent ID") from None
from app.plugins.builtins.ai_assistant.models import AIAgent
+2 -4
View File
@@ -3,11 +3,9 @@
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
Boolean,
DateTime,
Float,
ForeignKey,
Index,
@@ -15,13 +13,13 @@ from sqlalchemy import (
String,
Text,
)
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
from app.models.owned_mixin import OwnedMixin
# --- Providers ---
class AIProvider(Base, TenantMixin):
+11 -1
View File
@@ -6,7 +6,13 @@ import logging
from typing import Any
from app.plugins.base import BasePlugin
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendSettingsPage
from app.plugins.manifest import (
FrontendMenuItem,
FrontendPageRoute,
FrontendSettingsPage,
PluginManifest,
PluginRouteDef,
)
logger = logging.getLogger(__name__)
@@ -71,6 +77,10 @@ class AIAssistantPlugin(BasePlugin):
await seed_defaults(db)
def get_entity_models(self) -> dict[str, type]:
from app.plugins.builtins.ai_assistant.models import AIAgent, AIChatSession
return {"ai_agent": AIAgent, "ai_chat_session": AIChatSession}
async def on_activate(self, db, service_container, event_bus) -> None:
"""Activate plugin: register CRM API tool and participant handler."""
await super().on_activate(db, service_container, event_bus)
+4 -6
View File
@@ -33,10 +33,8 @@ from app.plugins.builtins.ai_assistant.schemas import (
AIPresetUpdate,
AIProviderCreate,
AIProviderUpdate,
ChatAttachmentResponse,
ChatFolderCreate,
ChatFolderUpdate,
ChatFolderResponse,
ChatSendRequest,
ChatSessionCreate,
ChatSessionUpdate,
@@ -92,7 +90,7 @@ async def create_provider(
existing = await db.execute(
select(AIProvider)
.where(AIProvider.tenant_id == tenant_id)
.where(AIProvider.is_default == True)
.where(AIProvider.is_default.is_(True))
)
for p in existing.scalars().all():
p.is_default = False
@@ -129,7 +127,7 @@ async def update_provider(
existing = await db.execute(
select(AIProvider)
.where(AIProvider.tenant_id == tenant_id)
.where(AIProvider.is_default == True)
.where(AIProvider.is_default.is_(True))
.where(AIProvider.id != provider.id)
)
for p in existing.scalars().all():
@@ -717,8 +715,8 @@ async def delete_folder(
# ─── Attachments ───
import os
from pathlib import Path
import os # noqa: E402
from pathlib import Path # noqa: E402
ATTACHMENT_DIR = Path(os.environ.get("STORAGE_PATH", "/data/storage")) / "ai_attachments"
MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024 # 25MB
@@ -7,7 +7,6 @@ from typing import Any
from pydantic import BaseModel, ConfigDict, Field
# ─── Providers ───
class AIProviderCreate(BaseModel):
@@ -10,16 +10,15 @@ from __future__ import annotations
import json
import logging
import uuid
from typing import Any, AsyncGenerator
from collections.abc import AsyncGenerator
from typing import Any
import aiofiles
import litellm
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.ai.llm_client import llm_complete
from app.core.permissions import check_permission
from app.plugins.builtins.ai_assistant.models import (
AIAgent,
@@ -169,7 +168,7 @@ async def get_default_provider(db: AsyncSession, tenant_id: uuid.UUID) -> AIProv
result = await db.execute(
select(AIProvider)
.where(AIProvider.tenant_id == tenant_id)
.where(AIProvider.is_default == True)
.where(AIProvider.is_default.is_(True))
.limit(1)
)
return result.scalar_one_or_none()
@@ -209,7 +208,7 @@ async def get_default_agent(db: AsyncSession, tenant_id: uuid.UUID) -> AIAgent |
result = await db.execute(
select(AIAgent)
.where(AIAgent.tenant_id == tenant_id)
.where(AIAgent.is_default == True)
.where(AIAgent.is_default.is_(True))
.limit(1)
)
return result.scalar_one_or_none()
@@ -394,8 +393,9 @@ async def _extract_attachment_content(
text_content = content.decode("utf-8", errors="replace")
elif mime == "application/pdf" or att.filename.endswith(".pdf"):
try:
from pypdf import PdfReader
from io import BytesIO
from pypdf import PdfReader
reader = PdfReader(BytesIO(content))
text_content = "\n".join(page.extract_text() or "" for page in reader.pages)
except ImportError:
@@ -8,8 +8,8 @@ and an async handler. Tools can optionally require specific RBAC permissions.
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable, Protocol
from dataclasses import dataclass
from typing import Any, Protocol
logger = logging.getLogger(__name__)