__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. """DrainSecretProvider — shared-bearer-secret auth for the drain-control endpoint.
  2. Non-interactive token capability of the ``DashboardAuthProvider`` ABC (``verify_token`` +
  3. the ``token_auth`` middleware seam): ``nous-account-service`` provisions a per-agent unique
  4. secret (``HERMES_DASHBOARD_DRAIN_SECRET``, env-only — it is a credential); an inbound bearer
  5. is compared constant-time and vouched for as the ``drain-control`` principal. Fail-CLOSED
  6. entropy gate at registration (length, distinct chars, Shannon bits); interactive ABC methods
  7. raise. Knobs ``scope`` / ``min_secret_chars`` live under ``dashboard.drain_auth``.
  8. """
  9. from __future__ import annotations
  10. import hmac
  11. import logging
  12. import math
  13. import os
  14. from collections import Counter
  15. from typing import Optional
  16. from hermes_cli.dashboard_auth import DashboardAuthProvider, Session, TokenPrincipal
  17. from plugins.dashboard_auth._shared import NonInteractiveMixin, SkipRegistration, load_config_section, register_provider
  18. logger = logging.getLogger(__name__)
  19. _TAG = "dashboard-auth-drain"
  20. # token_urlsafe(32) produces exactly 43 chars, so a correctly-provisioned
  21. # secret clears the default bar exactly.
  22. _DEFAULT_MIN_SECRET_CHARS = 43
  23. # Rejects degenerate values like "aaaa..." that are long but trivially low-entropy.
  24. _MIN_DISTINCT_CHARS = 16
  25. # Distribution-aware second guard on top of length + distinct-count.
  26. _MIN_SHANNON_BITS = 128.0
  27. # Kept here (not imported from web_server) to avoid a heavy import at plugin load.
  28. DRAIN_ROUTE_PATH = "/api/gateway/drain"
  29. LAST_SKIP_REASON: str = ""
  30. def _shannon_bits(value: str) -> float:
  31. """Total Shannon entropy (bits) of ``value`` over its character distribution."""
  32. if not value:
  33. return 0.0
  34. n = len(value)
  35. per_char = -sum((c / n) * math.log2(c / n) for c in Counter(value).values())
  36. return per_char * n
  37. def assess_secret_strength(secret: str, *, min_chars: int = _DEFAULT_MIN_SECRET_CHARS) -> Optional[str]:
  38. """Human-readable rejection reason if ``secret`` is too weak, else ``None``. Checks, in
  39. order: length >= ``min_chars``, distinct chars >= ``_MIN_DISTINCT_CHARS``, Shannon
  40. entropy >= ``_MIN_SHANNON_BITS``."""
  41. if not secret:
  42. return "secret is empty"
  43. if len(secret) < min_chars:
  44. return (
  45. f"secret too short: {len(secret)} chars (need >= {min_chars}; "
  46. "use a >=256-bit value, e.g. `python -c \"import secrets; "
  47. "print(secrets.token_urlsafe(32))\"`)")
  48. distinct = len(set(secret))
  49. if distinct < _MIN_DISTINCT_CHARS:
  50. return f"secret has only {distinct} distinct characters (need >= {_MIN_DISTINCT_CHARS}); looks structured/low-entropy"
  51. bits = _shannon_bits(secret)
  52. if bits < _MIN_SHANNON_BITS:
  53. return f"secret entropy too low: {bits:.0f} bits (need >= {_MIN_SHANNON_BITS:.0f}); looks structured/repeated"
  54. return None
  55. class DrainSecretProvider(NonInteractiveMixin, DashboardAuthProvider):
  56. """Non-interactive shared-bearer-secret provider for drain control."""
  57. name = "drain-secret"
  58. display_name = "Drain Control (service credential)"
  59. supports_token = True
  60. supports_session = False
  61. _NOT_INTERACTIVE = "DrainSecretProvider is a non-interactive service credential."
  62. _NO_START_LOGIN = "DrainSecretProvider is a non-interactive service credential; there is no login flow."
  63. def __init__(self, *, secret: str, scope: str = "drain") -> None:
  64. # Defence in depth: construction enforces the entropy bar too, so a
  65. # caller bypassing register() still can't build a weak provider.
  66. reason = assess_secret_strength(secret)
  67. if reason is not None:
  68. raise ValueError(f"drain secret rejected: {reason}")
  69. self._secret = secret
  70. self._scope = scope or "drain"
  71. # ---- token capability (the only thing this provider implements) --------
  72. def verify_token(self, *, token: str) -> Optional[TokenPrincipal]:
  73. """Constant-time compare; ``drain-control`` principal on match, else
  74. ``None`` so the generic seam falls through / fails closed."""
  75. if token and hmac.compare_digest(token.encode("utf-8"), self._secret.encode("utf-8")):
  76. return TokenPrincipal(principal="drain-control", provider=self.name, scopes=(self._scope,))
  77. return None
  78. # ---- interactive methods: unsupported (service credential only) --------
  79. def verify_session(self, *, access_token: str) -> Optional[Session]:
  80. # Never mints a Session, so never recognises a cookie. Return None (don't raise)
  81. # so it stacks harmlessly in the cookie-verify loop.
  82. return None
  83. def refresh_session(self, *, refresh_token: str) -> Session:
  84. raise NotImplementedError(self._NOT_INTERACTIVE)
  85. def revoke_session(self, *, refresh_token: str) -> None:
  86. return None
  87. # ---- Plugin entry point ----
  88. def _load_config_drain_auth_section() -> dict:
  89. return load_config_section(logger, _TAG, "dashboard", "drain_auth")
  90. def _settings() -> dict:
  91. """Resolve DrainSecretProvider kwargs from env/config; raises ``SkipRegistration``."""
  92. secret = os.environ.get("HERMES_DASHBOARD_DRAIN_SECRET", "").strip()
  93. if not secret:
  94. raise SkipRegistration(
  95. "HERMES_DASHBOARD_DRAIN_SECRET is not set. Set a per-agent >=256-bit secret "
  96. "(e.g. `python -c \"import secrets; print(secrets.token_urlsafe(32))\"`) to enable "
  97. "NAS-driven drain coordination; leave it unset to disable the drain endpoint.")
  98. section = _load_config_drain_auth_section()
  99. scope = str(section.get("scope", "drain") or "drain").strip() or "drain"
  100. try:
  101. min_chars = int(section.get("min_secret_chars", _DEFAULT_MIN_SECRET_CHARS))
  102. except (TypeError, ValueError):
  103. min_chars = _DEFAULT_MIN_SECRET_CHARS
  104. reason = assess_secret_strength(secret, min_chars=min_chars)
  105. if reason is not None:
  106. raise SkipRegistration(
  107. f"HERMES_DASHBOARD_DRAIN_SECRET rejected — {reason}. The drain endpoint stays disabled (fail-closed).",
  108. level="warning")
  109. return {"secret": secret, "scope": scope}
  110. def register(ctx) -> None:
  111. """Register ``DrainSecretProvider`` when a strong secret is set; no-op (records a skip
  112. reason) when ``HERMES_DASHBOARD_DRAIN_SECRET`` is unset or fails the entropy gate. On
  113. success also registers the drain route as token-authable via the generic seam."""
  114. global LAST_SKIP_REASON
  115. LAST_SKIP_REASON = ""
  116. kwargs, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, DrainSecretProvider, _settings)
  117. if kwargs is None:
  118. return
  119. # Opt the drain endpoint into the token-auth seam so the interactive cookie gate
  120. # doesn't bounce NAS's bearer call.
  121. try:
  122. from hermes_cli.dashboard_auth.token_auth import register_token_route
  123. register_token_route(DRAIN_ROUTE_PATH)
  124. except Exception as exc:
  125. logger.warning("dashboard-auth-drain: could not register token route %s: %s", DRAIN_ROUTE_PATH, exc)
  126. logger.info(
  127. "dashboard-auth-drain: registered drain service-credential provider (scope=%s, route=%s)",
  128. kwargs["scope"], DRAIN_ROUTE_PATH)