token_auth.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Route-agnostic non-interactive (bearer-token) auth seam for the dashboard.
  2. Any machine-credential provider plugs in here. A route opts in by registering its exact path via
  3. :func:`register_token_route`; only registered paths are token-authable, so the auth surface of
  4. existing routes never widens. :func:`token_auth_middleware` runs OUTERMOST (installed last) and
  5. owns the decision for a token route: a recognised token attaches ``request.state.token_principal``
  6. + ``token_authenticated`` (the cookie gates honour that flag and never bounce to /login);
  7. otherwise 401, or 503 when a provider's backing store was unreachable. Fails closed.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import threading
  12. from typing import Awaitable, Callable, Optional, Tuple
  13. from fastapi import Request
  14. from fastapi.responses import JSONResponse, Response
  15. from hermes_cli.dashboard_auth import list_token_providers
  16. from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log
  17. from hermes_cli.dashboard_auth.base import ProviderError, TokenPrincipal
  18. from hermes_cli.dashboard_auth.request_utils import (
  19. client_ip as _client_ip, extract_bearer as extract_bearer_token, unreachable_response)
  20. _log = logging.getLogger(__name__)
  21. _token_routes: set[str] = set() # exact paths that accept bearer-token auth
  22. _lock = threading.Lock()
  23. def register_token_route(path: str) -> None:
  24. """Mark ``path`` (exact match) as token-authable. Idempotent; does NOT make the route public."""
  25. with _lock:
  26. _token_routes.add(path)
  27. def is_token_route(path: str) -> bool:
  28. """True if ``path`` was registered as token-authable (exact match)."""
  29. with _lock:
  30. return path in _token_routes
  31. def clear_token_routes() -> None:
  32. """Test-only: drop all registered token routes."""
  33. with _lock:
  34. _token_routes.clear()
  35. def authenticate_token(request: Request) -> tuple[Optional[TokenPrincipal], Optional[str]]:
  36. """Try every token provider against the request's bearer token. Returns ``(principal, None)``
  37. on success; ``(None, None)`` for no token or no recogniser (401); ``(None, name)`` when no
  38. provider accepted it AND at least one was unreachable (caller surfaces 503). Never raises."""
  39. token = extract_bearer_token(request)
  40. if not token:
  41. return None, None
  42. unreachable: Optional[str] = None
  43. for provider in list_token_providers():
  44. try:
  45. principal = provider.verify_token(token=token)
  46. except ProviderError as e:
  47. _log.warning("dashboard-auth: token provider %r unreachable during verify: %s",
  48. provider.name, e)
  49. if unreachable is None:
  50. unreachable = provider.name
  51. continue
  52. except Exception as e:
  53. _log.warning("dashboard-auth: token provider %r raised during verify: %s",
  54. provider.name, e)
  55. continue
  56. if principal is not None:
  57. return principal, None
  58. return None, unreachable
  59. async def token_auth_middleware(
  60. request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
  61. """Pass-through for unregistered paths; for a token route, valid token -> attach principal +
  62. flag, unreachable -> 503, else 401."""
  63. path = request.url.path
  64. if not is_token_route(path):
  65. return await call_next(request)
  66. principal, unreachable = authenticate_token(request)
  67. if principal is not None:
  68. request.state.token_principal = principal
  69. request.state.token_authenticated = True
  70. return await call_next(request)
  71. if unreachable:
  72. audit_log(
  73. AuditEvent.TOKEN_AUTH_FAILURE, provider=unreachable, reason="provider_unreachable",
  74. path=path, ip=_client_ip(request))
  75. return unreachable_response(unreachable)
  76. audit_log(
  77. AuditEvent.TOKEN_AUTH_FAILURE, reason="no_provider_recognises_token", path=path,
  78. ip=_client_ip(request))
  79. return JSONResponse({"error": "unauthenticated", "detail": "Unauthorized"}, status_code=401)