websocket.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 backend.app.core.auth import is_auth_enabled, verify_websocket_token
  18. from backend.app.core.database import async_session
  19. from backend.app.core.websocket import ws_manager
  20. from backend.app.services.printer_manager import printer_manager, printer_state_to_dict
  21. logger = logging.getLogger(__name__)
  22. router = APIRouter()
  23. # 4401 mirrors the WebSocket "unauthorised" application close code
  24. # convention used by Sec-WebSocket-Protocol authors (private-use range
  25. # is 4000-4999 per RFC 6455). The SPA distinguishes 4401 from network
  26. # drops and refetches a token instead of retrying with the old one.
  27. _WS_CLOSE_UNAUTHORIZED = 4401
  28. @router.websocket("/ws")
  29. async def websocket_endpoint(websocket: WebSocket, token: str | None = Query(default=None)) -> None:
  30. """WebSocket endpoint for real-time updates.
  31. Connection auth (GHSA-r2qv follow-up):
  32. - Auth disabled → connect without a token, identical to the prior
  33. behaviour (single-user / local-network deployments).
  34. - Auth enabled → ``?token=<value>`` query param must hold an
  35. unexpired token minted via ``POST /api/v1/auth/ws-token``.
  36. Missing / invalid / expired token → ``close(code=4401)`` *before*
  37. ``accept()`` so no ``ws_manager.broadcast`` ever reaches the
  38. caller (broadcasts walk ``active_connections`` blindly — letting
  39. an unauthenticated socket into that list is a fan-out leak).
  40. The auth check is fail-closed at every error path: a DB exception
  41. while reading the ``auth_enabled`` setting closes the connection
  42. rather than admitting the caller.
  43. """
  44. # Authenticate before accept() so an unauth caller never lands in
  45. # ws_manager.active_connections (where broadcasts blindly fan out).
  46. try:
  47. async with async_session() as db:
  48. auth_required = await is_auth_enabled(db)
  49. except Exception: # SEC-AUTH-EXC: DB failure on auth probe → fail-closed (refuse connect), matches is_auth_enabled itself which returns True on error
  50. logger.error("WebSocket auth probe failed; refusing connection", exc_info=True)
  51. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  52. return
  53. principal: str | None = None
  54. if auth_required:
  55. if not token:
  56. logger.info("WebSocket connect refused: no token (auth enabled)")
  57. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  58. return
  59. principal = await verify_websocket_token(token)
  60. if principal is None:
  61. logger.info("WebSocket connect refused: invalid or expired token")
  62. await websocket.close(code=_WS_CLOSE_UNAUTHORIZED)
  63. return
  64. # Token verified (or auth disabled); now safe to admit the connection.
  65. logger.info("WebSocket client connecting (principal=%s)", principal if principal else "<anonymous>")
  66. await ws_manager.connect(websocket)
  67. # Stash on connection state for any future per-message permission
  68. # logic; today the message handlers are read-only and only respond
  69. # to the requesting socket, so the stash is informational. The
  70. # explicit attribute (rather than a side dict) means a future
  71. # ``broadcast_to_principal()`` helper can filter on it without
  72. # touching every call site.
  73. websocket.state.bambuddy_principal = principal
  74. logger.info("WebSocket client connected")
  75. try:
  76. # Send initial status of all printers.
  77. statuses = printer_manager.get_all_statuses()
  78. for printer_id, state in statuses.items():
  79. await websocket.send_json(
  80. {
  81. "type": "printer_status",
  82. "printer_id": printer_id,
  83. "data": printer_state_to_dict(
  84. state,
  85. printer_id,
  86. printer_manager.get_model(printer_id),
  87. printer_manager.get_drying_targets(printer_id),
  88. ),
  89. }
  90. )
  91. logger.info("Sent initial status for %s printers", len(statuses))
  92. # Keep connection alive and handle incoming messages.
  93. while True:
  94. data = await websocket.receive_json()
  95. # Handle ping/pong for keepalive
  96. if data.get("type") == "ping":
  97. await websocket.send_json({"type": "pong"})
  98. # Handle status request
  99. elif data.get("type") == "get_status":
  100. printer_id = data.get("printer_id")
  101. if printer_id:
  102. state = printer_manager.get_status(printer_id)
  103. if state:
  104. await websocket.send_json(
  105. {
  106. "type": "printer_status",
  107. "printer_id": printer_id,
  108. "data": printer_state_to_dict(
  109. state,
  110. printer_id,
  111. printer_manager.get_model(printer_id),
  112. printer_manager.get_drying_targets(printer_id),
  113. ),
  114. }
  115. )
  116. except WebSocketDisconnect:
  117. logger.info("WebSocket client disconnected normally")
  118. await ws_manager.disconnect(websocket)
  119. except Exception as e:
  120. logger.error("WebSocket error: %s", e, exc_info=True)
  121. await ws_manager.disconnect(websocket)