request_utils.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """Request-level helpers shared by the auth routes and both middlewares."""
  2. from __future__ import annotations
  3. import logging
  4. import time
  5. from typing import Callable, Optional
  6. from urllib.parse import urlsplit
  7. from fastapi import Request
  8. from fastapi.responses import JSONResponse
  9. from hermes_cli.dashboard_auth import list_session_providers
  10. from hermes_cli.dashboard_auth.base import DashboardAuthProvider, ProviderError
  11. # Paths a post-login redirect must never land on: the auth flow itself (would loop) and any
  12. # ``/api/*`` target (raw JSON in the address bar, indistinguishable from a weaponised redirect).
  13. _NEXT_DENY_PREFIXES = ("/login", "/auth/", "/api/auth/")
  14. def client_ip(request: Request) -> str:
  15. """ASGI peer address for rate limits, native pending caps, and auth audit.
  16. Never parse client-supplied ``X-Forwarded-For`` here: direct clients can
  17. spoof it. Trusted proxy normalization belongs upstream, where the server
  18. may rewrite ``request.client`` only for operator-configured trusted peers.
  19. """
  20. return request.client.host if request.client else ""
  21. def extract_bearer(request: Request) -> str:
  22. """``Authorization: Bearer <token>`` value (scheme case-insensitive), or ``""``."""
  23. parts = request.headers.get("authorization", "").split(" ", 1)
  24. if len(parts) == 2 and parts[0].strip().lower() == "bearer":
  25. return parts[1].strip()
  26. return ""
  27. def _http_origin(value: str) -> tuple[str, str, int] | None:
  28. """Parse one serialized HTTP origin, never an opaque or URL-like origin."""
  29. if not value or any(ord(c) <= 32 or ord(c) >= 127 or c in "\\,?#%" for c in value):
  30. return None
  31. try:
  32. parsed = urlsplit(value)
  33. if (parsed.scheme not in {"http", "https"} or not parsed.hostname
  34. or parsed.username is not None or parsed.password is not None or parsed.path
  35. or parsed.netloc.endswith(":")):
  36. return None
  37. port = parsed.port
  38. effective_port = port if port is not None else (443 if parsed.scheme == "https" else 80)
  39. return parsed.scheme, parsed.hostname, effective_port
  40. except ValueError:
  41. return None
  42. def cookie_origin_is_allowed(request: Request) -> bool:
  43. """Cookie writes must come from the listener's own origin, not just its site. The gate asks
  44. only where the surface policy says so (``SurfacePolicy.own_origin_cookie_writes``: the
  45. gateway's Webapp); elsewhere the gate refuses only writes the browser marks as another page's.
  46. ``SameSite=Lax`` keeps cross-site pages from sending the session cookies but
  47. still admits same-site siblings (another port or subdomain). A write without
  48. Origin passes only in a shape no page can produce (native Desktop's own
  49. requests), and only after the Host guard. With an Origin, the browser's
  50. ``Sec-Fetch-Site`` verdict decides when present: pages cannot set it, and the
  51. browser computes it against the URL it actually addressed, so it stays right
  52. behind a TLS-terminating or Host-rewriting proxy where this server's view of
  53. its own URL differs. Only a browser without Fetch Metadata falls back to
  54. comparing Origin with the OAuth public-URL authority, otherwise the request's
  55. Host and ASGI scheme (uvicorn applies *trusted* proxy headers). Never trust
  56. raw forwarded headers here or reuse WS's opaque/non-HTTP Origin exemption.
  57. """
  58. from hermes_cli.dashboard_auth.prefix import resolve_public_url
  59. from hermes_cli.web_server import _is_accepted_host
  60. bound_host = getattr(request.app.state, "bound_host", None)
  61. if bound_host and not _is_accepted_host(
  62. request.headers.get("host", ""), bound_host,
  63. getattr(request.app.state, "trusted_public_hosts", frozenset()),
  64. ):
  65. return False
  66. origins = request.headers.getlist("origin")
  67. fetch_sites = request.headers.getlist("sec-fetch-site")
  68. if not origins:
  69. # Electron's net.request sends Sec-Fetch-Site: none to https and loopback, and no Fetch
  70. # Metadata to plain http. Pages attach Origin to every non-GET and keep none for typed GETs.
  71. return fetch_sites in ([], ["none"])
  72. origin = _http_origin(origins[0]) if len(origins) == 1 else None
  73. if origin is None:
  74. return False
  75. if fetch_sites:
  76. return fetch_sites == ["same-origin"]
  77. target = urlsplit(resolve_public_url(request.app.state) or str(request.url))
  78. return origin == _http_origin(f"{target.scheme}://{target.netloc}")
  79. def is_safe_next_path(path: str) -> bool:
  80. """Same-origin post-login target: rejects non-relative and protocol-relative (``//evil``)
  81. values, the auth routes themselves, and every ``/api`` path."""
  82. if not path.startswith("/") or path.startswith("//"):
  83. return False
  84. if any(path == p or path.startswith(p) for p in _NEXT_DENY_PREFIXES):
  85. return False
  86. return not (path == "/api" or path.startswith("/api/"))
  87. def access_token_max_age(session) -> int:
  88. """Cookie Max-Age for the access token: seconds to ``exp``, floored at 60."""
  89. return max(60, int(session.expires_at) - int(time.time()))
  90. def unreachable_response(provider_name: str) -> JSONResponse:
  91. """503 for a transient IDP/backing-store outage (never a forced re-login)."""
  92. return JSONResponse({"detail": f"Auth provider {provider_name!r} unreachable"}, status_code=503)
  93. def scan_session_providers(
  94. provider_hint: Optional[str], call: Callable[[DashboardAuthProvider], object], *, phase: str,
  95. log: logging.Logger, swallow: tuple[type[BaseException], ...] = (),
  96. on_swallow: Optional[Callable[[DashboardAuthProvider], None]] = None,
  97. on_unreachable: Optional[Callable[[DashboardAuthProvider], None]] = None):
  98. """Run ``call`` across the session providers; first non-``None`` result or ``None``.
  99. The hinted provider goes first (stable sort; a stale/unknown hint leaves registration order
  100. intact). ``swallow`` exceptions reject that candidate only. A ``ProviderError`` (IDP/JWKS
  101. unreachable) must NOT abort the chain — the credential may belong to a different, reachable
  102. provider; it is logged under ``phase`` and, if nothing else succeeds, re-raised as
  103. ``ProviderError(name)`` so the caller answers 503 instead of forcing a re-login.
  104. """
  105. providers = list_session_providers()
  106. if provider_hint:
  107. providers.sort(key=lambda provider: provider.name != provider_hint)
  108. unreachable: Optional[str] = None
  109. for provider in providers:
  110. try:
  111. result = call(provider)
  112. except swallow:
  113. if on_swallow is not None:
  114. on_swallow(provider)
  115. continue
  116. except ProviderError as e:
  117. log.warning("dashboard-auth: provider %r unreachable during %s: %s",
  118. provider.name, phase, e)
  119. if on_unreachable is not None:
  120. on_unreachable(provider)
  121. if unreachable is None:
  122. unreachable = provider.name
  123. continue
  124. if result is not None:
  125. return result
  126. if unreachable is not None:
  127. raise ProviderError(unreachable)
  128. return None