ws_tickets.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. """WS-upgrade auth credentials for gated mode.
  2. Browsers cannot set ``Authorization`` on a WebSocket upgrade, and gated mode has no token
  3. injected into the SPA, so two credential shapes exist: (1) single-use browser tickets
  4. (``mint_ticket`` / ``consume_ticket``) fetched via authenticated ``POST /api/auth/ws-ticket`` and
  5. passed as ``?ticket=`` on the upgrade — 30 s TTL, a leak is uninteresting; (2) a process-lifetime
  6. internal credential (``internal_ws_credential`` / ``consume_internal_credential``) for
  7. *server-spawned* WS clients (the embedded-TUI PTY child on ``/api/ws`` + ``/api/pub``), which
  8. reuse their attach URL on every reconnect, possibly >30 s after boot — minted once, never expires,
  9. multi-use, never injected into any HTML/SPA (leaves the process only via the child's environment,
  10. so browser XSS cannot read it; grants no more than a ticket). In-memory; ``time.time`` patchable.
  11. """
  12. from __future__ import annotations
  13. import secrets
  14. import threading
  15. import time
  16. from typing import Any, Dict, Optional, Tuple
  17. #: Long enough for ``getWsTicket()`` -> open WS, short enough that a leaked ticket is uninteresting.
  18. TTL_SECONDS = 30
  19. _lock = threading.Lock()
  20. _tickets: dict[str, tuple[int, dict[str, Any]]] = {} # ticket -> (expires_at, info)
  21. _internal_credential: Optional[str] = None # lazily minted; guarded by ``_lock``
  22. #: Identity recorded for internal-credential connections (audit logs distinguish them from tickets).
  23. INTERNAL_USER_ID = "server-internal"
  24. INTERNAL_PROVIDER = "server-internal"
  25. class TicketInvalid(Exception):
  26. """Ticket missing, expired, or already consumed."""
  27. def mint_ticket(*, user_id: str, provider: str, issuer: str = "",
  28. extra: Optional[dict[str, Any]] = None) -> str:
  29. """One-shot base64url ticket (32 random bytes) bound to this identity; ``consume_ticket``
  30. hands the ``info`` dict back to the WS handler. ``extra`` rides along for routes that need
  31. server-chosen context (the Bot Desktop bridge pins the RFB socket's profile home here so a
  32. client can never pick another profile's screen)."""
  33. ticket = secrets.token_urlsafe(32)
  34. info = {"user_id": user_id, "provider": provider, "minted_at": int(time.time()), **(extra or {})}
  35. if issuer:
  36. info["issuer"] = issuer
  37. with _lock:
  38. _tickets[ticket] = (int(time.time()) + TTL_SECONDS, info)
  39. _gc_expired_locked()
  40. return ticket
  41. def consume_ticket(ticket: str) -> dict[str, Any]:
  42. """Validate and consume (single-use). Raises :class:`TicketInvalid` on missing/expired/used."""
  43. now = int(time.time())
  44. with _lock:
  45. entry = _tickets.pop(ticket, None)
  46. if entry is None:
  47. # Truncated so misuse never logs the secret in full.
  48. truncated = (ticket[:8] + "…") if ticket else "<empty>"
  49. raise TicketInvalid(f"unknown ticket: {truncated}")
  50. expires_at, info = entry
  51. if expires_at < now:
  52. raise TicketInvalid("expired")
  53. return info
  54. def _gc_expired_locked() -> None:
  55. """Drop expired tickets. Caller must hold ``_lock``."""
  56. now = int(time.time())
  57. for t in [t for t, (exp, _) in _tickets.items() if exp < now]:
  58. _tickets.pop(t, None)
  59. def internal_ws_credential() -> str:
  60. """Process-lifetime internal WS credential, minted once. Never injected into the SPA or
  61. returned over REST — only passed to a spawned child via its environment."""
  62. global _internal_credential
  63. with _lock:
  64. if _internal_credential is None:
  65. _internal_credential = secrets.token_urlsafe(32)
  66. return _internal_credential
  67. def consume_internal_credential(value: str) -> dict[str, Any]:
  68. """Validate an internal credential (NOT single-use); returns the fixed server-internal
  69. ``{user_id, provider}`` info dict, mirroring ``consume_ticket``. Constant-time compare; any
  70. value is rejected until a credential has been minted."""
  71. with _lock:
  72. expected = _internal_credential
  73. if not value or expected is None:
  74. raise TicketInvalid("no internal credential")
  75. if not secrets.compare_digest(value.encode(), expected.encode()):
  76. raise TicketInvalid("internal credential mismatch")
  77. return {"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER}
  78. def _reset_for_tests() -> None:
  79. """Test-only: drop all tickets and the internal credential."""
  80. global _internal_credential
  81. with _lock:
  82. _tickets.clear()
  83. _internal_credential = None