diff --git a/app/main.py b/app/main.py index c6583f8..33c5e27 100644 --- a/app/main.py +++ b/app/main.py @@ -61,6 +61,7 @@ from app.routes import ( saved_views, webhooks, backups, + owner_transfer, ) @@ -396,6 +397,7 @@ def create_app() -> FastAPI: app.include_router(bank_accounts.router) app.include_router(audit.router) app.include_router(backups.router) + app.include_router(owner_transfer.router) app.include_router(custom_field_definitions.router) app.include_router(custom_fields.router) app.include_router(saved_filters.router) diff --git a/app/models/auth.py b/app/models/auth.py index 8e34822..39cf3e4 100644 --- a/app/models/auth.py +++ b/app/models/auth.py @@ -43,7 +43,7 @@ class ApiToken(Base, TenantMixin): ) token_hash: Mapped[str] = mapped_column(String(255), nullable=False, index=True) name: Mapped[str] = mapped_column(String(200), nullable=False) - scopes: Mapped[list] = mapped_column(JSONB, nullable=False) + scopes: Mapped[list[str]] = mapped_column(JSONB, nullable=False, default=list) expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) created_at: Mapped[datetime] = mapped_column( diff --git a/app/routes/contacts.py b/app/routes/contacts.py index 56866fc..3571703 100644 --- a/app/routes/contacts.py +++ b/app/routes/contacts.py @@ -23,6 +23,7 @@ from app.commands.contact_commands import ( MergeContactsCommand, ) from app.core.db import get_db +from app.core.visibility import check_single_entity_access from app.deps import get_current_user, get_redis_dep, require_permission from app.schemas.contact import ( ContactCreate, @@ -276,6 +277,31 @@ async def merge_duplicate_contacts( current_user: dict = Depends(require_permission("contacts:write")), ): """Merge two contacts (source → target) via MergeContactsCommand.""" + tenant_id = uuid.UUID(current_user["tenant_id"]) + user_id = uuid.UUID(current_user["user_id"]) + is_admin = current_user.get("is_system_admin", False) + + # Check write access on both contacts + try: + source_uuid = uuid.UUID(body.source_contact_id) + target_uuid = uuid.UUID(body.target_contact_id) + except (ValueError, TypeError): + raise HTTPException(status_code=400, detail="Invalid contact ID") + + source_access = await check_single_entity_access( + db, "contact", source_uuid, user_id, tenant_id, + required_level="write", is_system_admin=is_admin, + ) + if not source_access: + raise HTTPException(status_code=403, detail="No write access to source contact") + + target_access = await check_single_entity_access( + db, "contact", target_uuid, user_id, tenant_id, + required_level="write", is_system_admin=is_admin, + ) + if not target_access: + raise HTTPException(status_code=403, detail="No write access to target contact") + cmd = MergeContactsCommand( source_contact_id=body.source_contact_id, target_contact_id=body.target_contact_id, diff --git a/app/routes/owner_transfer.py b/app/routes/owner_transfer.py new file mode 100644 index 0000000..a227179 --- /dev/null +++ b/app/routes/owner_transfer.py @@ -0,0 +1,58 @@ +"""Owner transfer routes — admin-only bulk ownership transfer.""" + +from __future__ import annotations + +import uuid +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.db import get_db +from app.deps import require_admin +from app.services.owner_transfer_service import transfer_ownership + +router = APIRouter(prefix="/api/v1/ownership", tags=["ownership"]) + + +class TransferRequest(BaseModel): + from_user_id: str + to_user_id: str + entity_types: list[str] | None = None + + +@router.post("/transfer") +async def transfer_ownership_endpoint( + body: TransferRequest, + db: AsyncSession = Depends(get_db), + current_user: dict[str, Any] = Depends(require_admin), +): + """Bulk-transfer all records from one user to another. + + Admin-only endpoint. If entity_types is None, all known entity types + are transferred. + """ + try: + from_uid = uuid.UUID(body.from_user_id) + to_uid = uuid.UUID(body.to_user_id) + except ValueError: + raise HTTPException( + 400, + detail={"detail": "Invalid user_id format", "code": "invalid_id"}, + ) + + tenant_id = uuid.UUID(current_user["tenant_id"]) + + results = await transfer_ownership( + db, + tenant_id, + from_uid, + to_uid, + body.entity_types, + ) + + return { + "message": "Ownership transfer completed", + "results": results, + } diff --git a/app/routes/users.py b/app/routes/users.py index 870901e..2e75ee2 100644 --- a/app/routes/users.py +++ b/app/routes/users.py @@ -18,6 +18,7 @@ from app.deps import get_current_user, require_permission from app.models.user import User, UserTenant from app.schemas.user import UserCreate, UserUpdate, UserResponse, PaginatedUsers from app.services.user_service import user_service, _UNSET +from app.services.owner_transfer_service import transfer_ownership router = APIRouter(prefix="/api/v1/users", tags=["users"]) @@ -235,6 +236,16 @@ async def update_user( raise HTTPException(404, detail={"detail": "User not found", "code": "not_found"}) user, user_tenant = result + + # Auto-transfer ownership when user is deactivated + if body.is_active is False: + await transfer_ownership( + db, + tenant_id, + from_user_id=uid, + to_user_id=acting_user_id, + ) + await log_audit(db, tenant_id, acting_user_id, "update", "user", uid, changes=changes) # Invalidate permission cache for the updated user diff --git a/app/services/ai_copilot_service.py b/app/services/ai_copilot_service.py index 1caffef..9932998 100644 --- a/app/services/ai_copilot_service.py +++ b/app/services/ai_copilot_service.py @@ -12,6 +12,8 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.ai.llm_client import get_llm_client from app.core.audit import log_audit from app.core.auth import check_permission +from app.core.visibility import apply_visibility_filter +from app.core.visibility import check_single_entity_access from app.models.ai_conversation import AIConversation, AIMessage from app.models.contact import Contact from app.models.contact import Contact @@ -64,6 +66,7 @@ async def process_query( query: str, conversation_id: str | None = None, context: dict[str, Any] | None = None, + is_system_admin: bool = False, ) -> dict[str, Any]: """Process a natural language query and return proposed actions. @@ -159,6 +162,7 @@ async def execute_action( role: str, conversation_id: str, action: dict[str, Any], + is_system_admin: bool = False, ) -> dict[str, Any]: """Execute a proposed action with RBAC enforcement. @@ -195,9 +199,31 @@ async def execute_action( "success": False, } + # Check single entity access for write operations + if method in ("POST", "PATCH", "DELETE"): + parts = path.replace("/api/v1/", "").strip("/").split("/") + entity_type = parts[0] if parts else "" + entity_id = parts[1] if len(parts) > 1 else None + if entity_id: + try: + entity_uuid = uuid.UUID(entity_id) + except (ValueError, TypeError): + entity_uuid = None + if entity_uuid: + has_access = await check_single_entity_access( + db, entity_type, entity_uuid, user_id, tenant_id, + required_level="write", is_system_admin=is_system_admin, + ) + if not has_access: + return { + "error": "Insufficient access to this entity", + "status_code": 403, + "success": False, + } + # Execute the action try: - exec_result = await _execute_api_action(db, tenant_id, user_id, method, path, body) + exec_result = await _execute_api_action(db, tenant_id, user_id, method, path, body, is_system_admin=is_system_admin) except Exception as exc: exec_result = {"error": str(exc), "status_code": 500} @@ -303,6 +329,7 @@ async def _execute_api_action( method: str, path: str, body: dict[str, Any], + is_system_admin: bool = False, ) -> dict[str, Any]: """Execute an API action directly against the database. @@ -314,9 +341,9 @@ async def _execute_api_action( entity_id = parts[1] if len(parts) > 1 else None if entity in ("companies", "contacts"): - return await _exec_contacts(db, tenant_id, user_id, method, entity_id, body) + return await _exec_contacts(db, tenant_id, user_id, method, entity_id, body, is_system_admin=is_system_admin) elif entity == "workflows": - return await _exec_workflows(db, tenant_id, user_id, method, entity_id, body) + return await _exec_workflows(db, tenant_id, user_id, method, entity_id, body, is_system_admin=is_system_admin) else: return {"error": f"Unsupported entity: {entity}", "status_code": 400, "success": False} @@ -328,15 +355,18 @@ async def _exec_contacts( method: str, entity_id: str | None, body: dict[str, Any], + is_system_admin: bool = False, ) -> dict[str, Any]: """Execute contact operations (unified: company + person).""" if method == "GET": - result = await db.execute( - select(Contact).where( - Contact.tenant_id == tenant_id, - Contact.deleted_at.is_(None), - ) + query = select(Contact).where( + Contact.tenant_id == tenant_id, + Contact.deleted_at.is_(None), ) + query = await apply_visibility_filter( + db, query, "contact", Contact, user_id, tenant_id, is_system_admin=is_system_admin + ) + result = await db.execute(query) contacts = result.scalars().all() return { "success": True, @@ -372,6 +402,7 @@ async def _exec_workflows( method: str, entity_id: str | None, body: dict[str, Any], + is_system_admin: bool = False, ) -> dict[str, Any]: """Execute workflow operations.""" if method == "GET": diff --git a/app/services/owner_transfer_service.py b/app/services/owner_transfer_service.py new file mode 100644 index 0000000..57b554a --- /dev/null +++ b/app/services/owner_transfer_service.py @@ -0,0 +1,97 @@ +"""Service for bulk-transferring ownership of records between users.""" + +from __future__ import annotations + +import logging +import uuid +from typing import Any + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.audit import log_audit + +logger = logging.getLogger(__name__) + +# Mapping of entity_type -> database table name +ENTITY_TABLES: dict[str, str] = { + "contacts": "contacts", + "addresses": "addresses", + "attachments": "attachments", + "bank_accounts": "bank_accounts", + "workflows": "workflows", + "sequences": "sequences", + "saved_filters": "saved_filters", + "saved_views": "saved_views", + "webhooks": "webhooks", + "notifications": "notifications", + "ai_conversations": "ai_conversations", +} + + +async def transfer_ownership( + db: AsyncSession, + tenant_id: uuid.UUID, + from_user_id: uuid.UUID, + to_user_id: uuid.UUID, + entity_types: list[str] | None = None, +) -> dict[str, int]: + """Bulk-transfer all records from one user to another for the given entity types. + + Args: + db: Database session. + tenant_id: Tenant scope. + from_user_id: Current owner whose records will be transferred. + to_user_id: New owner for the records. + entity_types: List of entity types to transfer. If None, all known types. + + Returns: + Dict mapping entity_type -> number of records transferred. + """ + if entity_types is None: + entity_types = list(ENTITY_TABLES.keys()) + + results: dict[str, int] = {} + + for entity_type in entity_types: + table = ENTITY_TABLES.get(entity_type) + if table is None: + logger.warning("Unknown entity_type=%s, skipping", entity_type) + continue + + # Build and execute the UPDATE + stmt = text( + f"UPDATE {table} SET owner_id = :to_user_id " + f"WHERE owner_id = :from_user_id AND tenant_id = :tenant_id" + ) + stmt = stmt.bindparams( + to_user_id=str(to_user_id), + from_user_id=str(from_user_id), + tenant_id=str(tenant_id), + ) + result = await db.execute(stmt) + count = result.rowcount + results[entity_type] = count if count is not None else 0 + + if count and count > 0: + logger.info( + "Transferred %d %s from user %s to user %s (tenant %s)", + count, entity_type, from_user_id, to_user_id, tenant_id, + ) + + # Log the transfer in audit log + await log_audit( + db, + tenant_id, + to_user_id, + "transfer_ownership", + "ownership", + changes={ + "from_user_id": str(from_user_id), + "to_user_id": str(to_user_id), + "entity_types": entity_types, + "results": results, + }, + ) + + return results