feat(dashboard): let a peer pass reach the agent's API through /api/peer
Another Hermes agent can now call this agent's API server through the dashboard with a short-lived pass minted for this one agent, instead of holding its API_SERVER_KEY. - /api/peer/<path> and /api/peer/p/<profile>/<path> forward to the gateway api_server on loopback with the key that listener checks. The key never leaves the machine and nothing new listens on the network. - Each path needs a permission the pass carries: agents:message for what `hermes peer` uses (health, capabilities, sessions and session chat, runs, run events, stop), agents:control (which includes messaging) for the rest of the user-facing API. Unlisted paths are never forwarded: cron fire, platform event intake, RoomLink grants, /health/detailed. - Passes are checked through a new provider capability (supports_peer_pass / verify_peer_pass), kept apart from verify_token, so a pass never authorises another provider's token routes such as /api/gateway/drain. - The Nous provider no longer opens a dashboard session for a token whose scope lacks agent_dashboard:access. It did not look at scope before, which was safe only while every token minted for an agent granted the dashboard. A token with no scope claim is still accepted, like the other contract claims. - Control actions are written to the dashboard-auth audit log (peer_control) with the pass holder, and the api_server records the holder as peer_principal in a job's origin, so jobs outlive passes attributably. - /p/<profile>/ reads as the api_server reads it: hermes is the default profile unless a profile has that name, and an unknown profile gets the api_server's own 404 body, which `hermes peer` recognises. - X-Hermes-Session-Key (the api_server's memory scope) passes only with agents:control. The api_server's replay and partial-turn response headers come back. - A gateway that is asleep answers 503 with Retry-After; a request it dropped after receiving it answers 502 with no retry hint, since it may have run. Neither counts toward the dashboard's own health. - The cron-fire listener lookup is split out so the peer route resolves the same listener, with the key the gateway loads (a usable API_SERVER_KEY over the configured key).
This commit is contained in:
@@ -1368,7 +1368,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
|
||||
"real_ip": self._clean_log_value(request.headers.get("X-Real-IP", "")),
|
||||
"method": self._clean_log_value(request.method, max_len=16),
|
||||
"path": self._clean_log_value(request.path_qs, max_len=500),
|
||||
"user_agent": self._clean_log_value(request.headers.get("User-Agent", ""), max_len=300)}
|
||||
"user_agent": self._clean_log_value(request.headers.get("User-Agent", ""), max_len=300),
|
||||
# The Portal user a peer pass holder signed in as; set by the dashboard's /api/peer route.
|
||||
"peer_principal": self._clean_log_value(request.headers.get("X-Hermes-Peer-Principal", ""), max_len=128)}
|
||||
|
||||
def _request_audit_log_suffix(self, request: web.Request) -> str:
|
||||
ctx = self._request_audit_context(request)
|
||||
@@ -1379,11 +1381,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
|
||||
"""Persist safe API source metadata on cron jobs created over HTTP."""
|
||||
ctx = self._request_audit_context(request)
|
||||
origin = {"platform": "api_server", "chat_id": "api"}
|
||||
for ctx_key, origin_key in (("remote", "source_ip"), ("peer_ip", "peer_ip"),
|
||||
("forwarded_for", "forwarded_for"), ("real_ip", "real_ip"),
|
||||
("user_agent", "user_agent")):
|
||||
if ctx.get(ctx_key):
|
||||
origin[origin_key] = ctx[ctx_key]
|
||||
for key in ("remote", "peer_ip", "forwarded_for", "real_ip", "user_agent", "peer_principal"):
|
||||
if ctx.get(key):
|
||||
origin["source_ip" if key == "remote" else key] = ctx[key]
|
||||
return origin
|
||||
|
||||
def _expected_api_key(self) -> str:
|
||||
|
||||
@@ -48,6 +48,8 @@ class AuditEvent(enum.Enum):
|
||||
WS_TICKET_REJECTED = "ws_ticket_rejected"
|
||||
TOKEN_AUTH_SUCCESS = "token_auth_success"
|
||||
TOKEN_AUTH_FAILURE = "token_auth_failure"
|
||||
# A peer pass holder's control action forwarded by ``/api/peer``, with the Portal user.
|
||||
PEER_CONTROL = "peer_control"
|
||||
# RFC 8252 native-app (system-browser + loopback + PKCE) flow.
|
||||
NATIVE_AUTHORIZE_START = "native_authorize_start"
|
||||
NATIVE_CODE_ISSUED = "native_code_issued"
|
||||
|
||||
@@ -113,6 +113,7 @@ class DashboardAuthProvider(ABC):
|
||||
Subclasses MUST set ``name`` (stable lowercase id) and ``display_name``. Capability flags:
|
||||
``supports_password`` (credential form + ``complete_password_login``; OAuth methods may be
|
||||
``NotImplementedError`` stubs), ``supports_token`` (``verify_token`` for the token-auth seam),
|
||||
``supports_peer_pass`` (``verify_peer_pass`` for the ``/api/peer`` route),
|
||||
``supports_session`` (False for token-only credentials such as drain, never offered a login),
|
||||
``interactive_login`` (False for a provider that verifies credentials but has no browser
|
||||
sign-in flow — kept out of the login page, ``/api/auth/providers`` and the auto-SSO redirect
|
||||
@@ -123,6 +124,7 @@ class DashboardAuthProvider(ABC):
|
||||
display_name: str = ""
|
||||
supports_password: bool = False
|
||||
supports_token: bool = False
|
||||
supports_peer_pass: bool = False
|
||||
supports_session: bool = True
|
||||
interactive_login: bool = True
|
||||
|
||||
@@ -160,6 +162,16 @@ class DashboardAuthProvider(ABC):
|
||||
f"{type(self).__name__} does not support token auth "
|
||||
"(set supports_token = True and override verify_token)")
|
||||
|
||||
def verify_peer_pass(self, *, token: str) -> Optional[TokenPrincipal]:
|
||||
"""Verify a pass minted for this agent, for the ``/api/peer`` route; return its holder and
|
||||
every scope it carries (the route decides which permit what). Kept apart from
|
||||
``verify_token`` so a pass never authorises another provider's token routes. Return
|
||||
``None`` for a token that is not a pass for this agent; raise ``ProviderError`` only for an
|
||||
outage. The default raises so a mis-flagged provider fails loudly."""
|
||||
raise NotImplementedError(
|
||||
f"{type(self).__name__} does not support peer passes "
|
||||
"(set supports_peer_pass = True and override verify_peer_pass)")
|
||||
|
||||
|
||||
def assert_protocol_compliance(cls: type) -> None:
|
||||
"""Raise ``TypeError`` if ``cls`` doesn't fully implement the protocol (call it from every
|
||||
|
||||
69
hermes_cli/dashboard_auth/peer_pass.py
Normal file
69
hermes_cli/dashboard_auth/peer_pass.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""Bearer check for ``/api/peer/...``: only a pass minted for this agent opens it.
|
||||
|
||||
The route owns its prefix. A provider with ``supports_peer_pass`` verifies the bearer; a pass
|
||||
attaches ``request.state.peer_principal`` (also as ``token_principal``, with
|
||||
``token_authenticated``, so the cookie gates stand aside) and the route then checks the pass's
|
||||
permissions per path (``hermes_cli.web_routers.peer``).
|
||||
Cookies, the session token and native tickets never open it, and nothing else reaches the shared
|
||||
token-auth seam's providers: a pass never authorises their routes, nor they this one. No pass
|
||||
provider registered (an agent not signed in through a provider that mints passes) is a 404.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Awaitable, Callable, Optional
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from hermes_cli.dashboard_auth import TokenPrincipal, list_providers
|
||||
from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log
|
||||
from hermes_cli.dashboard_auth.base import ProviderError
|
||||
from hermes_cli.dashboard_auth.request_utils import client_ip, extract_bearer, unreachable_response
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
PEER_PREFIX = "/api/peer/"
|
||||
|
||||
|
||||
def is_peer_path(path: str) -> bool:
|
||||
return path.startswith(PEER_PREFIX)
|
||||
|
||||
|
||||
async def _verify(providers: list, token: str) -> tuple[Optional[TokenPrincipal], Optional[str]]:
|
||||
"""``(principal, None)`` for a pass; ``(None, provider name)`` when none accepted it and one
|
||||
was unreachable (503); ``(None, None)`` otherwise (401)."""
|
||||
unreachable: Optional[str] = None
|
||||
for provider in providers:
|
||||
try:
|
||||
principal = await run_in_threadpool(provider.verify_peer_pass, token=token)
|
||||
except ProviderError as exc:
|
||||
_log.warning("dashboard-auth: peer pass provider %r unreachable: %s", provider.name, exc)
|
||||
unreachable = unreachable or provider.name
|
||||
continue
|
||||
if principal is not None:
|
||||
return principal, None
|
||||
return None, unreachable
|
||||
|
||||
|
||||
async def peer_pass_middleware(
|
||||
request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
|
||||
providers = [p for p in list_providers() if getattr(p, "supports_peer_pass", False)]
|
||||
if not providers:
|
||||
return JSONResponse({"error": "peer_access_unavailable",
|
||||
"detail": "This agent does not accept peer passes."}, status_code=404)
|
||||
token = extract_bearer(request)
|
||||
principal, unreachable = await _verify(providers, token) if token else (None, None)
|
||||
if principal is not None:
|
||||
request.state.token_principal = request.state.peer_principal = principal
|
||||
request.state.token_authenticated = True
|
||||
return await call_next(request)
|
||||
if unreachable:
|
||||
audit_log(AuditEvent.TOKEN_AUTH_FAILURE, provider=unreachable, reason="provider_unreachable",
|
||||
path=request.url.path, ip=client_ip(request))
|
||||
return unreachable_response(unreachable)
|
||||
audit_log(AuditEvent.TOKEN_AUTH_FAILURE, reason="no_peer_pass" if not token else "peer_pass_rejected",
|
||||
path=request.url.path, ip=client_ip(request))
|
||||
return JSONResponse({"error": "unauthenticated", "detail": "A peer pass for this agent is required."},
|
||||
status_code=401)
|
||||
195
hermes_cli/web_routers/peer.py
Normal file
195
hermes_cli/web_routers/peer.py
Normal file
@@ -0,0 +1,195 @@
|
||||
"""Cloud peer access: ``/api/peer/...`` carries another Hermes agent's API calls to this agent's
|
||||
gateway api_server on loopback, so ``hermes peer`` can reach a hosted agent without its key.
|
||||
|
||||
The bearer is a short-lived pass minted for this one agent, verified before this route runs
|
||||
(``hermes_cli.dashboard_auth.peer_pass``). Each path in :data:`_ROUTES` needs one permission; a path
|
||||
not listed is never forwarded, which keeps machine plumbing (``/api/cron/fire``, platform event
|
||||
intake, RoomLink grants, ``/health/detailed``) off this route. The request goes on with the
|
||||
API_SERVER_KEY the listener checks, which never leaves the machine, and with the pass holder's id
|
||||
in ``X-Hermes-Peer-Principal`` so jobs they create stay attributable. Control actions are written to
|
||||
the dashboard-auth audit log. ``/api/peer/p/<profile>/...`` reaches one profile.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import http.cookiejar
|
||||
import logging
|
||||
import urllib.parse
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from gateway.platforms.api_server_profile_prefix import DEFAULT_PROFILE_HANDLE, UNKNOWN_PROFILE_ERROR
|
||||
from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log
|
||||
from hermes_cli.dashboard_auth.peer_pass import PEER_PREFIX
|
||||
from hermes_cli.dashboard_auth.request_utils import client_ip
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
#: Messaging: everything ``hermes peer`` sends today, plus run events.
|
||||
MESSAGE = "agents:message"
|
||||
#: Control: what a user controls through the agent's API. Includes messaging.
|
||||
CONTROL = "agents:control"
|
||||
|
||||
# (method, path with ``*`` for one id segment) -> permission.
|
||||
_ROUTES: dict[tuple[str, str], str] = {
|
||||
**{route: MESSAGE for route in (
|
||||
("GET", "health"), ("GET", "v1/health"), ("GET", "v1/capabilities"),
|
||||
("GET", "api/sessions"), ("POST", "api/sessions"), ("GET", "api/sessions/*"),
|
||||
("POST", "api/sessions/*/chat"),
|
||||
("POST", "v1/runs"), ("GET", "v1/runs/*"), ("GET", "v1/runs/*/events"), ("POST", "v1/runs/*/stop"))},
|
||||
**{route: CONTROL for route in (
|
||||
("POST", "v1/runs/*/steer"), ("POST", "v1/runs/*/approval"), ("POST", "v1/runs/*/clarify"),
|
||||
("POST", "v1/runs/*/resolve-unknown"),
|
||||
("PATCH", "api/sessions/*"), ("DELETE", "api/sessions/*"), ("GET", "api/sessions/*/messages"),
|
||||
("POST", "api/sessions/*/fork"), ("POST", "api/sessions/*/chat/stream"), ("POST", "api/sessions/*/model"),
|
||||
("GET", "api/jobs"), ("POST", "api/jobs"), ("GET", "api/jobs/*"), ("PATCH", "api/jobs/*"),
|
||||
("DELETE", "api/jobs/*"), ("POST", "api/jobs/*/pause"), ("POST", "api/jobs/*/resume"),
|
||||
("POST", "api/jobs/*/run"),
|
||||
("GET", "api/model/options"), ("GET", "v1/models"), ("GET", "v1/skills"), ("GET", "v1/toolsets"),
|
||||
("POST", "v1/chat/completions"), ("POST", "v1/responses"), ("GET", "v1/responses/*"),
|
||||
("DELETE", "v1/responses/*"))},
|
||||
}
|
||||
_METHODS = sorted({method for method, _ in _ROUTES})
|
||||
|
||||
_HOP_BY_HOP = frozenset({"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te",
|
||||
"trailer", "transfer-encoding", "upgrade"})
|
||||
#: Request headers that never reach the gateway: the caller's credentials and provenance (the pass,
|
||||
#: cookies, browser origin). The agent's key and the verified pass holder replace them.
|
||||
_DROP_REQUEST = _HOP_BY_HOP | frozenset({
|
||||
"host", "cookie", "authorization", "origin", "referer", "forwarded", "x-real-ip",
|
||||
"x-hermes-session-token", "x-hermes-gateway-ticket", "x-hermes-window-ticket"})
|
||||
#: Picks the api_server's memory scope, which it keeps for key holders: only a control pass, which
|
||||
#: has key-holder parity, may set it.
|
||||
_CONTROL_ONLY_REQUEST = frozenset({"x-hermes-session-key"})
|
||||
#: Response headers that come back: what describes the body, plus the api_server's own signals
|
||||
#: (session, replayed admission, partial or failed turn).
|
||||
_KEEP_RESPONSE = frozenset({"content-type", "content-length", "content-encoding", "cache-control",
|
||||
"x-accel-buffering", "retry-after", "x-hermes-session-id", "x-hermes-session-key",
|
||||
"idempotency-replayed", "x-hermes-completed", "x-hermes-partial", "x-hermes-error"})
|
||||
#: Failures before the request reached the gateway (asleep, restarting, off): safe to retry.
|
||||
_NOT_SENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
|
||||
|
||||
|
||||
def _permission(method: str, segments: list[str]) -> Optional[str]:
|
||||
for (route_method, template), permission in _ROUTES.items():
|
||||
parts = template.split("/")
|
||||
if route_method == method and len(parts) == len(segments) and all(
|
||||
part in ("*", segment) for part, segment in zip(parts, segments)):
|
||||
return permission
|
||||
return None
|
||||
|
||||
|
||||
def _parse(scope) -> Optional[tuple[Optional[str], list[str]]]:
|
||||
"""``(profile or None, decoded path segments)`` after the prefix, or None for a path this route
|
||||
never carries: an empty, ``.`` or ``..`` segment (however encoded) or a control character."""
|
||||
raw = (scope.get("raw_path") or scope.get("path", "").encode("utf-8")).decode("latin-1")
|
||||
index = raw.find(PEER_PREFIX)
|
||||
if index < 0:
|
||||
return None
|
||||
segments = [urllib.parse.unquote(part) for part in raw[index + len(PEER_PREFIX):].split("/")]
|
||||
if any(not s or s in (".", "..") or any(ord(c) < 0x20 or ord(c) == 0x7F for c in s) for s in segments):
|
||||
return None
|
||||
if len(segments) > 2 and segments[0] == "p":
|
||||
return segments[1], segments[2:]
|
||||
return None, segments
|
||||
|
||||
|
||||
def _upstream(profile: Optional[str]) -> Optional[tuple[str, str]]:
|
||||
"""``(loopback base URL, API_SERVER_KEY)`` of the gateway api_server serving *profile* (None: the
|
||||
profile this dashboard serves), or None when this host has no such profile. The prefix reads as
|
||||
the api_server reads it: the default profile's handle ``hermes`` is the default profile unless a
|
||||
profile has that name. Reads config and .env files: call it off the event loop."""
|
||||
from hermes_cli import profiles
|
||||
from hermes_cli import web_server_cron as cron
|
||||
if profile is None:
|
||||
name, home = cron._cron_profile_home(None)
|
||||
return cron._gateway_api_target(name, home)
|
||||
name = profiles.normalize_profile_name(profile)
|
||||
if name == DEFAULT_PROFILE_HANDLE and not profiles.profile_exists(name):
|
||||
name = "default"
|
||||
if not profiles.profile_exists(name):
|
||||
return None
|
||||
return cron._gateway_api_target(name, profiles.get_profile_dir(name))
|
||||
|
||||
|
||||
def _gateway_client(state) -> httpx.AsyncClient:
|
||||
"""One client per event loop: no redirects, no proxy settings from the environment, no read
|
||||
deadline (run events and chat streams last as long as the turn), and no cookie jar, since every
|
||||
pass holder's requests share it."""
|
||||
loop = asyncio.get_running_loop()
|
||||
held = getattr(state, "peer_gateway_client", None)
|
||||
if held is not None and held[0] is loop:
|
||||
return held[1]
|
||||
no_cookies = http.cookiejar.CookieJar(policy=http.cookiejar.DefaultCookiePolicy(allowed_domains=[]))
|
||||
client = httpx.AsyncClient(follow_redirects=False, trust_env=False, cookies=no_cookies,
|
||||
timeout=httpx.Timeout(connect=10.0, read=None, write=60.0, pool=10.0))
|
||||
state.peer_gateway_client = (loop, client)
|
||||
return client
|
||||
|
||||
|
||||
def _refusal(error: str, detail: str, status: int, **headers: str) -> JSONResponse:
|
||||
return JSONResponse({"error": error, "detail": detail}, status_code=status, headers=headers or None)
|
||||
|
||||
|
||||
@router.api_route(PEER_PREFIX + "{path:path}", methods=_METHODS, include_in_schema=False)
|
||||
async def peer_forward(request: Request, path: str):
|
||||
principal = getattr(request.state, "peer_principal", None)
|
||||
if principal is None:
|
||||
raise HTTPException(401, "A peer pass for this agent is required.")
|
||||
parsed = _parse(request.scope)
|
||||
needed = _permission(request.method, parsed[1]) if parsed else None
|
||||
if parsed is None or needed is None:
|
||||
return _refusal("not_found", "This agent's peer route does not carry that path.", 404)
|
||||
profile, segments = parsed
|
||||
if needed not in principal.scopes and CONTROL not in principal.scopes:
|
||||
audit_log(AuditEvent.TOKEN_AUTH_FAILURE, reason="insufficient_scope", principal=principal.principal,
|
||||
method=request.method, path=request.url.path, ip=client_ip(request))
|
||||
return _refusal("insufficient_scope", f"This pass does not grant {needed}.", 403)
|
||||
|
||||
upstream_target = await asyncio.to_thread(_upstream, profile)
|
||||
if upstream_target is None:
|
||||
return JSONResponse({"error": UNKNOWN_PROFILE_ERROR}, status_code=404)
|
||||
base, key = upstream_target
|
||||
if not key:
|
||||
return _refusal("peer_gateway_unavailable", "This agent's API server has no key configured.", 503)
|
||||
target = "/" + "/".join(urllib.parse.quote(segment, safe="") for segment in segments)
|
||||
query = (request.scope.get("query_string") or b"").decode("latin-1")
|
||||
headers = {name: value for name, value in request.headers.items()
|
||||
if name.lower() not in _DROP_REQUEST
|
||||
and not name.lower().startswith(("x-forwarded-", "x-hermes-peer-"))
|
||||
and (name.lower() not in _CONTROL_ONLY_REQUEST or CONTROL in principal.scopes)}
|
||||
headers.update({"Authorization": f"Bearer {key}", "X-Hermes-Peer-Principal": principal.principal})
|
||||
if client_ip(request):
|
||||
headers["X-Forwarded-For"] = client_ip(request)
|
||||
method = request.method
|
||||
has_body = method not in {"GET", "HEAD"} or request.headers.get("content-length") not in (None, "0")
|
||||
client = _gateway_client(request.app.state)
|
||||
upstream = client.build_request(method, f"{base}{target}" + (f"?{query}" if query else ""),
|
||||
headers=headers, content=request.stream() if has_body else None)
|
||||
response: Optional[httpx.Response] = None
|
||||
try:
|
||||
response = await client.send(upstream, stream=True)
|
||||
except _NOT_SENT as exc:
|
||||
_log.info("peer route: gateway api_server at %s unreachable: %s", base, exc)
|
||||
return _refusal("peer_gateway_unavailable", "This agent's API server is not reachable yet.", 503,
|
||||
**{"Retry-After": "5"})
|
||||
except httpx.HTTPError as exc: # sent, then the connection broke: the action may have run
|
||||
_log.warning("peer route: gateway api_server at %s dropped %s %s: %s", base, method, target, exc)
|
||||
if response is not None and response.status_code == 401:
|
||||
await response.aclose()
|
||||
return _refusal("peer_gateway_auth", "This agent's API server refused the agent's own key.", 502)
|
||||
if needed == CONTROL:
|
||||
audit_log(AuditEvent.PEER_CONTROL, principal=principal.principal, provider=principal.provider,
|
||||
method=method, path=target, profile=profile or "",
|
||||
status=response.status_code if response is not None else 502, ip=client_ip(request))
|
||||
if response is None:
|
||||
return _refusal("peer_gateway_dropped",
|
||||
"This agent's API server dropped the request before answering; it may have run.", 502)
|
||||
out = {name: value for name, value in response.headers.items() if name.lower() in _KEEP_RESPONSE}
|
||||
return StreamingResponse(response.aiter_raw(), status_code=response.status_code, headers=out,
|
||||
background=BackgroundTask(response.aclose))
|
||||
@@ -484,8 +484,11 @@ async def _token_auth_seam(request: Request, call_next):
|
||||
|
||||
A registered token route is owned here — authenticate, attach the principal
|
||||
+ ``token_authenticated`` so downstream gates skip enforcement. Non-token
|
||||
routes pass through untouched.
|
||||
routes pass through untouched. ``/api/peer/`` is owned by the peer-pass check instead.
|
||||
"""
|
||||
from hermes_cli.dashboard_auth.peer_pass import is_peer_path, peer_pass_middleware
|
||||
if is_peer_path(request.url.path): # only a peer pass opens it; nothing else is tried
|
||||
return await peer_pass_middleware(request, call_next)
|
||||
from hermes_cli.dashboard_auth.native_http import authenticate_native_http, native_profile_scope
|
||||
from hermes_cli.dashboard_auth.token_auth import token_auth_middleware
|
||||
rejection = await authenticate_native_http(request)
|
||||
@@ -556,7 +559,10 @@ async def _dashboard_health_middleware(request: Request, call_next):
|
||||
except Exception as exc:
|
||||
DASHBOARD_HEALTH.record_error(type(exc).__name__, request.url.path)
|
||||
raise
|
||||
if response.status_code >= 500:
|
||||
# /api/peer answers carry the gateway api_server's status (asleep, restarting, its own errors),
|
||||
# which the gateway component reports; they say nothing about this process.
|
||||
from hermes_cli.dashboard_auth.peer_pass import is_peer_path
|
||||
if response.status_code >= 500 and not is_peer_path(request.url.path):
|
||||
DASHBOARD_HEALTH.record_error(f"http_{response.status_code}", request.url.path)
|
||||
return response
|
||||
|
||||
@@ -806,6 +812,7 @@ from hermes_cli.web_routers import (
|
||||
gateway_connections as _gateway_connections_routes,
|
||||
gateway_connections_reach as _gateway_connections_reach_routes,
|
||||
webapp_relay_proxy as _webapp_relay_proxy_routes,
|
||||
peer as _peer_routes,
|
||||
)
|
||||
|
||||
import hermes_cli.web_routers.desktop_plugins as _desktop_plugin_routes
|
||||
@@ -850,6 +857,7 @@ app.include_router(_dashboard_ui_routes.router)
|
||||
app.include_router(_webapp_routes.router)
|
||||
# The saved-connections proxy checks its surface per request (WebSocket routes take no Request).
|
||||
app.include_router(_webapp_relay_proxy_routes.router)
|
||||
app.include_router(_peer_routes.router)
|
||||
app.include_router(_shared_metrics_routes.router)
|
||||
app.include_router(_delegation_routes.router)
|
||||
app.include_router(_webapp_access_routes.router, dependencies=[_Depends(_route_on("web_access"))])
|
||||
|
||||
@@ -325,39 +325,33 @@ def _profile_env_value(home: Path, key: str) -> str:
|
||||
return load_env_file(home / ".env").get(key, "")
|
||||
|
||||
|
||||
def _gateway_fire_endpoint(profile: str, home: Path) -> str:
|
||||
"""Loopback URL of the gateway api_server's cron-fire route.
|
||||
|
||||
Port resolution mirrors gateway/config.py's api_server load order for the LISTENER-OWNER
|
||||
profile: ``platforms.api_server.extra.port`` in its config.yaml, then ``API_SERVER_PORT``
|
||||
(process env for the active profile, the profile's own .env otherwise), then 8642. Loopback
|
||||
is safe: dashboard and gateway share a network namespace in every supported deployment.
|
||||
def _gateway_listener(profile: str, home: Path) -> tuple[bool, str, Path]:
|
||||
"""``(multiplex, listener profile, listener home)`` of the gateway api_server serving *profile*.
|
||||
|
||||
In multiplex mode only the DEFAULT profile's api_server is bound and exposes per-profile
|
||||
mirrors under ``/p/<profile>/…``, so a non-default profile's port must be read from the
|
||||
default home (a secondary's own API_SERVER_PORT is a port nothing listens on).
|
||||
mirrors under ``/p/<profile>/…``, so a non-default profile's listener is the default home (a
|
||||
secondary's own API_SERVER_PORT is a port nothing listens on).
|
||||
"""
|
||||
from hermes_cli.config import load_config
|
||||
import os as _os
|
||||
multiplex = False
|
||||
try:
|
||||
# The live default gateway's own record, else the explicit flag — never the merged default:
|
||||
# an unset gateway.multiplex_profiles is settled by the gateway at boot, not by this process.
|
||||
from hermes_cli.gateway_multiplex_mode import default_gateway_multiplexes
|
||||
multiplex = default_gateway_multiplexes()
|
||||
except Exception:
|
||||
_log.debug("cron fire: multiplex detection failed; assuming single-profile", exc_info=True)
|
||||
|
||||
listener_profile, listener_home = profile, home
|
||||
except Exception: # health: allow BLE001 -- moved from _gateway_fire_endpoint; detection must never fail a request
|
||||
_log.debug("gateway api_server: multiplex detection failed; assuming single-profile", exc_info=True)
|
||||
if multiplex and profile != "default":
|
||||
from hermes_constants import get_default_hermes_root
|
||||
listener_profile, listener_home = "default", get_default_hermes_root()
|
||||
_log.info(
|
||||
"cron fire: multiplex gateway — resolving api_server port for %s "
|
||||
"from the default profile's listener (%s)", profile, listener_home,
|
||||
)
|
||||
"gateway api_server: multiplex gateway; %s is served by the default profile's "
|
||||
"listener", profile)
|
||||
return True, "default", get_default_hermes_root()
|
||||
return multiplex, profile, home
|
||||
|
||||
port = 0
|
||||
|
||||
def _listener_api_server_extra(listener_home: Path) -> dict:
|
||||
"""``platforms.api_server.extra`` of the listener profile's config ({} when unreadable)."""
|
||||
from hermes_cli.config import load_config
|
||||
try:
|
||||
# Profile-scoped read through the CANONICAL loader (managed-scope overlay, ${ENV_VAR}
|
||||
# expansion) — never a raw yaml.safe_load (tests/hermes_cli/test_config_read_guard.py).
|
||||
@@ -367,24 +361,75 @@ def _gateway_fire_endpoint(profile: str, home: Path) -> str:
|
||||
profile_cfg = load_config()
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
raw = cfg_get(profile_cfg, "platforms", "api_server", "extra", "port", default=None)
|
||||
if raw:
|
||||
port = int(raw)
|
||||
except Exception:
|
||||
extra = cfg_get(profile_cfg, "platforms", "api_server", "extra", default=None)
|
||||
return extra if isinstance(extra, dict) else {}
|
||||
except Exception: # health: allow BLE001 -- moved from _gateway_fire_endpoint; unreadable config falls back to env
|
||||
return {}
|
||||
|
||||
|
||||
def _profile_setting(profile: str, home: Path, key: str) -> str:
|
||||
"""*key* from the process env for the active profile, the profile's own .env otherwise."""
|
||||
import os as _os
|
||||
return _os.getenv(key, "") if profile == _cron_default_profile() else _profile_env_value(home, key)
|
||||
|
||||
|
||||
def _gateway_api_base(profile: str, home: Path) -> str:
|
||||
"""Loopback base URL of the gateway api_server serving *profile* (:func:`_listener_base`)."""
|
||||
listener = _gateway_listener(profile, home)
|
||||
return _listener_base(profile, listener, _listener_api_server_extra(listener[2]))
|
||||
|
||||
|
||||
def _gateway_api_target(profile: str, home: Path) -> tuple[str, str]:
|
||||
"""``(loopback base URL, API_SERVER_KEY)`` of the gateway api_server serving *profile*, from one
|
||||
listener lookup. The key is the one that listener checks (the api_server's ``_expected_api_key``):
|
||||
a multiplexed profile's own key, never the default's; otherwise a usable ``API_SERVER_KEY``,
|
||||
which the gateway loads over ``platforms.api_server.extra.key`` (gateway/config_env.py), then
|
||||
that configured key. ``""`` when there is none."""
|
||||
listener = _gateway_listener(profile, home)
|
||||
multiplex, listener_profile, listener_home = listener
|
||||
extra = _listener_api_server_extra(listener_home)
|
||||
base = _listener_base(profile, listener, extra)
|
||||
if multiplex and profile != "default":
|
||||
return base, _profile_env_value(home, "API_SERVER_KEY")
|
||||
from hermes_cli.auth import has_usable_secret
|
||||
key = _profile_setting(listener_profile, listener_home, "API_SERVER_KEY").strip()
|
||||
if has_usable_secret(key, min_length=16):
|
||||
return base, key
|
||||
configured = extra.get("key")
|
||||
return base, configured.strip() if isinstance(configured, str) else ""
|
||||
|
||||
|
||||
def _listener_base(profile: str, listener: tuple[bool, str, Path], extra: dict) -> str:
|
||||
"""Loopback base URL of *listener* (from :func:`_gateway_listener`) for *profile*.
|
||||
|
||||
Port resolution mirrors gateway/config.py's api_server load order for the LISTENER-OWNER
|
||||
profile: ``platforms.api_server.extra.port`` in its config.yaml (*extra*), then
|
||||
``API_SERVER_PORT`` (process env for the active profile, the profile's own .env otherwise), then
|
||||
8642. Loopback is safe: dashboard and gateway share a network namespace in every supported
|
||||
deployment.
|
||||
"""
|
||||
multiplex, listener_profile, listener_home = listener
|
||||
port = 0
|
||||
try:
|
||||
raw = extra.get("port")
|
||||
port = int(raw) if raw else 0
|
||||
except (TypeError, ValueError):
|
||||
port = 0
|
||||
if not port:
|
||||
raw = (
|
||||
_os.getenv("API_SERVER_PORT", "")
|
||||
if listener_profile == _cron_default_profile()
|
||||
else _profile_env_value(listener_home, "API_SERVER_PORT"))
|
||||
raw = _profile_setting(listener_profile, listener_home, "API_SERVER_PORT")
|
||||
try:
|
||||
port = int(raw) if raw else 0
|
||||
except ValueError:
|
||||
port = 0
|
||||
port = port or 8642
|
||||
if multiplex and profile != "default":
|
||||
return f"http://127.0.0.1:{port}/p/{profile}/api/cron/fire"
|
||||
return f"http://127.0.0.1:{port}/api/cron/fire"
|
||||
return f"http://127.0.0.1:{port}/p/{profile}"
|
||||
return f"http://127.0.0.1:{port}"
|
||||
|
||||
|
||||
def _gateway_fire_endpoint(profile: str, home: Path) -> str:
|
||||
"""Loopback URL of the gateway api_server's cron-fire route."""
|
||||
return f"{_gateway_api_base(profile, home)}/api/cron/fire"
|
||||
|
||||
|
||||
async def _forward_cron_fire_to_gateway(
|
||||
|
||||
@@ -16,7 +16,8 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from hermes_cli.dashboard_auth import InvalidCodeError, LoginStart, ProviderError, Session, listener_client
|
||||
from hermes_cli.dashboard_auth import (
|
||||
InvalidCodeError, LoginStart, ProviderError, Session, TokenPrincipal, listener_client)
|
||||
from plugins.dashboard_auth._shared import (
|
||||
DEFAULT_TOKEN_LEEWAY_SECONDS,
|
||||
JwtOAuthProvider,
|
||||
@@ -47,6 +48,7 @@ class NousDashboardAuthProvider(JwtOAuthProvider):
|
||||
|
||||
name = "nous"
|
||||
display_name = "Nous Research"
|
||||
supports_peer_pass = True
|
||||
|
||||
def __init__(self, *, client_id: str, portal_url: str, token_leeway: float = DEFAULT_TOKEN_LEEWAY_SECONDS) -> None:
|
||||
# Defense-in-depth: register() filters too, but a malformed id must never construct a provider.
|
||||
@@ -98,6 +100,28 @@ class NousDashboardAuthProvider(JwtOAuthProvider):
|
||||
|
||||
|
||||
def _claims_for(self, access_token: str) -> dict[str, Any]:
|
||||
# Every dashboard grant mints ``agent_dashboard:access``; a pass for this agent without it
|
||||
# (a peer pass) opens ``/api/peer`` only, never a dashboard session. A token with no
|
||||
# ``scope`` claim at all is tolerated, as before: contract V1 always writes one.
|
||||
claims = self._agent_claims(access_token)
|
||||
if "scope" not in claims:
|
||||
logger.warning("Nous Portal token missing scope claim (contract says %s); proceeding anyway.", _SCOPE)
|
||||
elif _SCOPE not in _scopes(claims):
|
||||
raise InvalidCodeError(f"token does not grant {_SCOPE}")
|
||||
return claims
|
||||
|
||||
def verify_peer_pass(self, *, token: str) -> Optional[TokenPrincipal]:
|
||||
try:
|
||||
claims = self._agent_claims(token)
|
||||
except InvalidCodeError:
|
||||
return None
|
||||
user_id = str(claims.get("sub") or "")
|
||||
if not user_id:
|
||||
return None
|
||||
return TokenPrincipal(principal=user_id, provider=self.name, scopes=tuple(sorted(_scopes(claims))))
|
||||
|
||||
def _agent_claims(self, access_token: str) -> dict[str, Any]:
|
||||
"""Claims of a Portal access token minted for this agent, whatever it grants."""
|
||||
claims = verify_jwt(
|
||||
access_token, self._get_jwks_client(), algorithms=["RS256"],
|
||||
audience=self._client_id, # contract C2: bare client_id
|
||||
@@ -128,6 +152,11 @@ class NousDashboardAuthProvider(JwtOAuthProvider):
|
||||
self.name, claims, access_token=access_token, refresh_token=refresh_token, org_id=str(claims.get("org_id") or ""))
|
||||
|
||||
|
||||
def _scopes(claims: dict[str, Any]) -> set[str]:
|
||||
raw = claims.get("scope")
|
||||
return set(raw.split()) if isinstance(raw, str) else set()
|
||||
|
||||
|
||||
# ---- Plugin entry point ----
|
||||
|
||||
def _load_config_oauth_section() -> dict:
|
||||
|
||||
@@ -139,6 +139,20 @@ class TestCreateJob:
|
||||
assert call_kwargs["origin"]["forwarded_for"] == "203.0.113.11"
|
||||
assert call_kwargs["origin"]["user_agent"] == "cron-client"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_a_job_created_through_the_dashboard_peer_route_names_its_creator(self, adapter):
|
||||
"""The dashboard's /api/peer route signs a peer pass holder's calls with the Portal user it
|
||||
verified, so a job they create stays attributable after their pass expires."""
|
||||
app = _create_app(adapter)
|
||||
mock_create = MagicMock(return_value=SAMPLE_JOB)
|
||||
async with TestClient(TestServer(app)) as cli:
|
||||
with patch(f"{_MOD}._CRON_AVAILABLE", True), patch(f"{_MOD}._cron_create", mock_create):
|
||||
resp = await cli.post("/api/jobs", json={
|
||||
"name": "nightly", "schedule": "0 3 * * *", "prompt": "summarise the day"},
|
||||
headers={"X-Hermes-Peer-Principal": "usr_abc"})
|
||||
assert resp.status == 200
|
||||
assert mock_create.call_args[1]["origin"]["peer_principal"] == "usr_abc"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_job_reports_saved_but_unregistered(self, adapter):
|
||||
|
||||
335
tests/hermes_cli/test_dashboard_peer_access.py
Normal file
335
tests/hermes_cli/test_dashboard_peer_access.py
Normal file
@@ -0,0 +1,335 @@
|
||||
"""Cloud peer access: ``/api/peer/...`` on the dashboard carries a local Hermes agent's API calls to
|
||||
this agent's gateway api_server on loopback.
|
||||
|
||||
The caller holds a short-lived pass minted for this one agent, never the agent's
|
||||
``API_SERVER_KEY``. Each path needs the permission the route table names (``agents:message`` or
|
||||
``agents:control``, which includes messaging), paths outside the table are never forwarded, and the
|
||||
agent's own key is added only here, on the way to loopback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, StreamingResponse
|
||||
from starlette.routing import Route
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
import hermes_cli.config as _cfg_mod
|
||||
import hermes_cli.web_server_cron as _web_server_cron
|
||||
from hermes_cli import web_server
|
||||
import plugins.dashboard_auth.session_token as session_token_plugin
|
||||
from hermes_cli.dashboard_auth import ProviderError, TokenPrincipal, clear_providers, register_provider
|
||||
from hermes_cli.profiles import get_profile_dir
|
||||
from hermes_cli.web_routers import peer as peer_routes
|
||||
from hermes_constants import get_hermes_home
|
||||
from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider, _sign
|
||||
|
||||
AGENT_KEY = "local-api-server-key-0123456789abcdef"
|
||||
MESSAGE, CONTROL = "agents:message", "agents:control"
|
||||
|
||||
|
||||
class PeerPassStub(StubAuthProvider):
|
||||
"""The stub IdP, plus passes minted for this agent: token -> (user, scopes)."""
|
||||
|
||||
supports_peer_pass = True
|
||||
passes = {
|
||||
"pass-message": ("usr_msg", (MESSAGE,)),
|
||||
"pass-control": ("usr_ctl", (CONTROL,)),
|
||||
"pass-dashboard": ("usr_dash", ("agent_dashboard:access",)),
|
||||
}
|
||||
down = False
|
||||
|
||||
def verify_peer_pass(self, *, token: str):
|
||||
if self.down:
|
||||
raise ProviderError("pass keys unreachable")
|
||||
hit = self.passes.get(token)
|
||||
return None if hit is None else TokenPrincipal(principal=hit[0], provider=self.name, scopes=hit[1])
|
||||
|
||||
|
||||
# Response headers the api_server documents for its clients (replays, partial turns, memory scope).
|
||||
GATEWAY_SIGNALS = {"Idempotency-Replayed": "true", "X-Hermes-Session-Key": "chan-1", "X-Hermes-Completed": "false",
|
||||
"X-Hermes-Partial": "true", "X-Hermes-Error": "provider timeout"}
|
||||
|
||||
|
||||
def _gateway(seen: list) -> Starlette:
|
||||
"""The gateway api_server: records each request; accepts only the agent's own key."""
|
||||
|
||||
async def record(request: Request):
|
||||
seen.append({"method": request.method, "path": request.url.path, "query": request.url.query,
|
||||
"headers": dict(request.headers), "body": await request.body()})
|
||||
if request.headers.get("authorization") != f"Bearer {AGENT_KEY}":
|
||||
return JSONResponse({"error": "gateway_auth_failed"}, status_code=401)
|
||||
return JSONResponse({"path": request.url.path}, status_code=202 if request.method == "POST" else 200,
|
||||
headers={"X-Hermes-Session-Id": "s1", "Set-Cookie": "edge=1",
|
||||
"Access-Control-Allow-Origin": "*", **GATEWAY_SIGNALS})
|
||||
|
||||
async def events(request: Request):
|
||||
seen.append({"method": request.method, "path": request.url.path})
|
||||
|
||||
async def stream():
|
||||
yield b'event: message.delta\ndata: {"delta": "hi"}\n\n'
|
||||
yield b"event: run.completed\ndata: {}\n\n"
|
||||
return StreamingResponse(stream(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"})
|
||||
|
||||
return Starlette(routes=[Route("/{prefix:path}/v1/runs/{run_id}/events", events),
|
||||
Route("/v1/runs/{run_id}/events", events),
|
||||
Route("/{path:path}", record, methods=["GET", "POST", "PATCH", "DELETE"])])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def peer(monkeypatch):
|
||||
clear_providers()
|
||||
stub = PeerPassStub()
|
||||
register_provider(stub)
|
||||
seen: list = []
|
||||
upstreams: list = []
|
||||
transport = httpx.ASGITransport(app=_gateway(seen))
|
||||
monkeypatch.setattr(peer_routes, "_gateway_client",
|
||||
lambda _state: httpx.AsyncClient(transport=transport, follow_redirects=False))
|
||||
|
||||
def listener(name, _home):
|
||||
upstreams.append(name)
|
||||
return ("http://gateway.test" + (f"/p/{name}" if name != "default" else ""), AGENT_KEY)
|
||||
monkeypatch.setattr(_web_server_cron, "_gateway_api_target", listener)
|
||||
work = get_profile_dir("work")
|
||||
work.mkdir(parents=True)
|
||||
(work / "config.yaml").write_text("{}\n", encoding="utf-8")
|
||||
state = web_server.app.state
|
||||
prev = {k: getattr(state, k, None) for k in ("bound_host", "bound_port", "auth_required")}
|
||||
state.bound_host, state.bound_port, state.auth_required = "agent.example.com", 443, True
|
||||
client = TestClient(web_server.app, base_url="https://agent.example.com")
|
||||
yield SimpleNamespace(client=client, stub=stub, seen=seen, upstreams=upstreams)
|
||||
client.close()
|
||||
clear_providers()
|
||||
for key, value in prev.items():
|
||||
setattr(state, key, value)
|
||||
|
||||
|
||||
def _bearer(token: str) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
def test_a_pass_reaches_the_agent_api_with_the_agent_key_and_nothing_of_the_callers(peer):
|
||||
resp = peer.client.post("/api/peer/v1/runs?wait=0", content=b'{"input": "hi"}', headers={
|
||||
**_bearer("pass-message"), "Content-Type": "application/json", "Idempotency-Key": "ticket-1",
|
||||
"Cookie": "hermes_session_at=browser", "X-Hermes-Peer-Principal": "someone-else",
|
||||
"X-Forwarded-For": "198.51.100.7", "Origin": "https://attacker.example"})
|
||||
|
||||
assert resp.status_code == 202 and resp.json() == {"path": "/v1/runs"}
|
||||
assert resp.headers["x-hermes-session-id"] == "s1"
|
||||
assert {name: resp.headers.get(name) for name in GATEWAY_SIGNALS} == GATEWAY_SIGNALS
|
||||
assert "set-cookie" not in resp.headers and "access-control-allow-origin" not in resp.headers
|
||||
(sent,) = peer.seen
|
||||
assert (sent["method"], sent["path"], sent["query"], sent["body"]) == (
|
||||
"POST", "/v1/runs", "wait=0", b'{"input": "hi"}')
|
||||
headers = sent["headers"]
|
||||
assert headers["authorization"] == f"Bearer {AGENT_KEY}"
|
||||
assert headers["idempotency-key"] == "ticket-1"
|
||||
assert headers["x-hermes-peer-principal"] == "usr_msg"
|
||||
assert "cookie" not in headers and "origin" not in headers
|
||||
assert "198.51.100.7" not in headers.get("x-forwarded-for", "")
|
||||
assert peer.upstreams == ["default"]
|
||||
|
||||
|
||||
# Every call ``hermes peer`` makes today, plus run events.
|
||||
MESSAGING = [("GET", "/health"), ("GET", "/v1/capabilities"), ("GET", "/api/sessions"),
|
||||
("POST", "/api/sessions"), ("GET", "/api/sessions/s1"), ("POST", "/api/sessions/s1/chat"),
|
||||
("POST", "/v1/runs"), ("GET", "/v1/runs/run_1"), ("POST", "/v1/runs/run_1/stop")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("method", "path"), MESSAGING)
|
||||
def test_messaging_routes_open_with_a_messaging_or_a_control_pass(peer, method, path):
|
||||
for token in ("pass-message", "pass-control"):
|
||||
resp = peer.client.request(method, f"/api/peer{path}", headers=_bearer(token))
|
||||
assert resp.status_code < 300, (token, resp.text)
|
||||
assert peer.seen[-1]["path"] == path
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("method", "path"), [
|
||||
("POST", "/v1/runs/run_1/approval"), ("POST", "/v1/runs/run_1/steer"),
|
||||
("POST", "/api/sessions/s1/fork"), ("DELETE", "/api/sessions/s1"),
|
||||
("POST", "/api/jobs"), ("POST", "/api/jobs/j1/run"),
|
||||
("POST", "/v1/chat/completions"), ("GET", "/v1/models")])
|
||||
def test_control_routes_need_the_control_permission(peer, method, path):
|
||||
refused = peer.client.request(method, f"/api/peer{path}", headers=_bearer("pass-message"))
|
||||
assert refused.status_code == 403 and refused.json()["error"] == "insufficient_scope"
|
||||
assert peer.seen == []
|
||||
|
||||
allowed = peer.client.request(method, f"/api/peer{path}", headers=_bearer("pass-control"))
|
||||
assert allowed.status_code < 300 and peer.seen[-1]["path"] == path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [
|
||||
"/api/cron/fire", "/api/platforms/telegram/events", "/v1/room-members/grant", "/health/detailed",
|
||||
"/v1/runs/%2e%2e/stop", "/api/sessions/%2E/chat", "/api/sessions//chat", "/api/env"])
|
||||
def test_paths_outside_the_table_are_never_forwarded(peer, path):
|
||||
resp = peer.client.post(f"/api/peer{path}", headers=_bearer("pass-control"))
|
||||
assert resp.status_code == 404
|
||||
assert peer.seen == []
|
||||
|
||||
|
||||
def test_peer_paths_open_only_with_a_peer_pass(peer):
|
||||
assert peer.client.get("/api/peer/health").status_code == 401
|
||||
assert peer.client.get("/api/peer/health", headers=_bearer("forged")).status_code == 401
|
||||
# A valid pass for this agent that carries neither peer permission.
|
||||
resp = peer.client.get("/api/peer/health", headers=_bearer("pass-dashboard"))
|
||||
assert resp.status_code == 403 and resp.json()["error"] == "insufficient_scope"
|
||||
peer.stub.down = True
|
||||
assert peer.client.get("/api/peer/health", headers=_bearer("pass-message")).status_code == 503
|
||||
assert peer.seen == []
|
||||
|
||||
|
||||
def test_dashboard_credentials_never_open_peer_paths(peer):
|
||||
"""A browser session cookie and the deployment session token both open the dashboard, and
|
||||
neither opens /api/peer: only a pass minted for this agent does."""
|
||||
deployment_token = "deployment-session-token-0123456789"
|
||||
register_provider(session_token_plugin.SessionTokenProvider(token=deployment_token))
|
||||
session = _sign({"sub": "stub-user-1", "email": "stub@example.test", "name": "Stub User",
|
||||
"org_id": "stub-org-1", "exp": 4102444800})
|
||||
for credentials in ({"Cookie": f"hermes_session_at={session}"},
|
||||
{"X-Hermes-Session-Token": deployment_token}, _bearer(deployment_token)):
|
||||
assert peer.client.get("/api/auth/me", headers=credentials).status_code == 200, credentials
|
||||
resp = peer.client.get("/api/peer/health", headers=credentials)
|
||||
assert resp.status_code == 401, (credentials, resp.text)
|
||||
assert peer.seen == []
|
||||
|
||||
|
||||
def test_an_agent_that_accepts_no_passes_has_no_peer_route(peer):
|
||||
clear_providers()
|
||||
resp = peer.client.get("/api/peer/health", headers=_bearer("pass-message"))
|
||||
assert resp.status_code == 404 and resp.json()["error"] == "peer_access_unavailable"
|
||||
assert peer.seen == []
|
||||
|
||||
|
||||
def test_an_api_server_without_a_key_is_never_called(peer, monkeypatch):
|
||||
monkeypatch.setattr(_web_server_cron, "_gateway_api_target", lambda name, home: ("http://gateway.test", ""))
|
||||
resp = peer.client.get("/api/peer/health", headers=_bearer("pass-message"))
|
||||
assert resp.status_code == 503 and resp.json()["error"] == "peer_gateway_unavailable"
|
||||
assert peer.seen == []
|
||||
|
||||
|
||||
def test_a_profile_prefix_reaches_that_profile(peer):
|
||||
resp = peer.client.post("/api/peer/p/work/v1/runs", headers=_bearer("pass-message"), json={})
|
||||
assert resp.status_code == 202
|
||||
assert peer.upstreams == ["work"] and peer.seen[-1]["path"] == "/p/work/v1/runs"
|
||||
|
||||
|
||||
def test_the_default_profiles_handle_reaches_the_default_profile(peer):
|
||||
"""Bot Mode shows a host's default profile as @hermes, so peers address it as /p/hermes, which
|
||||
the api_server answers as the default profile when no profile has that name."""
|
||||
resp = peer.client.get("/api/peer/p/hermes/health", headers=_bearer("pass-message"))
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert peer.upstreams == ["default"] and peer.seen[-1]["path"] == "/health"
|
||||
|
||||
|
||||
def test_an_unknown_profile_gets_the_api_servers_unknown_profile_answer(peer):
|
||||
"""``hermes peer`` reads this exact body as the peer's own "no such profile" verdict."""
|
||||
resp = peer.client.get("/api/peer/p/nosuch/health", headers=_bearer("pass-message"))
|
||||
assert resp.status_code == 404 and resp.json() == {"error": "Unknown or unconfigured profile"}
|
||||
assert peer.seen == []
|
||||
|
||||
|
||||
def test_only_a_control_pass_chooses_the_memory_scope(peer):
|
||||
"""``X-Hermes-Session-Key`` picks the api_server's memory scope, which the api_server keeps
|
||||
for key holders. A control pass has key-holder parity; a messaging pass never sets it."""
|
||||
for token, forwarded in (("pass-message", None), ("pass-control", "chan-1")):
|
||||
peer.client.post("/api/peer/v1/runs", headers={**_bearer(token), "X-Hermes-Session-Key": "chan-1"}, json={})
|
||||
assert peer.seen[-1]["headers"].get("x-hermes-session-key") == forwarded, token
|
||||
|
||||
|
||||
def test_run_events_stream_through(peer):
|
||||
with peer.client.stream("GET", "/api/peer/v1/runs/run_1/events", headers=_bearer("pass-message")) as resp:
|
||||
assert resp.status_code == 200
|
||||
assert resp.headers["content-type"].startswith("text/event-stream")
|
||||
body = resp.read()
|
||||
assert b"event: message.delta" in body and b"event: run.completed" in body
|
||||
|
||||
|
||||
def _gateway_raising(monkeypatch, exc: Exception) -> None:
|
||||
def fail(_request):
|
||||
raise exc
|
||||
monkeypatch.setattr(peer_routes, "_gateway_client",
|
||||
lambda _state: httpx.AsyncClient(transport=httpx.MockTransport(fail)))
|
||||
|
||||
|
||||
def test_a_sleeping_or_restarting_gateway_is_a_retryable_503(peer, monkeypatch):
|
||||
"""It is the gateway's state, not the dashboard's, so the dashboard's health stays as it was."""
|
||||
_gateway_raising(monkeypatch, httpx.ConnectError("connection refused"))
|
||||
errors_before = web_server.DASHBOARD_HEALTH.recent_error_count()
|
||||
resp = peer.client.get("/api/peer/health", headers=_bearer("pass-message"))
|
||||
assert resp.status_code == 503 and resp.json()["error"] == "peer_gateway_unavailable"
|
||||
assert int(resp.headers["retry-after"]) > 0
|
||||
assert web_server.DASHBOARD_HEALTH.recent_error_count() == errors_before
|
||||
|
||||
|
||||
def test_a_request_the_gateway_dropped_is_not_offered_for_retry(peer, monkeypatch):
|
||||
"""Sent, then the connection broke: the action may have run, so a retry could repeat it.
|
||||
A control action is still audited."""
|
||||
_gateway_raising(monkeypatch, httpx.RemoteProtocolError("server disconnected without a response"))
|
||||
resp = peer.client.post("/api/peer/api/jobs", headers=_bearer("pass-control"), json={"prompt": "x"})
|
||||
assert resp.status_code == 502 and resp.json()["error"] == "peer_gateway_dropped"
|
||||
assert "retry-after" not in resp.headers
|
||||
|
||||
lines = (get_hermes_home() / "logs" / "dashboard-auth.log").read_text(encoding="utf-8-sig").splitlines()
|
||||
control = [json.loads(line) for line in lines if '"peer_control"' in line]
|
||||
assert [(e["principal"], e["path"], e["status"]) for e in control] == [("usr_ctl", "/api/jobs", 502)]
|
||||
|
||||
|
||||
def test_a_gateway_refusing_the_agent_key_is_not_the_callers_fault(peer, monkeypatch):
|
||||
monkeypatch.setattr(_web_server_cron, "_gateway_api_target", lambda name, home: ("http://gateway.test", "stale-key"))
|
||||
resp = peer.client.get("/api/peer/health", headers=_bearer("pass-message"))
|
||||
assert resp.status_code == 502 and resp.json()["error"] == "peer_gateway_auth"
|
||||
|
||||
|
||||
def test_control_actions_are_audited_with_the_portal_user(peer):
|
||||
peer.client.post("/api/peer/v1/runs/run_1/approval", headers=_bearer("pass-control"), json={"choice": "once"})
|
||||
peer.client.post("/api/peer/v1/runs", headers=_bearer("pass-control"), json={}) # messaging: not a control action
|
||||
|
||||
lines = (get_hermes_home() / "logs" / "dashboard-auth.log").read_text(encoding="utf-8-sig").splitlines()
|
||||
control = [json.loads(line) for line in lines if '"peer_control"' in line]
|
||||
assert [(e["principal"], e["method"], e["path"], e["status"]) for e in control] == [
|
||||
("usr_ctl", "POST", "/v1/runs/run_1/approval", 202)]
|
||||
|
||||
|
||||
# ── Where a pass goes on this machine ────────────────────────────────────
|
||||
|
||||
|
||||
def test_upstream_is_the_profiles_listener_with_the_key_that_listener_checks(tmp_path, monkeypatch):
|
||||
"""Default profile: its listener and its API_SERVER_KEY. A multiplexed profile: the default
|
||||
listener's /p/<profile> mirror and that profile's own key (it never inherits the default's)."""
|
||||
default_home = tmp_path / "root"
|
||||
worker_home = default_home / "profiles" / "worker_alpha"
|
||||
worker_home.mkdir(parents=True)
|
||||
(default_home / "config.yaml").write_text(
|
||||
"gateway:\n multiplex_profiles: true\nplatforms:\n api_server:\n extra:\n port: 8650\n",
|
||||
encoding="utf-8")
|
||||
(worker_home / ".env").write_text("API_SERVER_KEY=worker-key-0123456789abcdef\n", encoding="utf-8")
|
||||
monkeypatch.setenv("HERMES_HOME", str(default_home))
|
||||
monkeypatch.setenv("API_SERVER_KEY", "default-key-0123456789abcdef")
|
||||
monkeypatch.delenv("API_SERVER_PORT", raising=False)
|
||||
monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)
|
||||
monkeypatch.setattr(_web_server_cron, "_cron_default_profile", lambda: "default")
|
||||
|
||||
assert _web_server_cron._gateway_api_target("default", default_home) == (
|
||||
"http://127.0.0.1:8650", "default-key-0123456789abcdef")
|
||||
assert _web_server_cron._gateway_api_target("worker_alpha", worker_home) == (
|
||||
"http://127.0.0.1:8650/p/worker_alpha", "worker-key-0123456789abcdef")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("env_key", "expected"), [
|
||||
("env-key-0123456789abcdef", "env-key-0123456789abcdef"), # a usable API_SERVER_KEY wins, as in the gateway
|
||||
("", "config-key-0123456789abcdef"),
|
||||
("short", "config-key-0123456789abcdef"), # too short for the gateway to use
|
||||
])
|
||||
def test_the_default_profiles_key_is_the_one_the_gateway_loads(tmp_path, monkeypatch, env_key, expected):
|
||||
monkeypatch.setenv("API_SERVER_KEY", env_key)
|
||||
monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)
|
||||
monkeypatch.setattr(_cfg_mod, "load_config", lambda: {
|
||||
"platforms": {"api_server": {"extra": {"port": 8700, "key": "config-key-0123456789abcdef"}}}})
|
||||
monkeypatch.setattr(_web_server_cron, "_cron_default_profile", lambda: "default")
|
||||
assert _web_server_cron._gateway_api_target("default", tmp_path) == ("http://127.0.0.1:8700", expected)
|
||||
80
tests/plugins/dashboard_auth/test_nous_peer_pass.py
Normal file
80
tests/plugins/dashboard_auth/test_nous_peer_pass.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""Nous Portal agent passes on the peer route.
|
||||
|
||||
The Portal mints short-lived passes for one agent (``aud`` = the agent's client_id). A pass that
|
||||
carries ``agent_dashboard:access`` is a dashboard sign-in; a peer pass carries only the peer
|
||||
permissions (``agents:message`` / ``agents:control``) and must open ``/api/peer`` and nothing else.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from starlette.applications import Starlette
|
||||
from starlette.responses import JSONResponse
|
||||
from starlette.routing import Route
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
import plugins.dashboard_auth.nous as nous_plugin
|
||||
from hermes_cli import web_server
|
||||
from hermes_cli.dashboard_auth import clear_providers, register_provider
|
||||
from hermes_cli.web_routers import peer as peer_routes
|
||||
from tests.plugins.dashboard_auth.test_nous_provider import _mint_token, _patched_jwks
|
||||
from tests.plugins.dashboard_auth.test_nous_provider import rsa_keypair as rsa_keypair # noqa: PLC0414 -- the self-alias
|
||||
# is load-bearing: it suppresses F811 for the pytest fixture parameter shadowing this import
|
||||
|
||||
PORTAL = "https://portal.example.com"
|
||||
PEER_SCOPES = "agents:message agents:control"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def provider(rsa_keypair):
|
||||
p = nous_plugin.NousDashboardAuthProvider(client_id="agent:inst123", portal_url=PORTAL)
|
||||
_patched_jwks(p, rsa_keypair)
|
||||
return p
|
||||
|
||||
|
||||
def test_a_peer_pass_is_not_a_dashboard_session(provider, rsa_keypair):
|
||||
token = _mint_token(rsa_keypair, scope=PEER_SCOPES)
|
||||
assert provider.verify_session(access_token=token) is None
|
||||
|
||||
principal = provider.verify_peer_pass(token=token)
|
||||
assert principal is not None
|
||||
assert (principal.principal, principal.provider) == ("usr_abc", "nous")
|
||||
assert set(principal.scopes) == {"agents:message", "agents:control"}
|
||||
|
||||
|
||||
def test_a_dashboard_sign_in_still_works_and_carries_no_peer_permission(provider, rsa_keypair):
|
||||
token = _mint_token(rsa_keypair) # scope agent_dashboard:access, what every dashboard grant mints
|
||||
assert provider.verify_session(access_token=token).user_id == "usr_abc"
|
||||
principal = provider.verify_peer_pass(token=token)
|
||||
assert principal is not None and not {"agents:message", "agents:control"} & set(principal.scopes)
|
||||
|
||||
|
||||
def test_a_pass_for_another_agent_is_not_recognised(provider, rsa_keypair):
|
||||
assert provider.verify_peer_pass(token=_mint_token(rsa_keypair, aud="agent:other", scope=PEER_SCOPES)) is None
|
||||
assert provider.verify_peer_pass(token="not-a-jwt") is None
|
||||
|
||||
|
||||
def test_on_the_dashboard_a_peer_pass_opens_the_peer_route_and_nothing_else(provider, rsa_keypair, monkeypatch):
|
||||
seen: list[str] = []
|
||||
|
||||
async def gateway(request):
|
||||
seen.append(request.url.path)
|
||||
return JSONResponse({"status": "ok"})
|
||||
transport = httpx.ASGITransport(app=Starlette(routes=[Route("/health", gateway)]))
|
||||
monkeypatch.setattr(peer_routes, "_gateway_client", lambda _state: httpx.AsyncClient(transport=transport))
|
||||
monkeypatch.setattr(peer_routes, "_upstream", lambda profile: ("http://gateway.test", "agent-key-0123456789"))
|
||||
clear_providers()
|
||||
register_provider(provider)
|
||||
state = web_server.app.state
|
||||
prev = {k: getattr(state, k, None) for k in ("bound_host", "bound_port", "auth_required")}
|
||||
state.bound_host, state.bound_port, state.auth_required = "agent.example.com", 443, True
|
||||
peer_pass = {"Authorization": f"Bearer {_mint_token(rsa_keypair, scope=PEER_SCOPES)}"}
|
||||
try:
|
||||
with TestClient(web_server.app, base_url="https://agent.example.com") as client:
|
||||
assert client.get("/api/sessions", headers=peer_pass).status_code == 401
|
||||
assert client.get("/api/peer/health", headers=peer_pass).status_code == 200
|
||||
finally:
|
||||
clear_providers()
|
||||
for key, value in prev.items():
|
||||
setattr(state, key, value)
|
||||
assert seen == ["/health"]
|
||||
@@ -1178,6 +1178,19 @@ The bundled first consumer is the **drain** provider (`plugins/dashboard_auth/dr
|
||||
|
||||
Custom providers can implement `supports_token`/`verify_token` the same way to expose their own machine-authable endpoints.
|
||||
|
||||
### Peer passes (`/api/peer`)
|
||||
|
||||
A provider can also accept **peer passes** (`supports_peer_pass = True` + `verify_peer_pass(token=...)`): short-lived tokens minted for one agent that let another Hermes agent call this agent's API server through the dashboard, without the agent's `API_SERVER_KEY`.
|
||||
|
||||
- `/api/peer/<path>` forwards to the gateway API server on loopback and adds the API server key on the way; `/api/peer/p/<profile>/<path>` reaches one profile, named as the API server's `/p/<profile>/` prefix names it (`hermes` is the default profile unless a profile has that name).
|
||||
- Each path needs a permission the pass carries. `agents:message` covers what `hermes peer` uses: health, capabilities, sessions (list, create, get, chat), runs (start, status, events, stop). `agents:control` includes messaging and adds the rest of the user-facing API: run approvals, clarify, steer and resolve-unknown; session fork, messages, model, rename and delete; scheduled jobs; models, skills and toolsets; chat completions and responses. Only `agents:control` may set `X-Hermes-Session-Key`, which picks the API server's memory scope.
|
||||
- Any other path is never forwarded, including `/api/cron/fire`, platform event intake, RoomLink grants and `/health/detailed`.
|
||||
- A gateway that is asleep or restarting answers 503 with `Retry-After`. A request the gateway dropped after receiving it answers 502 `peer_gateway_dropped` with no retry hint, because it may have run.
|
||||
- Only a peer pass opens `/api/peer`. It is checked apart from `verify_token`, so a pass never authorises another provider's token routes, and a pass without the dashboard scope never opens a dashboard session.
|
||||
- Control actions are written to `logs/dashboard-auth.log` as `peer_control` events with the pass holder, and jobs created through the route record the holder as `peer_principal` in their origin.
|
||||
|
||||
The bundled Nous provider verifies peer passes with the same Portal keys and audience as dashboard sign-ins; dashboard sign-ins carry `agent_dashboard:access`, peer passes carry only the peer permissions.
|
||||
|
||||
### Verifying the gate is on
|
||||
|
||||
```bash
|
||||
|
||||
Reference in New Issue
Block a user