registry.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. """Module-level registry for DashboardAuthProvider instances. Plugins call ``register_provider``
  2. via the plugin context hook at startup; the auth gate iterates ``list_providers()`` and uses
  3. ``get_provider`` to dispatch on the session's ``provider`` field."""
  4. from __future__ import annotations
  5. import logging
  6. import threading
  7. from typing import List, Optional
  8. from hermes_constants import hermes_home_key, normalize_scope
  9. from hermes_cli.dashboard_auth.base import DashboardAuthProvider, assert_protocol_compliance
  10. _log = logging.getLogger(__name__)
  11. _lock = threading.Lock()
  12. _providers: dict[str, DashboardAuthProvider] = {}
  13. _scoped_providers: dict[str, dict[str, DashboardAuthProvider]] = {}
  14. def _merged(scope: Optional[str] = None) -> dict[str, DashboardAuthProvider]:
  15. providers = dict(_providers)
  16. providers.update(_scoped_providers.get(hermes_home_key(scope), {}))
  17. return providers
  18. def _target(scope: Optional[str], *, create: bool) -> dict[str, DashboardAuthProvider]:
  19. """Global map for ``scope is None``, else that scope's overlay."""
  20. if scope is None:
  21. return _providers
  22. return _scoped_providers.setdefault(scope, {}) if create else _scoped_providers.get(scope, {})
  23. def _log_registered(kind: str, provider: DashboardAuthProvider) -> None:
  24. _log.info("dashboard-auth: registered %s%r (%s)", kind, provider.name, provider.display_name)
  25. def register_provider(provider: DashboardAuthProvider, *, scope: Optional[str] = None) -> None:
  26. """Raises ``TypeError`` on protocol violation, ``ValueError`` on a duplicate name."""
  27. assert_protocol_compliance(type(provider))
  28. with _lock:
  29. scope = normalize_scope(scope)
  30. target = _target(scope, create=True)
  31. effective = target if scope is None else _merged(scope)
  32. if provider.name in effective:
  33. raise ValueError(f"dashboard-auth provider already registered: {provider.name!r}")
  34. target[provider.name] = provider
  35. _log_registered("provider ", provider)
  36. def get_provider(name: str, *, scope: Optional[str] = None) -> Optional[DashboardAuthProvider]:
  37. """Return the registered provider for ``name``, or None if unknown."""
  38. with _lock:
  39. return _merged(scope).get(name)
  40. def snapshot_registration(
  41. name: str, *, scope: Optional[str] = None) -> Optional[DashboardAuthProvider]:
  42. with _lock:
  43. scope = normalize_scope(scope)
  44. return _target(scope, create=False).get(name)
  45. def restore_registration(
  46. name: str, current: DashboardAuthProvider, previous: Optional[DashboardAuthProvider],
  47. *, scope: Optional[str] = None) -> bool:
  48. """Restore a host-owned provider registration if it is still current."""
  49. with _lock:
  50. scope = normalize_scope(scope)
  51. target = _target(scope, create=True)
  52. if target.get(name) is not current:
  53. return False
  54. if previous is None:
  55. target.pop(name, None)
  56. else:
  57. target[name] = previous
  58. if scope is not None and not target:
  59. _scoped_providers.pop(scope, None)
  60. return True
  61. def list_providers(*, scope: Optional[str] = None) -> list[DashboardAuthProvider]:
  62. """All registered providers, in registration order."""
  63. with _lock:
  64. return list(_merged(scope).values())
  65. def list_token_providers() -> list[DashboardAuthProvider]:
  66. """Providers with ``supports_token`` True, in registration order. The ``token_auth`` seam
  67. consults only these, so OAuth/password-only providers are never asked to ``verify_token``;
  68. empty => a token-authable route fails closed (401)."""
  69. return [p for p in list_providers() if getattr(p, "supports_token", False)]
  70. def list_session_providers() -> list[DashboardAuthProvider]:
  71. """Providers with ``supports_session`` True (interactive cookie sessions); the login page,
  72. /auth/login and the gate's verify/refresh loops use only these."""
  73. return [p for p in list_providers() if getattr(p, "supports_session", True)]
  74. def list_interactive_providers() -> list[DashboardAuthProvider]:
  75. """Session providers that offer a sign-in flow (``interactive_login`` True). Every login
  76. surface — the login page, ``/api/auth/providers``, auto-SSO, native authorize selection and
  77. chooser, the ``native_pkce`` advertisement — uses this; the verify/refresh loops keep
  78. :func:`list_session_providers`, so a provisioned-credential provider still authenticates."""
  79. return [p for p in list_session_providers() if getattr(p, "interactive_login", True)]
  80. def register_global_provider(provider: DashboardAuthProvider) -> None:
  81. """Register a host-owned provider in the process-global slot (upsert). The registry is shared
  82. across every profile one dashboard process serves, so these outlive any per-home plugin
  83. manager: always targets ``_providers`` (never a per-home overlay) and *replaces* a same-name
  84. entry instead of raising, so a forced plugin re-discovery (e.g. after a password change)
  85. rotates the provider in place. Pairs with ``unregister_global_provider``.
  86. Pairs with ``unregister_global_provider`` for teardown of the exact object still current (#91701).
  87. """
  88. assert_protocol_compliance(type(provider))
  89. with _lock:
  90. _providers[provider.name] = provider
  91. _log_registered("global provider ", provider)
  92. def unregister_global_provider(name: str, provider: DashboardAuthProvider) -> bool:
  93. """Remove a global registration if ``provider`` is still current (a stale handle whose
  94. provider was already replaced never clears the live one)."""
  95. with _lock:
  96. if _providers.get(name) is provider:
  97. _providers.pop(name, None)
  98. return True
  99. return False
  100. def clear_providers() -> None:
  101. """Test-only: drop all registrations."""
  102. with _lock:
  103. _providers.clear()
  104. _scoped_providers.clear()