cookies.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """Cookie helpers for dashboard auth.
  2. All HttpOnly, ``SameSite=Lax`` unless noted, Path = proxy prefix or /: ``hermes_session_at``
  3. (access token; Max-Age = token TTL), ``hermes_session_rt`` (rotating refresh token; written only
  4. when the provider returned one, always cleared on logout/expiry), ``hermes_session_provider``
  5. (non-secret routing hint so an RT is not handed to the wrong provider), ``hermes_session_pkce``
  6. (PKCE state + CSRF nonce + provider hint, 10 min; ``SameSite=None; Secure`` over HTTPS because it
  7. is set on the /auth/login 302 and must survive the cross-site redirect chain — Chromium drops Lax
  8. cookies set on such a 302, crbug 40508226), ``hermes_sso_attempt`` (auto-SSO loop guard, 60 s),
  9. ``hermes_webapp_signin`` (the gateway Webapp's sign-in binding, ``hermes_cli.webapp_sign_in``; set only
  10. by a login on the Webapp, Max-Age as the refresh token's).
  11. Cookies are not scoped to a port, so on the gateway's Webapp every one of these names is followed by
  12. ``_<gateway>`` (``hermes_session_at_<gateway>``, ``<gateway>`` from a digest of the gateway's home,
  13. ``webapp_sign_in.cookie_gateway``): two gateways' Webapps on one hostname keep their own logins, and
  14. neither reads or clears the names the standalone dashboard uses.
  15. ``Secure`` only when ``request.url.scheme`` is https. Cookie-prefix hardening per
  16. draft-west-cookie-prefixes: bare name over HTTP; ``__Host-`` on gated HTTPS with Path=/;
  17. ``__Secure-`` behind a proxy prefix (``__Host-`` forbids Path != /). Setters and readers BOTH
  18. resolve the name via :func:`_resolved_name` and :func:`gateway_cookie_name` — a mismatch silently
  19. breaks sessions.
  20. """
  21. from __future__ import annotations
  22. import base64
  23. import binascii
  24. import json
  25. import re
  26. from typing import Literal, Optional, Tuple
  27. from urllib.parse import unquote
  28. from fastapi import Request
  29. from fastapi.responses import Response
  30. SESSION_AT_COOKIE = "hermes_session_at"
  31. SESSION_RT_COOKIE = "hermes_session_rt"
  32. SESSION_PROVIDER_COOKIE = "hermes_session_provider"
  33. PKCE_COOKIE = "hermes_session_pkce"
  34. SSO_ATTEMPT_COOKIE = "hermes_sso_attempt"
  35. #: The Webapp's sign-in binding (``hermes_cli.webapp_sign_in``); set beside the session cookies.
  36. WEBAPP_SIGNIN_COOKIE = "hermes_webapp_signin"
  37. # Name variants a reader may have to try; most strict first.
  38. _NAME_VARIANTS = ("__Host-", "__Secure-", "")
  39. # RT cookie lifetime is a generous browser-side upper bound; the provider's own RT TTL is the
  40. # real authority (an expired RT -> RefreshExpiredError -> re-login).
  41. _RT_MAX_AGE = 30 * 24 * 60 * 60
  42. _PKCE_MAX_AGE = 10 * 60
  43. # Long enough for one portal round trip / back-button; short enough that a user returning later
  44. # gets a fresh silent attempt rather than a stuck /login.
  45. _SSO_ATTEMPT_MAX_AGE = 60
  46. # Cheap pre-filter: legacy wire forms always contain ``%`` or ``;`` (outside base64url).
  47. _B64URL_RE = re.compile(r"^[A-Za-z0-9_-]+={0,2}$")
  48. def _resolved_name(bare: str, *, use_https: bool, prefix: str) -> str:
  49. """Cookie-prefix variant for the request shape (see module docstring)."""
  50. if not use_https:
  51. return bare
  52. return f"__Secure-{bare}" if prefix else f"__Host-{bare}"
  53. def gateway_cookie_name(bare: str, gateway: str = "") -> str:
  54. """*bare* as the gateway named *gateway* names it; ``""`` (off the gateway's Webapp) keeps *bare*."""
  55. return f"{bare}_{gateway}" if gateway else bare
  56. def _cookie_path(prefix: str) -> str:
  57. """``Path=/hermes`` under a proxy prefix (no leak to sibling apps), else ``/``."""
  58. return prefix if prefix else "/"
  59. def _common_attrs(*, use_https: bool, prefix: str) -> dict:
  60. attrs: dict = {"httponly": True, "samesite": "lax", "path": _cookie_path(prefix)}
  61. if use_https:
  62. attrs["secure"] = True
  63. return attrs
  64. def _pkce_attrs(*, use_https: bool, prefix: str) -> dict:
  65. """Attributes shared by the PKCE set AND clear paths (a shape mismatch
  66. means the browser silently keeps the stale cookie)."""
  67. attrs = _common_attrs(use_https=use_https, prefix=prefix)
  68. if use_https:
  69. attrs["samesite"] = "none"
  70. return attrs
  71. def _set(response: Response, bare: str, value: str, *, max_age: int,
  72. use_https: bool, prefix: str, attrs: dict | None = None) -> None:
  73. response.set_cookie(
  74. _resolved_name(bare, use_https=use_https, prefix=prefix), value, max_age=max_age,
  75. **(attrs if attrs is not None else _common_attrs(use_https=use_https, prefix=prefix)))
  76. def set_session_provider_cookie(
  77. response: Response, *, provider: str, use_https: bool, prefix: str = "", gateway: str = "") -> None:
  78. """Persist the non-secret provider routing hint for token refresh."""
  79. if provider:
  80. _set(response, gateway_cookie_name(SESSION_PROVIDER_COOKIE, gateway), provider, max_age=_RT_MAX_AGE,
  81. use_https=use_https, prefix=prefix)
  82. def set_session_cookies(
  83. response: Response, *, access_token: str, refresh_token: str, access_token_expires_in: int,
  84. use_https: bool, prefix: str = "", provider: str = "", gateway: str = "") -> None:
  85. """``access_token_expires_in`` is seconds (the provider's reported TTL). An empty
  86. ``refresh_token`` means "don't persist the RT cookie" — a literal empty cookie would be dead
  87. state at best, attack surface at worst.
  88. Nous Portal issues a 24h rotating refresh token (hermes #37247); a provider that omits it returns
  89. ``Session.refresh_token == ""`` and we simply don't persist the RT cookie — the session then behaves as
  90. access-token-only until the AT expires. No other branch changes between the two cases.
  91. """
  92. _set(response, gateway_cookie_name(SESSION_AT_COOKIE, gateway), access_token,
  93. max_age=access_token_expires_in, use_https=use_https, prefix=prefix)
  94. if refresh_token:
  95. _set(response, gateway_cookie_name(SESSION_RT_COOKIE, gateway), refresh_token, max_age=_RT_MAX_AGE,
  96. use_https=use_https, prefix=prefix)
  97. set_session_provider_cookie(response, provider=provider, use_https=use_https, prefix=prefix, gateway=gateway)
  98. def _clear_cookie_variants(
  99. response: Response, bare_name: str, *, prefix: str,
  100. https_samesite: Literal["lax", "strict", "none"], bare_attrs: dict) -> None:
  101. """Emit Max-Age=0 deletions for every plausible name variant (the setting request's shape is
  102. unknown). Prefixed names are rejected by the browser unless they carry ``Secure`` (``__Host-``
  103. additionally ``Path=/``), so those deletions always do; the bare deletion mirrors the setter's
  104. shape (``bare_attrs``), which works on both HTTP and HTTPS origins."""
  105. for variant, path in (("__Host-", "/"), ("__Secure-", _cookie_path(prefix))):
  106. response.set_cookie(
  107. f"{variant}{bare_name}", "", max_age=0, path=path, httponly=True,
  108. samesite=https_samesite, secure=True)
  109. response.set_cookie(bare_name, "", max_age=0, **bare_attrs)
  110. def clear_session_cookies(response: Response, *, prefix: str = "", gateway: str = "") -> None:
  111. """Delete the AT, RT and provider cookies (every name variant, active path)."""
  112. bare_attrs = _common_attrs(use_https=False, prefix=prefix)
  113. for name in (SESSION_AT_COOKIE, SESSION_RT_COOKIE, SESSION_PROVIDER_COOKIE):
  114. _clear_cookie_variants(
  115. response, gateway_cookie_name(name, gateway), prefix=prefix, https_samesite="lax",
  116. bare_attrs=bare_attrs)
  117. def encode_pkce_payload(parts: dict[str, str]) -> str:
  118. """Wire value ``base64url(JSON)``, no padding. The urlsafe alphabet is a strict subset of RFC
  119. 6265 cookie-octets, so http.cookies never quotes it (strict proxies such as Go net/http reject
  120. the quoted form) and no value can collide with a delimiter; padding ``=`` would trigger
  121. quoting, the parser restores it."""
  122. raw = json.dumps(parts, separators=(",", ":"), sort_keys=True)
  123. return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
  124. def set_pkce_cookie(response: Response, *, payload: dict[str, str], use_https: bool, prefix: str = "",
  125. gateway: str = "") -> None:
  126. """``payload`` is the segment dict; see module docstring for the SameSite=None rationale."""
  127. _set(response, gateway_cookie_name(PKCE_COOKIE, gateway), encode_pkce_payload(payload), max_age=_PKCE_MAX_AGE,
  128. use_https=use_https, prefix=prefix, attrs=_pkce_attrs(use_https=use_https, prefix=prefix))
  129. def clear_pkce_cookie(response: Response, *, use_https: bool, prefix: str = "", gateway: str = "") -> None:
  130. """Delete every PKCE cookie variant (prefixed ones carry ``Secure; SameSite=None``)."""
  131. _clear_cookie_variants(
  132. response, gateway_cookie_name(PKCE_COOKIE, gateway), prefix=prefix, https_samesite="none",
  133. bare_attrs=_pkce_attrs(use_https=use_https, prefix=prefix))
  134. def _read_with_fallback(request: Request, bare_name: str) -> Optional[str]:
  135. """Try every prefix variant (the reading request may not match the setting request's shape)."""
  136. return next((v for v in (request.cookies.get(f"{p}{bare_name}") for p in _NAME_VARIANTS)
  137. if v is not None), None)
  138. def read_session_cookies(request: Request, gateway: str = "") -> tuple[Optional[str], Optional[str]]:
  139. """Returns (access_token, refresh_token), either may be None."""
  140. return (
  141. _read_with_fallback(request, gateway_cookie_name(SESSION_AT_COOKIE, gateway)),
  142. _read_with_fallback(request, gateway_cookie_name(SESSION_RT_COOKIE, gateway)))
  143. def read_session_provider(request: Request, gateway: str = "") -> Optional[str]:
  144. """Return the provider routing hint associated with the session cookies."""
  145. return _read_with_fallback(request, gateway_cookie_name(SESSION_PROVIDER_COOKIE, gateway))
  146. def set_webapp_signin_cookie(response: Response, *, value: str, use_https: bool, prefix: str = "",
  147. gateway: str = "") -> None:
  148. """Set the Webapp's sign-in binding with the session cookies' Path, SameSite and Secure policy, for
  149. as long as a refresh token cookie lasts. *gateway* names the gateway it binds to."""
  150. _set(response, gateway_cookie_name(WEBAPP_SIGNIN_COOKIE, gateway), value, max_age=_RT_MAX_AGE,
  151. use_https=use_https, prefix=prefix)
  152. def read_webapp_signin_cookie(request: Request, gateway: str = "") -> Optional[str]:
  153. return _read_with_fallback(request, gateway_cookie_name(WEBAPP_SIGNIN_COOKIE, gateway))
  154. def read_pkce_cookie(request: Request, gateway: str = "") -> Optional[str]:
  155. return _read_with_fallback(request, gateway_cookie_name(PKCE_COOKIE, gateway))
  156. def parse_pkce_payload(raw: str) -> dict[str, str]:
  157. """Inverse of :func:`encode_pkce_payload`. EVERY reader must go through this — reading the raw
  158. wire value parses zero segments and silently disables the check it feeds (provider dispatch,
  159. CSRF state, broker binding). Compatibility ladder for cookies minted by an older server
  160. mid-upgrade: 1. base64url(JSON); 2. flat form with raw ``;`` delimiters, split WITHOUT
  161. unquoting (the ``next`` segment carries its own URL-encoding); 3. URL-encoded flat form,
  162. unquote once then split. A NEW cookie hitting an OLD server fails the state check.
  163. 1. **base64url(JSON)** (current): the wire value is pure urlsafe base64 that decodes to a JSON object.
  164. Legacy forms can never match — they always contain ``%`` (URL-encoded, #99176) or a raw ``;`` (oldest
  165. flat form), both outside the base64url alphabet. Split as-is WITHOUT unquoting the payload — the
  166. ``next`` segment carries its own single URL-encoding, and unquoting here would turn a ``%3B`` inside it
  167. into a bogus delimiter and truncate the post-login target. Neither newer format can contain a raw ``;``.
  168. """
  169. if _B64URL_RE.match(raw):
  170. try:
  171. padded = raw + "=" * (-len(raw) % 4)
  172. decoded = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
  173. except (binascii.Error, ValueError, UnicodeDecodeError):
  174. decoded = None
  175. if isinstance(decoded, dict):
  176. return {str(k): str(v) for k, v in decoded.items()}
  177. flat = raw if ";" in raw else unquote(raw)
  178. return dict(seg.split("=", 1) for seg in flat.split(";") if "=" in seg)
  179. def set_sso_attempt_cookie(response: Response, *, use_https: bool, prefix: str = "", gateway: str = "") -> None:
  180. """Set the auto-SSO loop-guard marker; only its presence matters."""
  181. _set(response, gateway_cookie_name(SSO_ATTEMPT_COOKIE, gateway), "1", max_age=_SSO_ATTEMPT_MAX_AGE,
  182. use_https=use_https, prefix=prefix)
  183. def read_sso_attempt_cookie(request: Request, gateway: str = "") -> Optional[str]:
  184. """Return the auto-SSO marker value if present (any variant), else None."""
  185. return _read_with_fallback(request, gateway_cookie_name(SSO_ATTEMPT_COOKIE, gateway))
  186. def clear_sso_attempt_cookie(response: Response, *, prefix: str = "", gateway: str = "") -> None:
  187. """Delete the auto-SSO marker (every variant) so it never suppresses a later silent attempt."""
  188. _clear_cookie_variants(
  189. response, gateway_cookie_name(SSO_ATTEMPT_COOKIE, gateway), prefix=prefix, https_samesite="lax",
  190. bare_attrs=_common_attrs(use_https=False, prefix=prefix))
  191. def detect_https(request: Request) -> bool:
  192. """``Secure`` flag decision (honours ``X-Forwarded-Proto`` under uvicorn ``proxy_headers``)."""
  193. return request.url.scheme == "https"