websocket.py 11 KB

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