Skip to content

Latest commit

 

History

History
137 lines (114 loc) · 5 KB

websocket_403_analysis.md

File metadata and controls

137 lines (114 loc) · 5 KB

WebSocket 403 Rejection Analysis

Error

INFO:     127.0.0.1:50411 - "WebSocket /socket.io/?EIO=4&transport=websocket" 403
INFO:     connection rejected (403 Forbidden)
INFO:     connection closed

Source of Messages

  • "WebSocket ... 403" → from uvicorn/protocols/websockets/websockets_impl.py:289 when ASGI app sends websocket.close
  • "connection rejected (403 Forbidden)" → from websockets/server.py:535 when HTTP 403 response is sent instead of 101 Switching Protocols
  • "connection closed" → websockets library cleanup

Stack

  • Backend: python-socketio 5.16.1, python-engineio 4.13.1, uvicorn 0.42.0, FastAPI 0.135.2, Starlette 1.0.0
  • Frontend: socket.io-client 4.8.1 with transports: ['websocket']
  • WebSocket library: websockets 16.0 (uvicorn uses websockets_impl.py since websockets is installed)

How 403 is Generated

In engineio/async_drivers/asgi.py make_response():

if environ['asgi.scope']['type'] == 'websocket':
    if status.startswith('200 '):
        await environ['asgi.send']({'type': 'websocket.accept', ...})
    else:
        await environ['asgi.send']({'type': 'websocket.close', ...})  # → 403

When engineio sends websocket.close, uvicorn logs it as 403.

Engineio Pre-checks That Could Fail (in handle_request)

  1. CORS (cors_allowed_origins='*' → allowed_origins=None → never fails) ✓
  2. Transport ('websocket' in ['polling', 'websocket']) ✓
  3. EIO version (EIO=4) ✓
  4. WebSocket upgrade → transport == upgrade_header == 'websocket'
    • Requires HTTP_UPGRADE = 'websocket' in environ
    • Comes from Upgrade: websocket header in scope
    • Both websockets_impl.py and wsproto_impl.py include this header ✓

All Checks Should Pass — So Why 403?

Why Error Messages Are Hidden

logger=False, engineio_logger=False sets loggers to ERROR level. _log_error_once() logs at ERROR the first time, then INFO for subsequent occurrences. The user sees repeated 403s — the first occurrence error has already been logged (possibly before they started capturing), subsequent ones are INFO (suppressed by ERROR-level logger).

Most Likely Root Cause

Running app instead of socket_app:

  • If user runs uvicorn hemas_competition_agents.main:app (not socket_app)
  • FastAPI receives WebSocket requests to /socket.io/
  • No WebSocket route matches → Starlette closes WebSocket → uvicorn logs 403
  • This exactly matches the error pattern

Secondary cause: Exception in ASGI app:

  • If run_asgi() raises an unhandled exception, handshake_started_event is never set
  • uvicorn's error handler (run_asgi) may send websocket.close → 403
  • In websockets_impl.py:249: self.logger.exception("Exception in ASGI application\n")
  • This would appear as ERROR in logs — check for this message

Code Issues Found

1. FastAPI CORS Middleware Misconfiguration

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,   # ← INVALID with allow_origins=["*"]
    ...
)

In Starlette 1.0.0, this is handled (sends explicit origin instead of *) but is semantically wrong. Does NOT affect socket.io WebSocket connections (socket.io handles its own CORS).

2. Engineio Logging Suppressed

sio = socketio.AsyncServer(
    logger=False,          # ← hides warning-level errors after first occurrence
    engineio_logger=False, # ← same
    ...
)

3. Frontend WebSocket-Only Transport

const socket = io(WS_URL, {
  transports: ['websocket'],  // ← no polling fallback
  ...
})

This means no retry path if WebSocket fails.

Fix Plan

  1. Verify startup command uses socket_app:

    uvicorn hemas_competition_agents.main:socket_app --host 0.0.0.0 --port 8000 --reload
  2. Enable logging temporarily in websocket_manager.py:

    sio = socketio.AsyncServer(
        async_mode="asgi",
        cors_allowed_origins="*",
        logger=True,         # ← for diagnosis
        engineio_logger=True, # ← for diagnosis
        ...
    )
  3. Fix FastAPI CORS — remove allow_credentials=True with wildcard origins.

  4. Add polling fallback in frontend (more robust):

    const socket = io(WS_URL, {
      transports: ['websocket', 'polling'],
      ...
    })

    OR keep WebSocket-only but fix the server-side issue first.

ASGI Call Chain (should work correctly)

uvicorn → socket_app → socketio.ASGIApp
  → (path /socket.io/ matches)
  → engineio.handle_request(scope, receive, send)
    → translate_request → builds environ with all headers
    → all checks pass
    → _handle_connect → creates socket, queues OPEN packet
    → _trigger_event('connect') → socketio._handle_eio_connect → stores environ, returns None
    → s.handle_get_request → _upgrade_websocket → WebSocket.__call__
      → environ['asgi.send']({type: 'websocket.accept'})  ← directly accepts
      → _websocket_handler → writer task + reader loop