websocket.py 12 KB

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