Spaces:
Paused

File size: 3,865 Bytes
5eb4857
 
 
 
0243ced
4405ca9
0243ced
5eb4857
 
 
dbc31e7
5eb4857
 
0243ced
 
 
 
 
5eb4857
dbc31e7
 
 
0243ced
 
 
 
dbc31e7
 
0243ced
 
dbc31e7
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
0243ced
 
 
 
5eb4857
 
dbc31e7
5eb4857
 
c4abe06
dbc31e7
9377380
 
 
 
 
 
 
0243ced
5eb4857
0243ced
 
 
 
7b3791b
0243ced
 
5eb4857
 
e440c64
 
5eb4857
 
dbc31e7
5eb4857
a556997
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
dbc31e7
0243ced
 
 
5eb4857
0243ced
5eb4857
 
 
 
 
 
 
a556997
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
"""
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)