middleware.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. """Auth-gate middleware for the dashboard.
  2. Engaged when ``app.state.auth_required is True``; a no-op otherwise (loopback
  3. mode is handled by the legacy ``_SESSION_TOKEN`` ``auth_middleware``). Allows
  4. the auth-bootstrap routes and static assets through unauthenticated; for
  5. everything else demands a bearer token or a valid session cookie and attaches
  6. the verified :class:`Session` to ``request.state.session``. On the gateway's
  7. Webapp a cookie session also needs its sign-in binding to the browser credential
  8. (``hermes_cli.webapp_sign_in``), and its cookie writes, sign-out included, must come
  9. from the Webapp's own origin; elsewhere a cookie write the browser marks as another page's
  10. (``Sec-Fetch-Site``) is refused. HTML routes are
  11. redirected to ``/login``; ``/api/*`` routes get a 401 JSON envelope.
  12. """
  13. from __future__ import annotations
  14. import logging
  15. from typing import Awaitable, Callable
  16. from urllib.parse import quote
  17. from fastapi import Request
  18. from fastapi.responses import JSONResponse, RedirectResponse, Response
  19. from starlette.concurrency import run_in_threadpool
  20. from hermes_cli import webapp_sign_in
  21. from hermes_cli.dashboard_auth import list_interactive_providers, list_session_providers
  22. from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log
  23. from hermes_cli.dashboard_auth.base import ProviderError
  24. from hermes_cli.dashboard_auth.cookies import (
  25. clear_session_cookies, clear_sso_attempt_cookie, detect_https, read_session_cookies,
  26. read_session_provider, read_sso_attempt_cookie, set_session_cookies,
  27. set_session_provider_cookie, set_sso_attempt_cookie)
  28. from hermes_cli.dashboard_auth.prefix import prefix_from_request
  29. from hermes_cli.dashboard_auth.public_paths import PUBLIC_API_PATHS
  30. from hermes_cli.dashboard_auth.refresh_singleflight import refresh_session_coalesced
  31. from hermes_cli.dashboard_auth.request_utils import (
  32. access_token_max_age as _expires_in_seconds, client_ip as _client_ip,
  33. cookie_origin_is_allowed, extract_bearer as _extract_bearer, is_safe_next_path,
  34. scan_session_providers, unreachable_response)
  35. _log = logging.getLogger(__name__)
  36. # Prefix-matched bypass list: auth bootstrap routes and static asset mounts. ``/assets/`` with
  37. # the trailing slash matches ``/assets/foo.css`` but not ``/assetsleak``.
  38. _GATE_PUBLIC_PREFIXES: tuple[str, ...] = (
  39. "/auth/login", "/auth/callback", "/auth/native/authorize", "/auth/native/token",
  40. "/auth/native/refresh", "/auth/password-login", "/auth/logout", "/login",
  41. "/api/auth/providers", "/api/mcp/oauth/callback/",
  42. "/assets/", "/dashboard-plugins/", "/favicon.ico", "/ds-assets/", "/fonts/", "/fonts-terminal/")
  43. # Page icons, matched exactly. Browsers fetch them without cookies (the Webapp's page icon and
  44. # home-screen icon are ``/apple-touch-icon.png``), so behind the gate they hit the sign-in redirect
  45. # and log an auto-SSO ``login_start`` with no sign-in behind it.
  46. _GATE_PUBLIC_ICONS: frozenset[str] = frozenset({"/apple-touch-icon.png"})
  47. def _path_is_public(path: str) -> bool:
  48. """:data:`PUBLIC_API_PATHS` (shared with the legacy middleware) and :data:`_GATE_PUBLIC_ICONS`
  49. matched exactly so ``/api/status`` never exposes ``/api/status/extension``;
  50. :data:`_GATE_PUBLIC_PREFIXES` prefix-matched."""
  51. return path in PUBLIC_API_PATHS or path in _GATE_PUBLIC_ICONS or any(
  52. path == p or path.startswith(p) for p in _GATE_PUBLIC_PREFIXES)
  53. def _safe_next_target(request: Request) -> str:
  54. """URL-encoded ``next`` value for the login redirect, or ``""``. Only same-origin paths outside
  55. the auth flow and ``/api`` are kept (query preserved); dropped deep links fall back to the
  56. SPA's ``sessionStorage["hermes.lastLocation"]``.
  57. Behind a reverse proxy at a sub-path (``X-Forwarded-Prefix``, e.g. ``/hermes``), the prefix
  58. is prepended AFTER validation so the post-login redirect lands within the mount
  59. (``/hermes/sessions`` rather than bare ``/sessions``)."""
  60. path = request.url.path
  61. if not path or not is_safe_next_path(path):
  62. return ""
  63. prefix = prefix_from_request(request)
  64. if prefix:
  65. path = prefix + path
  66. query = request.url.query
  67. return quote(f"{path}?{query}" if query else path, safe="")
  68. #: The 403 detail for a cookie write from another origin; only the gateway's Webapp checks
  69. #: (``SurfacePolicy.own_origin_cookie_writes``), so it names the public URL that listener reads.
  70. _CROSS_ORIGIN_WRITE_DETAIL = ("Cookie-authenticated writes must come from the Webapp's own origin. "
  71. "Behind a reverse proxy, set webapp.public_url to the URL the browser uses.")
  72. _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})
  73. #: The 403 detail for a cookie write the browser itself says another page made, on a surface
  74. #: without the Webapp's own-origin check.
  75. _OTHER_PAGE_WRITE_DETAIL = "Cookie-authenticated writes must come from this dashboard's own page."
  76. #: ``Sec-Fetch-Site`` verdicts naming a request another page made. ``same-site`` is a sibling
  77. #: (another port or subdomain) that ``SameSite=Lax`` still sends the session cookies from.
  78. _OTHER_PAGE_FETCH_SITES = frozenset({"same-site", "cross-site"})
  79. def _own_origin_writes(request: Request) -> bool:
  80. from hermes_cli.web_server_surface import policy
  81. return policy(request.app.state).own_origin_cookie_writes
  82. def _browser_says_other_page(request: Request) -> bool:
  83. """The browser's own ``Sec-Fetch-Site`` verdict names another page. Pages cannot set the
  84. header and the browser computes it against the URL it addressed, so it holds behind any proxy;
  85. a request without Fetch Metadata (a plain-HTTP origin, a non-browser client) is not judged."""
  86. return any(value.strip().lower() in _OTHER_PAGE_FETCH_SITES
  87. for value in request.headers.getlist("sec-fetch-site"))
  88. def _unauth_response(request: Request, *, reason: str) -> Response:
  89. """API routes -> 401 JSON with ``login_url``; HTML routes -> 302 -> /login. fetch() follows a
  90. 302 opaquely into the cross-origin OAuth dance, so API routes never get redirects; the SPA's
  91. 401 handler navigates to ``login_url`` on ``unauthenticated`` / ``session_expired``."""
  92. next_param = _safe_next_target(request)
  93. prefix = prefix_from_request(request)
  94. login_url = f"{prefix}/login?next={next_param}" if next_param else f"{prefix}/login"
  95. if request.url.path.startswith("/api/"):
  96. expired = reason == "invalid_or_expired_session"
  97. # Same reason the client already receives. Never include the bearer.
  98. audit_log(AuditEvent.SESSION_REJECTED, reason=reason, path=request.url.path,
  99. ip=_client_ip(request))
  100. return JSONResponse(
  101. {"error": "session_expired" if expired else "unauthenticated", "detail": "Unauthorized",
  102. "reason": reason, "login_url": login_url}, status_code=401)
  103. return RedirectResponse(url=login_url, status_code=302)
  104. def _auto_sso_response(request: Request) -> Response | None:
  105. """302 straight to ``/auth/login`` on an unauthenticated HTML load, or ``None``.
  106. Only for a document load (not ``/api/*``) when exactly one interactive OAuth-style provider is
  107. registered (a password provider must render the form) and the one-shot loop-guard cookie is
  108. absent — a present marker means the portal had no session last time: clear it and fall back
  109. to ``/login`` rather than ping-pong. Convenience, not a security check.
  110. """
  111. if request.url.path.startswith("/api/"):
  112. return None
  113. gateway = webapp_sign_in.cookie_gateway(request)
  114. if read_sso_attempt_cookie(request, gateway):
  115. resp = _unauth_response(request, reason="no_cookie")
  116. clear_sso_attempt_cookie(resp, prefix=prefix_from_request(request), gateway=gateway)
  117. return resp
  118. providers = list_interactive_providers()
  119. if len(providers) != 1 or getattr(providers[0], "supports_password", False):
  120. return None
  121. provider = providers[0]
  122. prefix = prefix_from_request(request)
  123. next_param = _safe_next_target(request)
  124. auth_login = f"{prefix}/auth/login?provider={quote(provider.name, safe='')}"
  125. if next_param:
  126. auth_login = f"{auth_login}&next={next_param}"
  127. resp = RedirectResponse(url=auth_login, status_code=302)
  128. set_sso_attempt_cookie(resp, use_https=detect_https(request), prefix=prefix, gateway=gateway)
  129. audit_log(AuditEvent.LOGIN_START, provider=provider.name, reason="auto_sso",
  130. ip=_client_ip(request))
  131. return resp
  132. def _verify_access_token(
  133. request: Request, *, access_token: str, provider_hint: str | None = None, audit: bool = True):
  134. """Run ``verify_session`` across the provider stack; Session or ``None``. ``audit=False`` is
  135. the native-app bearer path (no cookie, no server-side refresh — the desktop rotates via
  136. ``/auth/native/refresh``); 503-on-outage semantics come from :func:`scan_session_providers`."""
  137. def _audit_unreachable(provider):
  138. if audit:
  139. audit_log(AuditEvent.SESSION_VERIFY_FAILURE, provider=provider.name,
  140. reason="provider_unreachable", ip=_client_ip(request))
  141. return scan_session_providers(
  142. provider_hint, lambda p: p.verify_session(access_token=access_token),
  143. phase="verify" if audit else "bearer verify", log=_log, on_unreachable=_audit_unreachable)
  144. def peek_session(request: Request):
  145. """The verified Session a request to a PUBLIC path carries, or ``None``, with the gate's own
  146. checks (Webapp sign-in binding, bearers only a native app was given) and none of its side
  147. effects: no refresh, no cookie writes, no audit records, no 401. A public route uses it to
  148. decide how much to show; an expired or unverifiable session reads as signed out."""
  149. bearer = _extract_bearer(request)
  150. if bearer:
  151. if not webapp_sign_in.token_works_alone(request, bearer):
  152. return None
  153. access_token, provider_hint = bearer, None
  154. else:
  155. gateway = webapp_sign_in.cookie_gateway(request)
  156. access_token, _rt = read_session_cookies(request, gateway)
  157. if not access_token or (webapp_sign_in.applies(request) and not webapp_sign_in.check(request)):
  158. return None
  159. provider_hint = read_session_provider(request, gateway)
  160. try:
  161. return _verify_access_token(
  162. request, access_token=access_token, provider_hint=provider_hint, audit=False)
  163. except ProviderError:
  164. return None
  165. async def _serve_refreshed(request: Request, call_next, new_session, provider: str) -> Response:
  166. """Serve the request under a just-rotated session and write the rotated cookies back. Writing
  167. the ROTATED RT is mandatory: Portal runs reuse detection, so replaying the stale RT would
  168. revoke the session."""
  169. request.state.session = new_session
  170. response = await call_next(request)
  171. set_session_cookies(
  172. response, access_token=new_session.access_token, refresh_token=new_session.refresh_token,
  173. access_token_expires_in=_expires_in_seconds(new_session), use_https=detect_https(request),
  174. prefix=prefix_from_request(request), provider=provider,
  175. gateway=webapp_sign_in.cookie_gateway(request))
  176. webapp_sign_in.renew(response, request)
  177. audit_log(AuditEvent.REFRESH_SUCCESS, provider=provider, user_id=new_session.user_id,
  178. ip=_client_ip(request))
  179. return response
  180. def _session_expired_response(request: Request) -> Response:
  181. """Refresh failed (or no RT): structured 401/redirect and clear the dead cookies under the
  182. active prefix so the deletion Path matches the set Path."""
  183. audit_log(AuditEvent.SESSION_VERIFY_FAILURE, reason="no_provider_recognises",
  184. ip=_client_ip(request))
  185. response = _unauth_response(request, reason="invalid_or_expired_session")
  186. clear_session_cookies(response, prefix=prefix_from_request(request),
  187. gateway=webapp_sign_in.cookie_gateway(request))
  188. return response
  189. async def gated_auth_middleware(
  190. request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
  191. """Engaged only when ``app.state.auth_required is True``."""
  192. if not getattr(request.app.state, "auth_required", False):
  193. return await call_next(request)
  194. # Already authenticated by the token-auth seam (service caller on a registered token
  195. # route): not a cookie session, must not bounce to /login.
  196. if (getattr(request.state, "token_authenticated", False)
  197. or getattr(request.state, "native_http_principal", None)):
  198. return await call_next(request)
  199. # Login/callback routes have their own credentials/state checks. Logout is public so an
  200. # expired session can leave; where cookie writes must come from the listener's own origin, or
  201. # the browser says another page sent it, it still consumes cookies, so it goes through that
  202. # check.
  203. own_origin = _own_origin_writes(request)
  204. other_page = not own_origin and _browser_says_other_page(request)
  205. cookie_logout = (own_origin or other_page) and request.url.path == "/auth/logout"
  206. if _path_is_public(request.url.path) and not cookie_logout:
  207. return await call_next(request)
  208. # RFC 8252 native-app bearer path: the same provider-minted access token the cookie flow
  209. # stores, verified with the same provider stack, no cookie read or set. A presented-but-
  210. # invalid bearer gets the structured 401 so the desktop refreshes/re-logs instead of
  211. # following a cookie redirect. On the gateway's Webapp only tokens it gave a native app's
  212. # sign-in work here: a browser login's tokens work only as its cookies, which sign-out ends.
  213. bearer = _extract_bearer(request)
  214. if bearer:
  215. if cookie_logout:
  216. return await call_next(request)
  217. if not webapp_sign_in.token_works_alone(request, bearer):
  218. return _unauth_response(request, reason="invalid_or_expired_session")
  219. try:
  220. bearer_session = _verify_access_token(request, access_token=bearer, audit=False)
  221. except ProviderError as e:
  222. return unreachable_response(str(e))
  223. if bearer_session is not None:
  224. request.state.session = bearer_session
  225. return await call_next(request)
  226. return _unauth_response(request, reason="invalid_or_expired_session")
  227. gateway = webapp_sign_in.cookie_gateway(request)
  228. at, _rt = read_session_cookies(request, gateway)
  229. provider_hint = read_session_provider(request, gateway)
  230. if (own_origin and (at or _rt) and request.method not in _SAFE_METHODS
  231. and not cookie_origin_is_allowed(request)):
  232. return JSONResponse(status_code=403, content={"detail": _CROSS_ORIGIN_WRITE_DETAIL})
  233. # Elsewhere main's rule stands (a Host-rewriting plain-HTTP proxy's page sends no Fetch
  234. # Metadata and still writes), but a write the browser itself says another page made is refused.
  235. if other_page and (at or _rt) and request.method not in _SAFE_METHODS:
  236. return JSONResponse(status_code=403, content={"detail": _OTHER_PAGE_WRITE_DETAIL})
  237. if cookie_logout:
  238. return await call_next(request)
  239. if not at and not _rt:
  240. # No session at all: try the silent portal bounce before /login.
  241. auto = _auto_sso_response(request)
  242. return auto if auto is not None else _unauth_response(request, reason="no_cookie")
  243. if webapp_sign_in.applies(request) and not webapp_sign_in.check(request):
  244. # A login on the gateway's Webapp holds only while the browser credential it was bound to is
  245. # in use; signing out replaced it. The cookies stay and open nothing until it signs in again.
  246. return _unauth_response(request, reason="signed_out")
  247. # An absent AT with a present RT is the COMMON expiry case (the AT cookie's Max-Age tracks
  248. # the token TTL, so the browser evicts it first) — skip straight to refresh.
  249. session = None
  250. if at:
  251. try:
  252. session = _verify_access_token(request, access_token=at, provider_hint=provider_hint)
  253. except ProviderError as e:
  254. return unreachable_response(str(e))
  255. if session is None:
  256. # Rotate via the refresh token before forcing re-login; on success the request is
  257. # served transparently with the rotated cookies re-set.
  258. try:
  259. refreshed = await run_in_threadpool(
  260. _attempt_refresh, request, refresh_token=_rt, provider_hint=provider_hint)
  261. except ProviderError as e:
  262. # Uncertain (provider unreachable), not rejected: keep the cookies.
  263. return unreachable_response(str(e))
  264. if refreshed is None:
  265. return _session_expired_response(request)
  266. return await _serve_refreshed(request, call_next, *refreshed)
  267. request.state.session = session
  268. response = await call_next(request)
  269. if not provider_hint and session.provider:
  270. set_session_provider_cookie(
  271. response, provider=session.provider, use_https=detect_https(request),
  272. prefix=prefix_from_request(request), gateway=gateway)
  273. return response
  274. def _attempt_refresh(request: Request, *, refresh_token, provider_hint: str | None = None):
  275. """Rotate an expired session via the refresh token; ``(Session, provider_name)`` or ``None``.
  276. Concurrent requests carrying the same stale RT are coalesced (``refresh_singleflight``): a
  277. burst of parallel fetches after AT expiry must not replay a rotated RT into the provider's
  278. reuse detection. ``RefreshExpiredError`` rejects that candidate only (Basic raises it for
  279. foreign opaque tokens too); if none succeeds and any raised ``ProviderError`` it is
  280. re-raised so the caller returns 503 without clearing cookies. Synchronous: the gate runs it
  281. in the threadpool so a slow IdP never blocks the event loop."""
  282. if not refresh_token:
  283. return None
  284. def _audit_failure(reason):
  285. return lambda provider: audit_log(
  286. AuditEvent.REFRESH_FAILURE, provider=provider.name, reason=reason,
  287. ip=_client_ip(request))
  288. return refresh_session_coalesced(
  289. refresh_token, provider_hint or "", phase="refresh", log=_log,
  290. on_rejected=_audit_failure("refresh_expired"),
  291. on_unreachable=_audit_failure("provider_unreachable"))