""" Attachment endpoints: Upload, Download, and Delete with BOLA protection. """ from datetime import datetime import uuid from typing import List, Any from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File from core.deps import get_db, get_current_user, get_current_user_flexible from core.permissions import ALL_SC_ROLES from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from core.storage import get_storage_provider from fastapi.responses import FileResponse, RedirectResponse from models.user import User, UserRole from models.ticket import Ticket from models.attachment import Attachment from schemas.attachment import AttachmentResponse router = APIRouter() # Local storage for attachments (Hackathon sim) # UPLOAD_DIR = Path("uploads") # UPLOAD_DIR.mkdir(exist_ok=True) @router.post("/upload/", response_model=AttachmentResponse, status_code=status.HTTP_201_CREATED) async def upload_generic_attachment( file: UploadFile = File(...), current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Upload a file without a ticket ID. Used for new ticket creation flows.""" storage = get_storage_provider() content = await file.read() upload_res = await storage.upload(content, file.filename, current_user.workspace_id) new_attachment = Attachment( workspace_id=current_user.workspace_id, uploader_id=current_user.id, filename=file.filename, storage_path=upload_res.path, storage_backend=upload_res.backend, content_type=file.content_type, file_size=len(content) ) db.add(new_attachment) await db.commit() await db.refresh(new_attachment) return new_attachment @router.post("/{ticket_id}/attachments/", response_model=AttachmentResponse, status_code=status.HTTP_201_CREATED) async def upload_attachment( ticket_id: uuid.UUID, file: UploadFile = File(...), current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Upload a file for a specific ticket. Enforces ownership for customers.""" is_staff = current_user.role in ALL_SC_ROLES stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.deleted_at.is_(None) ) if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id) if not is_staff: # Customers can ONLY upload to tickets they created stmt = stmt.where(Ticket.created_by == current_user.id) result = await db.execute(stmt) ticket = result.scalar_one_or_none() if not ticket: raise HTTPException(status_code=404, detail="Ticket not found or access denied") storage = get_storage_provider() content = await file.read() upload_res = await storage.upload(content, file.filename, ticket.workspace_id) new_attachment = Attachment( workspace_id=ticket.workspace_id, # Use ticket's actual workspace ticket_id=ticket_id, uploader_id=current_user.id, filename=file.filename, storage_path=upload_res.path, storage_backend=upload_res.backend, content_type=file.content_type, file_size=len(content) ) db.add(new_attachment) await db.commit() await db.refresh(new_attachment) return new_attachment @router.get("/{ticket_id}/attachments/", response_model=List[AttachmentResponse]) async def list_attachments( ticket_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """List all attachments for a specific ticket. Enforces ownership for customers.""" is_staff = current_user.role in ALL_SC_ROLES # 1. Verify ticket access stmt = select(Ticket).where( Ticket.id == ticket_id, Ticket.deleted_at.is_(None) ) if current_user.role != UserRole.SC_ADMIN: stmt = stmt.where(Ticket.workspace_id == current_user.workspace_id) if not is_staff: # Customers can ONLY list attachments for tickets they created stmt = stmt.where(Ticket.created_by == current_user.id) result = await db.execute(stmt) if not result.scalar_one_or_none(): raise HTTPException(status_code=404, detail="Ticket not found or access denied") # 2. Fetch attachments att_stmt = select(Attachment).where( Attachment.ticket_id == ticket_id, Attachment.deleted_at.is_(None) ).order_by(Attachment.created_at.desc()) att_res = await db.execute(att_stmt) return att_res.scalars().all() @router.get("/attachments/{attachment_id}/download/") async def download_attachment( attachment_id: uuid.UUID, current_user: User = Depends(get_current_user_flexible), db: AsyncSession = Depends(get_db) ) -> Any: """ Download an attachment. ENHANCED AUTH: Supports Header and Query Param tokens (for direct browser links). ADJUSTED BOLA: Allows workspace-wide access for staff and authorized users. """ is_staff = current_user.role in ALL_SC_ROLES # Fetch attachment and join with Ticket to verify workspace context # Use outerjoin to support generic attachments (e.g. uploaded but not yet linked to a ticket) stmt = ( select(Attachment, Ticket) .outerjoin(Ticket, Attachment.ticket_id == Ticket.id) .where( Attachment.id == attachment_id, Attachment.deleted_at.is_(None) ) ) result = await db.execute(stmt) row = result.fetchone() if not row: raise HTTPException(status_code=404, detail="Attachment not found") attachment, ticket = row[0], row[1] # Workspace-wide visibility: Enforce workspace BOLA isolation if current_user.role != UserRole.SC_ADMIN: if attachment.workspace_id != current_user.workspace_id: raise HTTPException(status_code=403, detail="Not authorized to download this attachment (Workspace Mismatch)") # (Optional) Secondary BOLA for customers: ensure they can only see their own tickets/attachments if not is_staff and ticket and ticket.created_by != current_user.id: if ticket.workspace_id != current_user.workspace_id: raise HTTPException(status_code=403, detail="Not authorized to download this attachment") storage = get_storage_provider() if attachment.storage_backend == "s3": url = await storage.get_url(attachment.storage_path) return RedirectResponse(url=url) return FileResponse( path=storage.get_local_path(attachment.storage_path), filename=attachment.filename, media_type=attachment.content_type ) @router.delete("/attachments/{attachment_id}/", status_code=status.HTTP_200_OK) async def delete_attachment( attachment_id: uuid.UUID, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ) -> Any: """Soft Delete an attachment. Enforces ownership check.""" is_staff = current_user.role in ALL_SC_ROLES stmt = ( select(Attachment, Ticket) .join(Ticket, Attachment.ticket_id == Ticket.id) .where( Attachment.id == attachment_id, Attachment.workspace_id == current_user.workspace_id, Attachment.deleted_at.is_(None) ) ) result = await db.execute(stmt) row = result.fetchone() if not row: raise HTTPException(status_code=404, detail="Attachment not found") attachment, ticket = row[0], row[1] # Permission: Sender of the attachment OR Admin OR Owner of the Parent Ticket is_uploader = attachment.uploader_id == current_user.id is_ticket_owner = ticket.created_by == current_user.id if not (is_staff or is_uploader or is_ticket_owner): raise HTTPException(status_code=403, detail="Not authorized to delete this attachment") attachment.deleted_at = datetime.utcnow() attachment.deleted_by_id = current_user.id db.add(attachment) await db.commit() return {"status": "deleted"}