websocket.py 13 KB

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