Security fixes: P0-P2 complete (22 fixes)

P0 (7): Auth-bypass removed, migrations fixed, plugin-upload disabled, RLS FORCE+WITH CHECK, plugin double-registration fixed, persistent volume, domain removed
P1 (11): User/tenant model, Redis centralized, worker separated, transactional outbox, XSS fixed, DMS chunked streaming, permissions unified, password reset, metrics secured, config/docs fixed, cross-tenant FK
P2 (4): Contact model normalized, cross-imports reduced 94%, commands+state machines for contacts/dms/mail/calendar, SPA path-traversal

8 new migrations, 99 unit tests, 13 commands, 8 contracts, 72 files changed
This commit is contained in:
Agent Zero
2026-07-25 21:03:46 +02:00
parent aaa7406929
commit 727d86614e
103 changed files with 6831 additions and 1053 deletions
+51 -37
View File
@@ -1,8 +1,11 @@
"""Unified contact routes — CRUD, contactpersons, FTS search, export, soft-delete."""
"""Unified contact routes — CRUD, contactpersons, FTS search, export, soft-delete.
Write operations (create, update, delete, merge) are delegated to Commands.
Read operations (list, get, export, contact persons) use services directly.
"""
from __future__ import annotations
import csv
import io
import uuid
from typing import Any
@@ -11,8 +14,16 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
import redis.asyncio as aioredis
from app.commands.contact_commands import (
CreateContactCommand,
UpdateContactCommand,
DeleteContactCommand,
MergeContactsCommand,
)
from app.core.db import get_db
from app.deps import require_permission
from app.deps import get_current_user, get_redis_dep, require_permission
from app.schemas.contact import (
ContactCreate,
ContactUpdate,
@@ -89,13 +100,16 @@ async def export_contacts(
async def create_contact(
body: ContactCreate,
db: AsyncSession = Depends(get_db),
redis: aioredis.Redis = Depends(get_redis_dep),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Create a new contact (company or person)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
"""Create a new contact (company or person) via CreateContactCommand."""
data = body.model_dump(exclude_none=True)
return await contact_service.create_contact(db, tenant_id, user_id, data)
cmd = CreateContactCommand(data=data)
result = await cmd.execute(db, redis, current_user)
if not result.success:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=result.error)
return result.data
@router.get("/merge-history")
@@ -129,16 +143,20 @@ async def update_contact(
contact_id: str,
body: ContactUpdate,
db: AsyncSession = Depends(get_db),
redis: aioredis.Redis = Depends(get_redis_dep),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Update a contact."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
"""Update a contact via UpdateContactCommand."""
data = body.model_dump(exclude_none=True)
try:
return await contact_service.update_contact(db, tenant_id, user_id, contact_id, data)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
cmd = UpdateContactCommand(contact_id=contact_id, data=data)
result = await cmd.execute(db, redis, current_user)
if not result.success:
if "not found" in (result.error or "").lower():
raise HTTPException(status_code=404, detail=result.error)
if "Invalid state transition" in (result.error or ""):
raise HTTPException(status_code=422, detail=result.error)
raise HTTPException(status_code=400, detail=result.error)
return result.data
@router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT)
@@ -146,18 +164,15 @@ async def delete_contact(
contact_id: str,
hard: bool = Query(False, description="GDPR hard-delete"),
db: AsyncSession = Depends(get_db),
redis: aioredis.Redis = Depends(get_redis_dep),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Soft-delete (or hard-delete with ?hard=true) a contact."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
try:
if hard:
await contact_service.hard_delete_contact(db, tenant_id, contact_id)
else:
await contact_service.delete_contact(db, tenant_id, contact_id, user_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
"""Soft-delete (or hard-delete with ?hard=true) a contact via DeleteContactCommand."""
cmd = DeleteContactCommand(contact_id=contact_id, hard=hard)
result = await cmd.execute(db, redis, current_user)
if not result.success:
raise HTTPException(status_code=404, detail=result.error)
return Response(status_code=status.HTTP_204_NO_CONTENT)
# ── ContactPersons ──
@@ -244,18 +259,17 @@ async def find_duplicate_contacts(
async def merge_duplicate_contacts(
body: MergeRequest,
db: AsyncSession = Depends(get_db),
redis: aioredis.Redis = Depends(get_redis_dep),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Merge two contacts (source → target)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
try:
return await dedup_service.merge_contacts(
db, tenant_id, user_id,
source_id=body.source_contact_id,
target_id=body.target_contact_id,
field_overrides=body.field_overrides,
note=body.note,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
"""Merge two contacts (source → target) via MergeContactsCommand."""
cmd = MergeContactsCommand(
source_contact_id=body.source_contact_id,
target_contact_id=body.target_contact_id,
field_overrides=body.field_overrides,
note=body.note,
)
result = await cmd.execute(db, redis, current_user)
if not result.success:
raise HTTPException(status_code=400, detail=result.error)
return result.data