Spaces:
Paused

File size: 8,745 Bytes
5eb4857
 
 
 
 
 
 
 
25925c2
5eb4857
 
 
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
428a35c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
e9e4f03
5eb4857
 
b7980f7
 
5eb4857
 
 
 
 
b7980f7
5eb4857
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
e9e4f03
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
25925c2
5eb4857
 
25925c2
 
 
 
 
5eb4857
 
25925c2
ad4fe35
5eb4857
 
ad4fe35
5eb4857
 
 
 
 
 
 
 
 
ad4fe35
5eb4857
 
 
ad4fe35
558f1c4
 
ad4fe35
 
 
 
e9e4f03
5eb4857
 
 
 
 
 
ce8fa6c
 
 
 
 
 
 
 
5eb4857
ce8fa6c
5eb4857
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
e8ff64c
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
9357dea
 
 
5eb4857
 
e8ff64c
5eb4857
 
9357dea
5eb4857
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""
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)
        # 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

@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)
        # 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()

@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
    # 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
    )

@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)
        .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"}