__init__.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """NousDashboardAuthProvider — Nous Portal OAuth (authorization-code + PKCE).
  2. Implements ``nous-account-service/docs/agent-dashboard-oauth-contract.md``; registers only
  3. when a client_id (``dashboard.oauth.client_id`` / ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``, shape
  4. ``agent:{instance_id}``) is configured. Access tokens are RS256 JWTs verified against the
  5. Portal JWKS with ``aud`` = bare client_id. Portal issues a 24h *rotating* refresh token with
  6. reuse detection: the middleware MUST persist ``Session.refresh_token`` back to the cookie on
  7. every refresh or the next refresh replays a rotated token and revokes the whole session.
  8. While the gateway serves the Webapp, its sign-in uses the client Web Access registered for the
  9. Webapp instead of the configured one (``hermes_cli.dashboard_auth.listener_client``).
  10. """
  11. from __future__ import annotations
  12. import logging
  13. from typing import Any, Callable, Optional
  14. from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session, listener_client
  15. from plugins.dashboard_auth._shared import (
  16. DEFAULT_TOKEN_LEEWAY_SECONDS,
  17. JwtOAuthProvider,
  18. SkipRegistration,
  19. exchange_token,
  20. load_config_section,
  21. parse_leeway,
  22. pkce_login_start,
  23. refresh_token_from,
  24. register_provider,
  25. resolve_env_or_cfg,
  26. session_from_claims,
  27. validate_redirect_uri,
  28. verify_jwt)
  29. logger = logging.getLogger(__name__)
  30. _TAG = "dashboard-auth-nous"
  31. _DEFAULT_PORTAL_URL = "https://portal.nousresearch.com"
  32. _SCOPE = "agent_dashboard:access" # contract C3
  33. _EXPECTED_CONTRACT_VERSION = 1 # contract C11
  34. LAST_SKIP_REASON: str = "" # cleared on every register() so restarts don't leak stale reasons
  35. class NousDashboardAuthProvider(JwtOAuthProvider):
  36. """Nous Portal OAuth via authorization-code + PKCE (S256)."""
  37. name = "nous"
  38. display_name = "Nous Research"
  39. def __init__(self, *, client_id: str, portal_url: str, token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS) -> None:
  40. # Defense-in-depth: register() filters too, but a malformed id must never construct a provider.
  41. if not client_id.startswith("agent:"):
  42. raise ValueError(f"client_id must match contract shape 'agent:{{instance_id}}', got {client_id!r}")
  43. self._client_id = client_id
  44. self._agent_instance_id = client_id[len("agent:") :]
  45. self._portal_url = portal_url.rstrip("/")
  46. # Clock-skew tolerance (seconds) for the access token's exp/nbf/iat claims;
  47. # the default absorbs Portal/host clock skew (#47815), 0 restores strict mode.
  48. self._token_leeway = parse_leeway(token_leeway)
  49. self._jwks_url = f"{self._portal_url}/.well-known/jwks.json"
  50. self._authorize_url = f"{self._portal_url}/oauth/authorize"
  51. self._token_url = f"{self._portal_url}/api/oauth/token"
  52. self._jwks_client: Any = None # lazily built (crypto import cost)
  53. def start_login(self, *, redirect_uri: str) -> LoginStart:
  54. validate_redirect_uri(redirect_uri)
  55. return pkce_login_start(self._authorize_url, client_id=self._client_id, scope=_SCOPE, redirect_uri=redirect_uri)
  56. def revoke_session(self, *, refresh_token: str) -> None:
  57. # Portal exposes no token-endpoint revocation grant; logout is client-side cookie
  58. # clearing and the RT expires within its 24h TTL.
  59. return None
  60. # ---- JwtOAuthProvider hooks -------------------------------------------
  61. def _jwks_uri(self) -> str:
  62. return self._jwks_url
  63. def _refresh_request(self, refresh_token: str) -> tuple[dict[str, str], Optional[dict[str, str]]]:
  64. # The RT goes in BOTH the body (Portal's request schema requires it) and the
  65. # ``x-nous-refresh-token`` header (Portal reconciles the two and keeps the value
  66. # out of body access logs). Header-only → 400.
  67. return (
  68. {"grant_type": "refresh_token", "client_id": self._client_id, "refresh_token": refresh_token},
  69. {"x-nous-refresh-token": refresh_token})
  70. def _grant(
  71. self, data: dict[str, str], *, bad_request_exc: type[Exception], headers: Optional[dict[str, str]] = None,
  72. previous_refresh_token: str = "",
  73. ) -> Session:
  74. access_token, payload = exchange_token(
  75. self._token_url, data, headers=headers, bad_request_exc=bad_request_exc,
  76. idp="Portal", endpoint="Portal token endpoint", token_key="access_token",
  77. missing_msg="Portal token response missing access_token")
  78. # Rotating RT the caller MUST persist back to the cookie.
  79. return self._session(access_token, refresh_token_from(payload), self._claims_for(access_token))
  80. def _claims_for(self, access_token: str) -> dict[str, Any]:
  81. claims = verify_jwt(
  82. access_token, self._get_jwks_client(), algorithms=["RS256"],
  83. audience=self._client_id, # contract C2: bare client_id
  84. issuer=self._portal_url, label="access token", leeway=self._token_leeway)
  85. # Contract C9: agent_instance_id is "should" not "must" — tolerated when absent
  86. # (the aud check already binds the token to this instance).
  87. token_instance_id = claims.get("agent_instance_id")
  88. if token_instance_id is not None and token_instance_id != self._agent_instance_id:
  89. raise ProviderError(
  90. f"agent_instance_id mismatch: token={token_instance_id!r} vs configured={self._agent_instance_id!r}")
  91. contract_version = claims.get("oauth_contract_version")
  92. if contract_version is None:
  93. logger.warning(
  94. "Nous Portal token missing oauth_contract_version claim (contract says it should be %d); proceeding anyway.",
  95. _EXPECTED_CONTRACT_VERSION)
  96. elif contract_version != _EXPECTED_CONTRACT_VERSION:
  97. raise ProviderError(
  98. f"unsupported oauth_contract_version={contract_version!r}, expected {_EXPECTED_CONTRACT_VERSION}")
  99. return claims
  100. def _session(self, access_token: str, refresh_token: str, claims: dict[str, Any]) -> Session:
  101. # Contract C4: no email / display_name in tokens.
  102. return session_from_claims(
  103. self.name, claims, access_token=access_token, refresh_token=refresh_token, org_id=str(claims.get("org_id") or ""))
  104. # ---- Plugin entry point ----
  105. def _load_config_oauth_section() -> dict:
  106. return load_config_section(logger, _TAG, "dashboard", "oauth")
  107. def _settings() -> dict:
  108. """Resolve NousDashboardAuthProvider kwargs; the skip reason names BOTH configuration surfaces."""
  109. section = _load_config_oauth_section()
  110. own = listener_client.current() # a plugin reload while the listener uses its own client keeps it
  111. if own is not None:
  112. return {"client_id": own[0], "portal_url": own[1],
  113. "token_leeway": parse_leeway(section.get("token_leeway"))}
  114. client_id = resolve_env_or_cfg("HERMES_DASHBOARD_OAUTH_CLIENT_ID", section.get("client_id", ""))
  115. portal_url = resolve_env_or_cfg("HERMES_DASHBOARD_PORTAL_URL", section.get("portal_url", "")) or _DEFAULT_PORTAL_URL
  116. if not client_id:
  117. raise SkipRegistration(
  118. "HERMES_DASHBOARD_OAUTH_CLIENT_ID is not set (and dashboard.oauth.client_id "
  119. "in config.yaml is empty). The Nous Portal provisions this env var (shape "
  120. "'agent:{instance_id}') when it deploys a Hermes Agent instance — set it to "
  121. "your provisioned client id (either as an env var or under "
  122. "dashboard.oauth.client_id in config.yaml), or pass --insecure to skip the "
  123. "OAuth gate entirely.")
  124. if not client_id.startswith("agent:"):
  125. raise SkipRegistration(
  126. f"HERMES_DASHBOARD_OAUTH_CLIENT_ID={client_id!r} doesn't match the contract "
  127. f"shape 'agent:{{instance_id}}'. The Nous Portal provisions this value at deploy "
  128. f"time; check your Fly app's secrets or override with the value from the Portal admin UI.",
  129. level="warning")
  130. return {"client_id": client_id, "portal_url": portal_url,
  131. # Clock-skew tolerance for access-token exp/nbf/iat (config.yaml only; default 60s, 0 = strict).
  132. "token_leeway": parse_leeway(section.get("token_leeway"))}
  133. def register(ctx) -> None:
  134. """Register ``NousDashboardAuthProvider`` when a client_id is configured."""
  135. global LAST_SKIP_REASON
  136. listener_client.offer(_swap_provider)
  137. LAST_SKIP_REASON = ""
  138. kwargs, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, NousDashboardAuthProvider, _settings)
  139. if kwargs is not None:
  140. logger.info(
  141. "dashboard-auth-nous: registered provider (client_id=%s, portal=%s, token_leeway=%ss)",
  142. kwargs["client_id"], kwargs["portal_url"], kwargs["token_leeway"])
  143. def _swap_provider() -> Callable[[], None]:
  144. """Put a provider on the listener's own client (``listener_client.use`` has made it current) in
  145. place of the registered one; the returned undo puts that one, or none, back."""
  146. from hermes_cli.dashboard_auth.registry import (
  147. register_global_provider, restore_registration, snapshot_registration)
  148. previous = snapshot_registration(NousDashboardAuthProvider.name)
  149. provider = NousDashboardAuthProvider(**_settings())
  150. register_global_provider(provider)
  151. return lambda: restore_registration(NousDashboardAuthProvider.name, provider, previous)