websocket.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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, principal_printer_scope, verify_websocket_token_principal
  19. from backend.app.core.database import async_session
  20. from backend.app.core.printer_scope import ALL_PRINTERS, PrinterScope
  21. from backend.app.core.websocket import ws_manager
  22. from backend.app.models.user import User
  23. from backend.app.services.printer_manager import printer_manager, printer_state_to_dict
  24. logger = logging.getLogger(__name__)
  25. router = APIRouter()
  26. # 4401 mirrors the WebSocket "unauthorised" application close code
  27. # convention used by Sec-WebSocket-Protocol authors (private-use range
  28. # is 4000-4999 per RFC 6455). The SPA distinguishes 4401 from network
  29. # drops and refetches a token instead of retrying with the old one.
  30. _WS_CLOSE_UNAUTHORIZED = 4401
  31. async def _user_id_of(username: str) -> int | None:
  32. """The id of the user with this name, or None (also when it can't be read)."""
  33. try:
  34. async with async_session() as db:
  35. row = await db.execute(select(User.id).where(User.username == username))
  36. return row.scalar_one_or_none()
  37. except Exception: # SEC-AUTH-EXC: a failed lookup refuses the socket (fail-closed)
  38. logger.warning("WebSocket principal resolve failed for %s", username, exc_info=True)
  39. return None
  40. @router.websocket("/ws")
  41. async def websocket_endpoint(websocket: WebSocket, token: str | None = Query(default=None)) -> None:
  42. """WebSocket endpoint for real-time updates.
  43. Connection auth (GHSA-r2qv follow-up):
  44. - Auth disabled → connect without a token, identical to the prior
  45. behaviour (single-user / local-network deployments).
  46. - Auth enabled → ``?token=<value>`` query param must hold an
  47. unexpired token minted via ``POST /api/v1/auth/ws-token``.
  48. Missing / invalid / expired token → ``close(code=4401)`` *before*
  49. ``accept()`` so no ``ws_manager.broadcast`` ever reaches the
  50. caller (broadcasts walk ``active_connections`` blindly — letting
  51. an unauthenticated socket into that list is a fan-out leak).
  52. The auth check is fail-closed at every error path: a DB exception
  53. while reading the ``auth_enabled`` setting closes the connection
  54. rather than admitting the caller.
  55. """
  56. # Authenticate before accept() so an unauth caller never lands in
  57. # ws_manager.active_connections (where broadcasts blindly fan out).
  58. try:
  59. async with async_session() as db:
  60. auth_required = await is_auth_enabled(db)
  61. except Exception: # SEC-AUTH-EXC: DB failure on auth probe → fail-closed (refuse connect), matches is_auth_enabled itself which returns True on error
  62. logger.error("WebSocket auth probe failed; refusing connection", exc_info=True)
  63. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  64. return
  65. principal: str | None = None
  66. api_key_id: int | None = None
  67. printer_scope: PrinterScope = ALL_PRINTERS
  68. if auth_required:
  69. if not token:
  70. logger.info("WebSocket connect refused: no token (auth enabled)")
  71. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  72. return
  73. token_principal = await verify_websocket_token_principal(token)
  74. if token_principal is None:
  75. logger.info("WebSocket connect refused: invalid or expired token")
  76. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  77. return
  78. principal, api_key_id = token_principal
  79. # Which printers this socket may hear about (#1727). Fail-closed: if
  80. # it can't be worked out the socket is refused rather than admitted
  81. # with every printer.
  82. try:
  83. async with async_session() as db:
  84. printer_scope = await principal_printer_scope(db, principal, api_key_id)
  85. except Exception: # SEC-AUTH-EXC: scope lookup failure → refuse connect (fail-closed)
  86. logger.error("WebSocket printer scope lookup failed; refusing connection", exc_info=True)
  87. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  88. return
  89. # Token verified (or auth disabled); now safe to admit the connection.
  90. logger.info("WebSocket client connecting (principal=%s)", principal if principal else "<anonymous>")
  91. # Resolve principal username → User.id once at connect so
  92. # ``ws_manager.broadcast_to_user()`` can filter without re-querying
  93. # per message. Auth-disabled path keeps None (broadcast_to_user fans
  94. # out to all when target is None — matches the legacy single-user
  95. # toast behaviour). API-keyed principal is empty string → None.
  96. #
  97. # A user renamed or deleted since the token was checked is refused: the
  98. # socket would keep the old name, and every scope refresh would give it the
  99. # printers of the next user given that name. Done before connect(), so the
  100. # socket carries its id from the moment it is listed, and checked again
  101. # after: a rename or delete commits before it closes the user's sockets by
  102. # id, so one landing in between is seen by the second check, and one after
  103. # it finds this socket listed with its id.
  104. principal_user_id: int | None = None
  105. if principal:
  106. principal_user_id = await _user_id_of(principal)
  107. if principal_user_id is None:
  108. logger.info("WebSocket connect refused: user %s is gone", principal)
  109. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  110. return
  111. # Stamped before connect() puts the socket in the broadcast list, so no
  112. # broadcast can reach it unfiltered (ws_manager refuses printer-bound
  113. # messages to a socket without a scope anyway).
  114. websocket.state.bambuddy_printer_scope = printer_scope
  115. websocket.state.bambuddy_scope_principal = (principal, api_key_id)
  116. websocket.state.bambuddy_principal_user_id = principal_user_id
  117. # Stash on connection state for any future per-message permission
  118. # logic; today the message handlers are read-only and only respond
  119. # to the requesting socket, so the stash is informational. The
  120. # explicit attribute (rather than a side dict) means a future
  121. # ``broadcast_to_principal()`` helper can filter on it without
  122. # touching every call site.
  123. websocket.state.bambuddy_principal = principal
  124. await ws_manager.connect(websocket)
  125. if principal and await _user_id_of(principal) != principal_user_id:
  126. logger.info("WebSocket connect refused: user %s was renamed or deleted while connecting", principal)
  127. await ws_manager.disconnect(websocket)
  128. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  129. return
  130. logger.info("WebSocket client connected")
  131. try:
  132. # Send initial status of all printers.
  133. statuses = {
  134. pid: state
  135. for pid, state in printer_manager.get_all_statuses().items()
  136. if websocket.state.bambuddy_printer_scope.allows(pid)
  137. }
  138. for printer_id, state in statuses.items():
  139. await websocket.send_json(
  140. {
  141. "type": "printer_status",
  142. "printer_id": printer_id,
  143. "data": printer_state_to_dict(
  144. state,
  145. printer_id,
  146. printer_manager.get_model(printer_id),
  147. printer_manager.get_drying_targets(printer_id),
  148. ),
  149. }
  150. )
  151. logger.info("Sent initial status for %s printers", len(statuses))
  152. # Keep connection alive and handle incoming messages.
  153. while True:
  154. data = await websocket.receive_json()
  155. # Handle ping/pong for keepalive
  156. if data.get("type") == "ping":
  157. await websocket.send_json({"type": "pong"})
  158. # Handle status request
  159. elif data.get("type") == "get_status":
  160. printer_id = data.get("printer_id")
  161. if printer_id and websocket.state.bambuddy_printer_scope.allows(printer_id):
  162. state = printer_manager.get_status(printer_id)
  163. if state:
  164. await websocket.send_json(
  165. {
  166. "type": "printer_status",
  167. "printer_id": printer_id,
  168. "data": printer_state_to_dict(
  169. state,
  170. printer_id,
  171. printer_manager.get_model(printer_id),
  172. printer_manager.get_drying_targets(printer_id),
  173. ),
  174. }
  175. )
  176. except WebSocketDisconnect:
  177. logger.info("WebSocket client disconnected normally")
  178. await ws_manager.disconnect(websocket)
  179. except Exception as e:
  180. logger.error("WebSocket error: %s", e, exc_info=True)
  181. await ws_manager.disconnect(websocket)