""" WebSocket endpoints for real-time ticket updates. """ import logging from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query from jose import ExpiredSignatureError from uuid import UUID from core.websockets import manager from core.security import decode_access_token from core.token_blocklist import is_token_blocked router = APIRouter() _security_log = logging.getLogger("security") # WS close codes (outside the reserved 1000-1015 range, safe for app use) _WS_CLOSE_TOKEN_EXPIRED = 4001 _WS_CLOSE_POLICY = 4003 async def _authenticate_ws(token: str) -> dict: """ Shared WebSocket auth: decode token, verify type is 'access' or 'ws_ticket', and check the revocation blocklist. Raises ExpiredSignatureError on expiry (caller sends 4001). Raises ValueError on any other auth failure (caller sends 4003). """ payload = decode_access_token(token) if payload.get("type") not in ("access", "ws_ticket"): raise ValueError("Token type not permitted for WebSocket authentication.") jti = payload.get("jti") if jti and await is_token_blocked(jti): raise ValueError("Token has been revoked.") return payload @router.websocket("/ws/{workspace_id}") async def ticket_events( websocket: WebSocket, workspace_id: UUID, token: str = Query(...) ): """ WebSocket endpoint for a specific workspace. Authenticates via token in query string (since WS headers are limited). Close codes: 4001 — token expired → client should refresh then reconnect 4003 — auth rejected → client should redirect to login """ try: payload = await _authenticate_ws(token) user_id = payload.get("sub") token_workspace_id = payload.get("workspace_id") role = payload.get("role", "").lower() # Security Guard: # 1. Super-admins have global clearance. # 2. All other users (Customer OR Staff) must have their token scoped to the requested workspace. is_super = role == "superadmin" or payload.get("is_platform_admin") if not is_super and str(token_workspace_id) != str(workspace_id): _security_log.warning(f"WS REJECTED: User {user_id} ({role}) tried to connect to workspace {workspace_id} with token for {token_workspace_id}") await websocket.close(code=_WS_CLOSE_POLICY) return except ExpiredSignatureError: _security_log.warning("WS AUTH FAILURE: token expired — client should call /auth/ws-ticket/ and reconnect") await websocket.close(code=_WS_CLOSE_TOKEN_EXPIRED) return except Exception as e: _security_log.error(f"WS AUTH FAILURE: {str(e)}") await websocket.close(code=_WS_CLOSE_POLICY) return user_uuid = UUID(user_id) if isinstance(user_id, str) else user_id await manager.connect(websocket, workspace_id, user_uuid, role=role) try: while True: await websocket.receive_text() except WebSocketDisconnect: await manager.disconnect(websocket, workspace_id, user_uuid, role=role) @router.websocket("/ws/tickets/{ticket_id}") async def ticket_thread_events( websocket: WebSocket, ticket_id: UUID, token: str = Query(...) ): """ WebSocket endpoint for a specific ticket thread. Allows real-time message updates within the thread. """ try: await _authenticate_ws(token) except ExpiredSignatureError: await websocket.close(code=_WS_CLOSE_TOKEN_EXPIRED) return except Exception: await websocket.close(code=_WS_CLOSE_POLICY) return await manager.connect_ticket(websocket, ticket_id) try: while True: await websocket.receive_text() except WebSocketDisconnect: await manager.disconnect_ticket(websocket, ticket_id)