Files
leocrm/app/routes/delegations.py
T
Agent Zero 7fbbe420bd
Check Cross-Plugin Imports / check (push) Has been cancelled
fix: comprehensive system audit fixes (55+ issues)
CRITICAL:
- Fix SQL injection in prestart.sh (parameterized query)
- Fix secret key validation (always validate, not just production)
- Fix workspace model partial index bug (func.text -> text)
- Fix HealthResponse schema (add checks field)
- Fix Tenant import in permissions.py (NameError on every auth request)
- Fix README tech stack (React instead of Alpine.js)
- Delete broken test_cross_tenant_security_v2.py
- Add fail-closed RLS migration 0084 (48 tenant tables)

HIGH:
- Add GeneralRateLimitMiddleware for all API routes
- Add file type blocklist for DMS and attachment uploads
- Fix guest auth: Pydantic schema, tenant_slug required, CSRF bypass
- Fix CSRF bypass path matching (in -> endswith)
- Add worker healthcheck in docker-compose.yml
- Add ARQ max_tries=3 for job retries
- Fix 28 bare pass in mail services (-> logger.debug)
- Fix print() -> logger in main.py and ai_assistant
- Fix duplicate email handling (catch IntegrityError -> 409)
- Add session revocation (invalidate_all_user_sessions)
- Add resource limits to all containers
- Fix CORS default (localhost -> production domain)
- Fix SameSite=Lax -> Strict
- Fix Redis password visibility in healthcheck
- Fix npm vulnerabilities (19 -> 9)
- Fix Sidebar OOM (wildcard lucide import -> curated ICON_MAP)

MEDIUM:
- Localize ErrorBoundary to German
- Wire Mail.tsx save/delete filter to API
- Document system_notif plugin (no routes needed)
- Fix datetime.utcnow() -> datetime.now(UTC)
- Pin litellm version (>=1.0,<2.0)
- Move CSRF token from sessionStorage to in-memory
- Fix restore_backup error handling and transaction
- Fix Dms.tsx useEffect cleanup
- Add skip-to-content link for accessibility
- Add selectinload imports to 3 services
- Add .env.example missing variables
- Fix AppShell/TopBar/Sidebar test mocks

NEW TESTS:
- test_guest_auth.py (6 tests)
- test_user_service.py (8 tests)
- test_backup_service.py (5 tests)

NEW SCHEMAS:
- saved_filter, saved_view, user_preference, workspace, entity_policy

Tests: 22/22 PASSED
2026-07-31 00:58:05 +02:00

107 lines
3.5 KiB
Python

"""Permission delegation routes — CRUD API for temporary permission handovers."""
from __future__ import annotations
import uuid
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import get_current_user
from app.schemas.delegation import DelegationCreate, DelegationUpdate
from app.services import delegation_service
router = APIRouter(prefix="/api/v1/delegations", tags=["delegations"])
@router.get("")
async def list_delegations(
direction: str = Query("all", pattern="^(from|to|all)$"),
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""List delegations for the current user."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
items = await delegation_service.list_delegations(db, tenant_id, user_id, direction)
return {"items": items, "total": len(items)}
@router.post("", status_code=status.HTTP_201_CREATED)
async def create_delegation(
body: DelegationCreate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""Create a new permission delegation."""
tenant_id = uuid.UUID(current_user["tenant_id"])
from_user_id = uuid.UUID(current_user["user_id"])
try:
return await delegation_service.create_delegation(
db,
tenant_id,
from_user_id=from_user_id,
to_user_id=uuid.UUID(body.to_user_id),
start_at=body.start_at,
end_at=body.end_at,
scope=body.scope,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.put("/{delegation_id}")
async def update_delegation(
delegation_id: str,
body: DelegationUpdate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""Update an existing delegation."""
tenant_id = uuid.UUID(current_user["tenant_id"])
try:
return await delegation_service.update_delegation(
db,
tenant_id,
delegation_id,
start_at=body.start_at,
end_at=body.end_at,
scope=body.scope,
active=body.active,
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.delete("/{delegation_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_delegation(
delegation_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""Delete a delegation."""
tenant_id = uuid.UUID(current_user["tenant_id"])
try:
await delegation_service.delete_delegation(db, tenant_id, delegation_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.get("/active")
async def check_active_delegation(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""Check if the current user has any active delegations."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
is_active = await delegation_service.is_delegation_active(db, user_id, tenant_id)
active_list = await delegation_service.get_active_delegations(db, user_id, tenant_id)
return {
"is_active": is_active,
"active_delegations": active_list,
"count": len(active_list),
}