webapp_sign_in.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. """Behind the sign-in gate, a Webapp login lasts only while the browser credential it is bound to does.
  2. On the gateway's Webapp (``app.state.ui_surface == "webapp"``) with the sign-in gate engaged, every
  3. successful cookie login (a password login or an OAuth callback) also sets the cookie
  4. ``hermes_webapp_signin_<gateway>``: the hex HMAC-SHA256 of ``"webapp-sign-in"`` keyed with the browser
  5. session token the gateway serves (``web_server._SESSION_TOKEN``, kept in the gateway home by ``gateway.webapp_listener``). The gate treats
  6. a cookie session without a matching value as signed out. Replacing that token (``hermes webapp
  7. --sign-out``, or the CLI replacing the stored token while no gateway runs) therefore signs every browser
  8. out, whichever provider it signed in with. ``<gateway>`` comes from a digest of the gateway's home
  9. (:func:`cookie_gateway`), and the Webapp's listener names every sign-in cookie it sets that way, so two
  10. gateways' Webapps on one hostname keep their own logins and leave the standalone dashboard's alone.
  11. A request that passes records the generation of the credential it was checked against
  12. (``hermes_cli.browser_credential``) on ``request.state.webapp_sign_in``; the socket tickets it mints
  13. carry that generation, so the sockets they open are tracked (``web_session_sockets.track``) and close
  14. at sign-out, and a ticket minted before a sign-out opens nothing after it. The standalone dashboard
  15. never sets or checks the binding.
  16. Such a login's cookies also hold the sign-in provider's access and refresh token. Presented on their own
  17. (``Authorization: Bearer``, a socket's ``?token=``, ``/auth/native/refresh``) they would skip the
  18. binding, and a list of tokens to refuse cannot catch them: a provider may accept many spellings of one
  19. token (the bundled password provider decodes base64 leniently, so the quoted cookie value verifies too).
  20. So on the gateway's Webapp behind the gate a provider token works on its own only when this listener
  21. gave it to a native app's sign-in (RFC 8252: ``/auth/native/token``, then ``/auth/native/refresh``). The
  22. listener keeps a digest of each such token until it expires, in ``RECORD_PATH`` under the gateway home
  23. (``app.state.webapp_home``), so native apps stay signed in across a restart and a sign-out. A browser
  24. login's tokens therefore work only as that login's cookies and end with it.
  25. """
  26. from __future__ import annotations
  27. import hashlib
  28. import hmac
  29. import json
  30. import logging
  31. import threading
  32. import time
  33. from pathlib import Path
  34. from typing import Optional
  35. from fastapi import Request
  36. from fastapi.responses import Response
  37. from hermes_cli import browser_credential
  38. _MESSAGE = b"webapp-sign-in"
  39. _log = logging.getLogger(__name__)
  40. #: Where the gateway home keeps the digests of the provider tokens its listener gave native apps.
  41. RECORD_PATH = Path("webapp") / "native-sign-in-tokens.json"
  42. #: How long a refresh token stays recorded. Providers do not say when theirs expire; this is the longest
  43. #: the bundled providers issue (the password provider's 30 days) and how long a browser keeps one.
  44. REFRESH_TOKEN_LIFETIME = 30 * 24 * 60 * 60
  45. _records_lock = threading.Lock()
  46. #: Per gateway home: token digest -> expiry in Unix seconds. Read from the home's file once per
  47. #: process; this process is its only writer.
  48. _records: dict[Optional[Path], dict[str, int]] = {}
  49. def binding(token: str) -> str:
  50. """The ``hermes_webapp_signin`` value for browser session token *token*."""
  51. return hmac.new(token.encode(), _MESSAGE, hashlib.sha256).hexdigest()
  52. def applies(request: Request) -> bool:
  53. """Whether *request* reaches the gateway's Webapp behind the sign-in gate."""
  54. state = request.app.state
  55. return getattr(state, "ui_surface", None) == "webapp" and bool(getattr(state, "auth_required", False))
  56. def check(request: Request) -> bool:
  57. """Whether the cookie login on *request* is bound to the browser credential in use now. When it
  58. is, records that credential's generation on ``request.state.webapp_sign_in``."""
  59. from hermes_cli.dashboard_auth.cookies import read_webapp_signin_cookie
  60. token = browser_credential.current()
  61. presented = read_webapp_signin_cookie(request, _gateway(request)) or ""
  62. if not hmac.compare_digest(presented.encode(), binding(token).encode()):
  63. return False
  64. request.state.webapp_sign_in = browser_credential.generation_of(token)
  65. return True
  66. def sign_in_of(request: Request) -> Optional[str]:
  67. """The browser credential generation *request*'s login was checked against, or None off the
  68. Webapp's gate (the socket tickets it mints then carry no binding)."""
  69. return getattr(request.state, "webapp_sign_in", None)
  70. def _set(response: Response, request: Request, token: str) -> None:
  71. from hermes_cli.dashboard_auth.cookies import detect_https, set_webapp_signin_cookie
  72. from hermes_cli.dashboard_auth.prefix import prefix_from_request
  73. set_webapp_signin_cookie(response, value=binding(token), use_https=detect_https(request),
  74. prefix=prefix_from_request(request), gateway=_gateway(request))
  75. def bind(response: Response, request: Request) -> None:
  76. """Bind the login *request* just completed to the browser credential in use now."""
  77. if applies(request):
  78. _set(response, request, browser_credential.current())
  79. def renew(response: Response, request: Request) -> None:
  80. """Keep the binding as long-lived as the session cookies a refresh just rotated, unless the
  81. credential it was checked against was replaced while the request ran."""
  82. token = browser_credential.current_if(sign_in_of(request))
  83. if token is not None:
  84. _set(response, request, token)
  85. def token_works_alone(request: Request, token: str) -> bool:
  86. """Whether provider token *token* may be used on its own (a bearer header, a socket's
  87. ``?token=``, the refresh route) on *request*'s listener: anywhere but the gateway's Webapp behind
  88. the gate, as on main; there, only when this listener gave it to a native app's sign-in and it has
  89. not expired."""
  90. if not applies(request):
  91. return True
  92. with _records_lock:
  93. expires = _loaded(_home(request)).get(_digest(token))
  94. return expires is not None and expires > time.time()
  95. def gave_native_app(request: Request, session) -> None:
  96. """Record that this listener just gave *session*'s tokens to a native app's sign-in, so they work
  97. on their own on the gateway's Webapp behind the gate (:func:`token_works_alone`)."""
  98. if not applies(request):
  99. return
  100. now = int(time.time())
  101. given = ((session.access_token, int(session.expires_at or 0) or now + REFRESH_TOKEN_LIFETIME),
  102. (session.refresh_token, now + REFRESH_TOKEN_LIFETIME))
  103. home = _home(request)
  104. with _records_lock:
  105. records = _loaded(home)
  106. for token, expires in given:
  107. if token:
  108. records[_digest(token)] = expires
  109. for key in [key for key, expires in records.items() if expires <= now]:
  110. del records[key]
  111. if home is not None:
  112. _write(home / RECORD_PATH, records)
  113. def _digest(token: str) -> str:
  114. return hashlib.sha256(token.encode()).hexdigest()
  115. def _home(request: Request) -> Optional[Path]:
  116. home = getattr(request.app.state, "webapp_home", None)
  117. return Path(home) if home is not None else None
  118. def cookie_gateway(request: Request) -> str:
  119. """The suffix the gateway's Webapp gives every sign-in cookie it sets (``hermes_session_at_<it>``
  120. and the rest, ``hermes_cli.dashboard_auth.cookies``): cookies are not scoped to a port. ``""`` off
  121. the Webapp, where the standalone dashboard keeps main's names."""
  122. return _gateway(request) if getattr(request.app.state, "ui_surface", None) == "webapp" else ""
  123. def _gateway(request: Request) -> str:
  124. """This gateway's name in its sign-in cookie: a digest of its home, the same across restarts and
  125. different for every gateway on one machine (each home has its own); ``""`` without a home."""
  126. home = _home(request)
  127. return "" if home is None else hashlib.sha256(str(home.absolute()).encode()).hexdigest()[:16]
  128. def _loaded(home: Optional[Path]) -> dict[str, int]:
  129. """*home*'s record, read from its file on first use (call with ``_records_lock`` held). Without a
  130. home it lives in memory only."""
  131. if home in _records:
  132. return _records[home]
  133. stored: object = {}
  134. if home is not None:
  135. try:
  136. stored = json.loads((home / RECORD_PATH).read_text(encoding="utf-8-sig"))
  137. except FileNotFoundError:
  138. pass
  139. except (OSError, ValueError) as exc: # native apps sign in again
  140. _log.warning("Could not read the Webapp's record of native sign-ins: %s", exc)
  141. records = ({key: value for key, value in stored.items() if isinstance(value, int)}
  142. if isinstance(stored, dict) else {})
  143. _records[home] = records
  144. return records
  145. def _write(path: Path, records: dict[str, int]) -> None:
  146. from utils import atomic_write_text
  147. try:
  148. path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
  149. atomic_write_text(path, json.dumps(records, separators=(",", ":")) + "\n", mode=0o600)
  150. except OSError as exc: # this process still accepts them; after a restart native apps sign in again
  151. _log.warning("Could not save the Webapp's record of native sign-ins: %s", exc)
  152. def _reset_for_tests() -> None:
  153. """Forget every loaded record, as a new process starts with only the files."""
  154. with _records_lock:
  155. _records.clear()