"""NousDashboardAuthProvider — Nous Portal OAuth (authorization-code + PKCE). Implements ``nous-account-service/docs/agent-dashboard-oauth-contract.md``. Bundled and auto-loaded, but only registers when a client_id is configured, so loopback / ``--insecure`` operators are unaffected. Configuration (env wins over config.yaml when set non-empty; an empty env value is treated as unset so a provisioned-but-blank Fly secret can't shadow config):: dashboard: oauth: client_id: agent:{agent_instance_id} # required portal_url: https://portal.example # optional HERMES_DASHBOARD_OAUTH_CLIENT_ID — shape ``agent:{agent_instance_id}`` HERMES_DASHBOARD_PORTAL_URL — default https://portal.nousresearch.com Contract points encoded here: - client_id is per-instance; its suffix is cross-checked against the token's ``agent_instance_id`` claim (defense-in-depth). - scope is ``agent_dashboard:access`` only; audience is the bare client_id. - access tokens are RS256 JWTs verified against ``/.well-known/jwks.json`` (JWKS cached 5 minutes). - Portal issues a 24h *rotating* refresh token with reuse detection: the middleware MUST persist ``Session.refresh_token`` back to the cookie on every refresh, or the next refresh replays a rotated token and (outside a 60s grace) trips reuse-detection, revoking the whole session. A 400 on refresh (expired / revoked / reuse-detected) → ``RefreshExpiredError`` → re-login. - ``oauth_contract_version``: missing → warn + proceed; ``!= 1`` → refuse. ``LAST_SKIP_REASON`` is read by the gate's fail-closed branch to surface a specific operator message when the plugin loads but declines to register. """ from __future__ import annotations import logging from typing import Any, Dict, Optional from hermes_cli.dashboard_auth import ( DashboardAuthProvider, InvalidCodeError, LoginStart, ProviderError, RefreshExpiredError, Session, ) from plugins.dashboard_auth._shared import ( exchange_token, load_config_section, make_jwks_client, pkce_login_start, refresh_token_from, resolve_env_or_cfg, session_from_claims, validate_redirect_uri, verify_jwt, ) logger = logging.getLogger(__name__) _DEFAULT_PORTAL_URL = "https://portal.nousresearch.com" _SCOPE = "agent_dashboard:access" # contract C3 _EXPECTED_CONTRACT_VERSION = 1 # contract C11 LAST_SKIP_REASON: str = "" # cleared on every register() so restarts don't leak stale reasons class NousDashboardAuthProvider(DashboardAuthProvider): """Nous Portal OAuth via authorization-code + PKCE (S256).""" name = "nous" display_name = "Nous Research" def __init__(self, *, client_id: str, portal_url: str) -> None: # Defense-in-depth: register() filters too, but a malformed id must # never construct a provider. if not client_id.startswith("agent:"): raise ValueError(f"client_id must match contract shape 'agent:{{instance_id}}', got {client_id!r}") self._client_id = client_id self._agent_instance_id = client_id[len("agent:") :] self._portal_url = portal_url.rstrip("/") self._jwks_url = f"{self._portal_url}/.well-known/jwks.json" self._authorize_url = f"{self._portal_url}/oauth/authorize" self._token_url = f"{self._portal_url}/api/oauth/token" self._jwks_client: Any = None # lazily built (crypto import cost) # ---- public API (DashboardAuthProvider) ------------------------------- def start_login(self, *, redirect_uri: str) -> LoginStart: validate_redirect_uri(redirect_uri) return pkce_login_start( self._authorize_url, client_id=self._client_id, scope=_SCOPE, redirect_uri=redirect_uri ) def complete_login( self, *, code: str, state: str, code_verifier: str, redirect_uri: str ) -> Session: # ``state`` is verified by the auth-route layer; Portal doesn't # re-check it at the token endpoint. return self._token_grant( { "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri, "client_id": self._client_id, "code_verifier": code_verifier, }, bad_request_exc=InvalidCodeError, ) def refresh_session(self, *, refresh_token: str) -> Session: if not refresh_token: raise RefreshExpiredError("no refresh token present in session") # The RT goes in BOTH the body (Portal's request schema requires it) # and the ``x-nous-refresh-token`` header (Portal reconciles the two # and keeps the value out of body access logs). Header-only → 400. return self._token_grant( { "grant_type": "refresh_token", "client_id": self._client_id, "refresh_token": refresh_token, }, headers={"x-nous-refresh-token": refresh_token}, bad_request_exc=RefreshExpiredError, ) def verify_session(self, *, access_token: str) -> Optional[Session]: # None on expiry/invalidity (middleware then tries refresh); a # ProviderError (JWKS unreachable) bubbles up so middleware emits 503. try: claims = self._verify_jwt(access_token) except InvalidCodeError: return None return self._session(access_token, "", claims) def revoke_session(self, *, refresh_token: str) -> None: # Portal exposes no token-endpoint revocation grant; logout is # client-side cookie clearing and the RT expires within its 24h TTL. return None # ---- internals -------------------------------------------------------- def _token_grant( self, data: Dict[str, str], *, bad_request_exc: type[Exception], headers: Optional[Dict[str, str]] = None, ) -> Session: access_token, payload = exchange_token( self._token_url, data, headers=headers, bad_request_exc=bad_request_exc, idp="Portal", endpoint="Portal token endpoint", token_key="access_token", missing_msg="Portal token response missing access_token", ) # Rotating RT the caller MUST persist back to the cookie. return self._session(access_token, refresh_token_from(payload), self._verify_jwt(access_token)) def _get_jwks_client(self) -> Any: if self._jwks_client is None: self._jwks_client = make_jwks_client(self._jwks_url) return self._jwks_client def _verify_jwt(self, access_token: str) -> Dict[str, Any]: claims = verify_jwt( access_token, self._get_jwks_client(), algorithms=["RS256"], audience=self._client_id, # contract C2: bare client_id issuer=self._portal_url, label="access token", ) # Contract C9: agent_instance_id is "should" not "must" — tolerated # when absent (the aud check already binds the token to this instance). token_instance_id = claims.get("agent_instance_id") if token_instance_id is not None and token_instance_id != self._agent_instance_id: raise ProviderError( f"agent_instance_id mismatch: token={token_instance_id!r} " f"vs configured={self._agent_instance_id!r}" ) contract_version = claims.get("oauth_contract_version") if contract_version is None: logger.warning( "Nous Portal token missing oauth_contract_version claim " "(contract says it should be %d); proceeding anyway.", _EXPECTED_CONTRACT_VERSION, ) elif contract_version != _EXPECTED_CONTRACT_VERSION: raise ProviderError( f"unsupported oauth_contract_version={contract_version!r}, " f"expected {_EXPECTED_CONTRACT_VERSION}" ) return claims def _session(self, access_token: str, refresh_token: str, claims: Dict[str, Any]) -> Session: # Contract C4: no email / display_name in tokens. return session_from_claims( self.name, claims, access_token=access_token, refresh_token=refresh_token, org_id=str(claims.get("org_id") or ""), ) # ---- Plugin entry point ---- def _load_config_oauth_section() -> dict: return load_config_section(logger, "dashboard-auth-nous", "dashboard", "oauth") def register(ctx) -> None: """Register ``NousDashboardAuthProvider`` when a client_id is configured. On skip, writes a reason naming BOTH configuration surfaces to :data:`LAST_SKIP_REASON` for the gate's fail-closed error message. """ global LAST_SKIP_REASON LAST_SKIP_REASON = "" section = _load_config_oauth_section() client_id = resolve_env_or_cfg("HERMES_DASHBOARD_OAUTH_CLIENT_ID", section.get("client_id", "")) portal_url = ( resolve_env_or_cfg("HERMES_DASHBOARD_PORTAL_URL", section.get("portal_url", "")) or _DEFAULT_PORTAL_URL ) if not client_id: LAST_SKIP_REASON = ( "HERMES_DASHBOARD_OAUTH_CLIENT_ID is not set (and dashboard.oauth.client_id " "in config.yaml is empty). The Nous Portal provisions this env var (shape " "'agent:{instance_id}') when it deploys a Hermes Agent instance — set it to " "your provisioned client id (either as an env var or under " "dashboard.oauth.client_id in config.yaml), or pass --insecure to skip the " "OAuth gate entirely." ) logger.debug("dashboard-auth-nous: %s", LAST_SKIP_REASON) return if not client_id.startswith("agent:"): LAST_SKIP_REASON = ( f"HERMES_DASHBOARD_OAUTH_CLIENT_ID={client_id!r} doesn't match the contract " f"shape 'agent:{{instance_id}}'. The Nous Portal provisions this value at deploy " f"time; check your Fly app's secrets or override with the value from the Portal admin UI." ) logger.warning("dashboard-auth-nous: %s", LAST_SKIP_REASON) return try: provider = NousDashboardAuthProvider(client_id=client_id, portal_url=portal_url) except ValueError as exc: LAST_SKIP_REASON = f"NousDashboardAuthProvider construction failed: {exc}" logger.warning("dashboard-auth-nous: %s", LAST_SKIP_REASON) return ctx.register_dashboard_auth_provider(provider) logger.info("dashboard-auth-nous: registered provider (client_id=%s, portal=%s)", client_id, portal_url)