web_session_sockets.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. """Browser sockets the dashboard session token opens, and how they end when it is replaced.
  2. A browser on the loopback Webapp never puts the session token in a socket URL. An authenticated
  3. request mints a one-use ticket for one socket instead: ``GATEWAY_SOCKET`` (``/api/ws``),
  4. ``HOST_TERMINAL_SOCKET`` (``/api/host-terminal``) or one of ``AUDIO_SOCKETS`` (the voice streams). A
  5. ticket named for one socket opens no other, and the host terminal opens only with its own ticket. A
  6. ticket minted with the session token records that browser credential's generation
  7. (``hermes_cli.browser_credential``) as ``session_token`` and opens nothing once the credential is
  8. replaced, nor behind the sign-in gate.
  9. Behind the sign-in gate the Webapp's browsers sign in instead, and each login is bound to the browser
  10. credential (``hermes_cli.webapp_sign_in``): a ticket such a login mints records the credential's
  11. generation as ``sign_in`` and likewise opens nothing once it is replaced.
  12. Every socket the browser credential admits, directly or through such a ticket, is tracked here under
  13. that generation until it ends; ``close_all``, which ``browser_credential.rotate`` runs when ``hermes
  14. webapp --sign-out`` replaces the credential, closes them all at once. Sockets admitted on any other
  15. credential (a native client's grant or sign-in, a dashboard login off the Webapp) are never tracked.
  16. """
  17. from __future__ import annotations
  18. import asyncio
  19. import contextlib
  20. import logging
  21. import threading
  22. import weakref
  23. from typing import Any, Optional
  24. from starlette.websockets import WebSocketDisconnect
  25. from hermes_cli import browser_credential
  26. _log = logging.getLogger(__name__)
  27. GATEWAY_SOCKET = "gateway"
  28. HOST_TERMINAL_SOCKET = "host-terminal"
  29. #: The voice streams beside ``/api/ws``, each named for its route ``/api/audio/<name>``.
  30. SPEAK_STREAM_SOCKET = "speak-stream"
  31. TRANSCRIBE_STREAM_SOCKET = "transcribe-stream"
  32. AUDIO_SOCKETS = frozenset({SPEAK_STREAM_SOCKET, TRANSCRIBE_STREAM_SOCKET})
  33. #: Sockets that open only with a ticket minted for them, never with a standing credential.
  34. OWN_TICKET_SOCKETS = frozenset({HOST_TERMINAL_SOCKET})
  35. #: What a signed-out tab's sockets are closed with: the same code a refused credential gets.
  36. SIGNED_OUT_CODE = 4401
  37. _lock = threading.Lock()
  38. _live: dict[int, tuple[weakref.ref, asyncio.AbstractEventLoop, str]] = {}
  39. def ticket_refusal(info: dict[str, Any], socket: Optional[str], *, auth_required: bool) -> Optional[str]:
  40. """Why a redeemed ticket may not open *socket*, or None when it may.
  41. A ticket named for a socket opens only that socket; an unnamed ticket opens any socket except
  42. one that takes only its own ticket. A ticket minted under the browser credential (with the
  43. session token, or by a Webapp login bound to it) opens nothing once that credential is replaced,
  44. and one minted with the session token opens nothing behind the sign-in gate.
  45. """
  46. named = info.get("socket")
  47. if named != socket and (named is not None or socket in OWN_TICKET_SOCKETS):
  48. return f"ticket for {named or 'any socket'} presented to {socket or 'an unnamed socket'}"
  49. granted = admitted_with(info)
  50. if granted is not None and not browser_credential.is_current(granted):
  51. return "ticket minted under a browser credential that has since been replaced"
  52. if auth_required and info.get("session_token") is not None:
  53. return "ticket minted with the session token, which opens nothing behind the sign-in gate"
  54. return None
  55. def admitted_with(info: dict[str, Any]) -> Optional[str]:
  56. """The browser credential generation a redeemed ticket was minted under, which its socket is
  57. tracked under; None when it was minted with another credential."""
  58. return info.get("session_token") or info.get("sign_in")
  59. def track(ws, admitted_with: str) -> None:
  60. """Keep *ws*, admitted under the browser credential generation *admitted_with*, until it ends.
  61. A socket admitted while that credential was being replaced closes at once, so ``close_all``
  62. never misses one.
  63. """
  64. try:
  65. loop = asyncio.get_running_loop()
  66. except RuntimeError: # judged outside a server loop: no live socket to close later
  67. return
  68. with _lock:
  69. # Ended sockets are dropped here rather than from a weakref callback, which garbage
  70. # collection could run while this thread already holds the lock.
  71. for key in [key for key, (ref, *_rest) in _live.items() if ref() is None]:
  72. del _live[key]
  73. _live[id(ws)] = (weakref.ref(ws), loop, admitted_with)
  74. if not browser_credential.is_current(admitted_with):
  75. _close_on(ws, loop)
  76. def admission_of(ws) -> Optional[str]:
  77. """The browser credential generation live socket *ws* was tracked under, or None when signing
  78. out does not close it. A socket it opens on the browser's behalf (a screen viewer) records the
  79. same one."""
  80. with _lock:
  81. entry = _live.get(id(ws))
  82. return entry[2] if entry is not None and entry[0]() is ws else None
  83. async def _close(ws) -> None:
  84. # The socket may already be closing or gone; it ends either way.
  85. with contextlib.suppress(RuntimeError, OSError, WebSocketDisconnect):
  86. await ws.close(code=SIGNED_OUT_CODE, reason="Signed out")
  87. def _close_on(ws, loop: asyncio.AbstractEventLoop) -> bool:
  88. if loop.is_closed():
  89. return False
  90. asyncio.run_coroutine_threadsafe(_close(ws), loop)
  91. return True
  92. def close_all() -> int:
  93. """Close every live socket the browser credential admitted, directly, through a ticket or through
  94. a login bound to it, each on its own event loop. Safe from any thread; returns how many were
  95. asked to close."""
  96. with _lock:
  97. live = list(_live.values())
  98. _live.clear()
  99. closing = sum(_close_on(ws, loop) for ref, loop, _digest in live if (ws := ref()) is not None)
  100. _log.info("Closing %d browser sockets opened with the replaced browser credential", closing)
  101. return closing
  102. browser_credential.on_rotate("sockets", close_all)