websocket.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. """GHSA-r2qv follow-up — WebSocket auth gate.
  2. Previously ``/api/v1/ws`` accepted *any* network client and immediately
  3. streamed every ``printer_status`` / ``print_start`` / ``print_complete``
  4. / ``archive_*`` / ``inventory_changed`` broadcast back to it. That is
  5. the GHSA-gc24 shape on a different protocol — anyone who could reach
  6. the HTTP port could subscribe to every printer event in the system.
  7. This endpoint now validates a short-lived token (minted by
  8. ``POST /api/v1/auth/ws-token`` behind ``Permission.WEBSOCKET_CONNECT``)
  9. *before* ``websocket.accept()``. When auth is disabled, no token is
  10. required (the legacy SPA-friendly path). The token is reused across
  11. reconnects within its 60-minute window so a brief network blip does
  12. not require a round-trip to the auth router.
  13. """
  14. from __future__ import annotations
  15. import logging
  16. from fastapi import APIRouter, Query, WebSocket, WebSocketDisconnect
  17. from sqlalchemy import select
  18. from backend.app.core.auth import is_auth_enabled, verify_websocket_token
  19. from backend.app.core.database import async_session
  20. from backend.app.core.websocket import ws_manager
  21. from backend.app.models.user import User
  22. from backend.app.services.printer_manager import printer_manager, printer_state_to_dict
  23. logger = logging.getLogger(__name__)
  24. router = APIRouter()
  25. # 4401 mirrors the WebSocket "unauthorised" application close code
  26. # convention used by Sec-WebSocket-Protocol authors (private-use range
  27. # is 4000-4999 per RFC 6455). The SPA distinguishes 4401 from network
  28. # drops and refetches a token instead of retrying with the old one.
  29. _WS_CLOSE_UNAUTHORIZED = 4401
  30. @router.websocket("/ws")
  31. async def websocket_endpoint(websocket: WebSocket, token: str | None = Query(default=None)) -> None:
  32. """WebSocket endpoint for real-time updates.
  33. Connection auth (GHSA-r2qv follow-up):
  34. - Auth disabled → connect without a token, identical to the prior
  35. behaviour (single-user / local-network deployments).
  36. - Auth enabled → ``?token=<value>`` query param must hold an
  37. unexpired token minted via ``POST /api/v1/auth/ws-token``.
  38. Missing / invalid / expired token → ``close(code=4401)`` *before*
  39. ``accept()`` so no ``ws_manager.broadcast`` ever reaches the
  40. caller (broadcasts walk ``active_connections`` blindly — letting
  41. an unauthenticated socket into that list is a fan-out leak).
  42. The auth check is fail-closed at every error path: a DB exception
  43. while reading the ``auth_enabled`` setting closes the connection
  44. rather than admitting the caller.
  45. """
  46. # Authenticate before accept() so an unauth caller never lands in
  47. # ws_manager.active_connections (where broadcasts blindly fan out).
  48. try:
  49. async with async_session() as db:
  50. auth_required = await is_auth_enabled(db)
  51. except Exception: # SEC-AUTH-EXC: DB failure on auth probe → fail-closed (refuse connect), matches is_auth_enabled itself which returns True on error
  52. logger.error("WebSocket auth probe failed; refusing connection", exc_info=True)
  53. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  54. return
  55. principal: str | None = None
  56. if auth_required:
  57. if not token:
  58. logger.info("WebSocket connect refused: no token (auth enabled)")
  59. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  60. return
  61. principal = await verify_websocket_token(token)
  62. if principal is None:
  63. logger.info("WebSocket connect refused: invalid or expired token")
  64. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  65. return
  66. # Token verified (or auth disabled); now safe to admit the connection.
  67. logger.info("WebSocket client connecting (principal=%s)", principal if principal else "<anonymous>")
  68. await ws_manager.connect(websocket)
  69. # Stash on connection state for any future per-message permission
  70. # logic; today the message handlers are read-only and only respond
  71. # to the requesting socket, so the stash is informational. The
  72. # explicit attribute (rather than a side dict) means a future
  73. # ``broadcast_to_principal()`` helper can filter on it without
  74. # touching every call site.
  75. websocket.state.bambuddy_principal = principal
  76. # Resolve principal username → User.id once at connect so
  77. # ``ws_manager.broadcast_to_user()`` can filter without re-querying
  78. # per message. Auth-disabled path keeps None (broadcast_to_user fans
  79. # out to all when target is None — matches the legacy single-user
  80. # toast behaviour). API-keyed principal is empty string → None.
  81. principal_user_id: int | None = None
  82. if principal:
  83. try:
  84. async with async_session() as db:
  85. row = await db.execute(select(User.id).where(User.username == principal))
  86. principal_user_id = row.scalar_one_or_none()
  87. except Exception: # SEC-AUTH-EXC: resolution failure is non-fatal — degrades to no per-user routing
  88. logger.warning("WebSocket principal resolve failed for %s", principal, exc_info=True)
  89. websocket.state.bambuddy_principal_user_id = principal_user_id
  90. logger.info("WebSocket client connected")
  91. try:
  92. # Send initial status of all printers.
  93. statuses = printer_manager.get_all_statuses()
  94. for printer_id, state in statuses.items():
  95. await websocket.send_json(
  96. {
  97. "type": "printer_status",
  98. "printer_id": printer_id,
  99. "data": printer_state_to_dict(
  100. state,
  101. printer_id,
  102. printer_manager.get_model(printer_id),
  103. printer_manager.get_drying_targets(printer_id),
  104. ),
  105. }
  106. )
  107. logger.info("Sent initial status for %s printers", len(statuses))
  108. # Keep connection alive and handle incoming messages.
  109. while True:
  110. data = await websocket.receive_json()
  111. # Handle ping/pong for keepalive
  112. if data.get("type") == "ping":
  113. await websocket.send_json({"type": "pong"})
  114. # Handle status request
  115. elif data.get("type") == "get_status":
  116. printer_id = data.get("printer_id")
  117. if printer_id:
  118. state = printer_manager.get_status(printer_id)
  119. if state:
  120. await websocket.send_json(
  121. {
  122. "type": "printer_status",
  123. "printer_id": printer_id,
  124. "data": printer_state_to_dict(
  125. state,
  126. printer_id,
  127. printer_manager.get_model(printer_id),
  128. printer_manager.get_drying_targets(printer_id),
  129. ),
  130. }
  131. )
  132. except WebSocketDisconnect:
  133. logger.info("WebSocket client disconnected normally")
  134. await ws_manager.disconnect(websocket)
  135. except Exception as e:
  136. logger.error("WebSocket error: %s", e, exc_info=True)
  137. await ws_manager.disconnect(websocket)