Spaces:
Paused
Paused
Download api/v1/attachments.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 8.75 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/attachments.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/api/v1/attachments.py
-
curl -L -o attachments.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/attachments.py
8.75 kB
| """ | |
| 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) | |
| 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 | |
| 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) | |
| # Workspace-wide access enabled | |
| 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 | |
| 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) | |
| # Workspace-wide access enabled | |
| 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() | |
| 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 | |
| # Platform Admins (Superadmins) bypass workspace checks to allow cross-tenant management | |
| if not current_user.is_platform_admin and 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 | |
| # Workspace-wide access enabled for downloads | |
| storage = get_storage_provider() | |
| if attachment.storage_backend == "s3": | |
| url = await storage.get_url(attachment.storage_path) | |
| return RedirectResponse(url=url) | |
| local_path = storage.get_local_path(attachment.storage_path) | |
| # Proactive check to avoid RuntimeError from Starlette FileResponse if file is missing | |
| import os | |
| if not os.path.exists(local_path): | |
| from core.logging import get_logger | |
| get_logger(__name__).error(f"Integrity Error: Attachment {attachment_id} metadata exists but file {local_path} is missing.") | |
| raise HTTPException(status_code=404, detail="Physical attachment file missing from server storage.") | |
| return FileResponse( | |
| path=local_path, | |
| filename=attachment.filename, | |
| media_type=attachment.content_type | |
| ) | |
| 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) | |
| .outerjoin(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] | |
| from core.logging import get_logger | |
| logger = get_logger(__name__) | |
| # 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 ticket else False | |
| if not (is_staff or is_uploader or is_ticket_owner): | |
| logger.warning(f"PERMISSION DENIED: User {current_user.id} (role={current_user.role}) attempted to delete attachment {attachment_id}. Uploader={attachment.uploader_id}, TicketOwner={ticket.created_by if ticket else 'N/A'}") | |
| 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"} | |