Skip to content

The agent that grows with you

feat(relay): ambient token endpoint mode for gateway.idp.token_url (#84074)

victor-kyriazakose9579a98966b
diff --git a/gateway/relay/__init__.py b/gateway/relay/__init__.py
index 77481d8a8fb..1e6c25bd75e 100644
--- a/gateway/relay/__init__.py
+++ b/gateway/relay/__init__.py
@@ -19,8 +19,20 @@ that don't set it are unaffected — exactly the same shape as ``gateway.proxy_u
from __future__ import annotations
import os
+import re
from typing import Optional
+# Shape gate for ambient-endpoint token bodies (mode 1b in
+# _resolve_relay_identity_token). Accepts a bearer-token-shaped string:
+# either a multi-segment dotted token (JWT: header.payload.signature) or a
+# single long opaque token (>= 32 chars of the base64url alphabet). Short
+# bare words — 'unauthorized', 'error', 'null' — match the alphabet but are
+# plain-text error bodies, not credentials, and must fail closed.
+_AMBIENT_TOKEN_SHAPE = re.compile(
+ r"[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+){2,}" # JWT-like: 3+ dotted segments
+ r"|[A-Za-z0-9_-]{32,}" # long opaque bearer token
+)
+
def relay_url() -> Optional[str]:
"""The connector relay endpoint URL, or None when relay is not configured.
@@ -492,14 +504,22 @@ def _resolve_relay_identity_token() -> str:
"""Resolve the caller-identity bearer token the connector introspects to a tenant.
Canonical resolver shared by the runtime self-provision path and the
- ``hermes gateway enroll`` CLI. Two modes, in precedence order:
+ ``hermes gateway enroll`` CLI. Three modes, in precedence order:
1. **Generic OIDC client-credentials** (air-gapped / self-hosted-IdP, NO
Nous Portal): when ``gateway.idp.token_url`` (or
- ``GATEWAY_RELAY_IDP_TOKEN_URL``) is configured, obtain a workload access
- token via the OAuth2 ``client_credentials`` grant against the operator's
- own IdP (Entra; Authentik in the sandbox). The connector's Seam-A OIDC
+ ``GATEWAY_RELAY_IDP_TOKEN_URL``) is configured together with a client
+ id/secret, obtain a workload access token via the OAuth2
+ ``client_credentials`` grant against the operator's own IdP (Entra;
+ Keycloak; Authentik in the sandbox). The connector's Seam-A OIDC
verifier reads a claim (default ``tid``) off it as the tenant.
+ 1b. **Ambient token endpoint**: when ``token_url`` is configured with
+ NEITHER client_id nor client_secret, the URL is treated as a metadata-server-style
+ ambient credential endpoint (e.g. Domino's
+ ``$DOMINO_API_PROXY/access-token``): a plain GET whose response body
+ IS the token — either a raw JWT string or a JSON envelope with an
+ ``access_token`` field. No client registration involved; possession
+ of the (typically loopback) endpoint is the credential.
2. **Nous Portal** (default): ``resolve_nous_access_token()`` — existing
managed/hosted behaviour.
@@ -528,16 +548,56 @@ def _resolve_relay_identity_token() -> str:
return resolve_nous_access_token()
- # Mode 1 — generic OAuth2 client_credentials grant.
import json
import urllib.error
import urllib.parse
import urllib.request
+ if not client_id and not client_secret:
+ # Mode 1b — ambient token endpoint (no client credentials configured).
+ # Plain GET; the body is the token, raw or JSON-enveloped.
+ req = urllib.request.Request(
+ token_url,
+ method="GET",
+ headers={"Accept": "application/json, text/plain"},
+ )
+ with urllib.request.urlopen(req, timeout=15.0) as resp:
+ body = resp.read().decode().strip()
+ token = ""
+ if body.startswith("{"):
+ try:
+ envelope_token = (json.loads(body) or {}).get("access_token")
+ except ValueError:
+ envelope_token = None
+ # Same contract as the client_credentials path below: the value
+ # must be a non-empty STRING. No shape gate here — a JSON envelope
+ # is a deliberate token response (and opaque tokens may use the
+ # standard-base64 alphabet the raw-body gate would reject).
+ if isinstance(envelope_token, str):
+ token = envelope_token.strip()
+ elif _AMBIENT_TOKEN_SHAPE.fullmatch(body):
+ token = body
+ if not token:
+ raise RuntimeError(
+ "no client_id/client_secret configured, so gateway.idp.token_url was "
+ "treated as an ambient token endpoint (GET), but the response body "
+ "was not a token. For the OAuth2 client_credentials grant, configure "
+ "client_id and client_secret alongside token_url."
+ )
+ return token
+
if not client_id or not client_secret:
+ # Exactly one credential configured: this is a mistyped client_credentials
+ # setup, not an ambient endpoint. Keep the loud error (never GET the IdP).
+ missing = "client_secret" if client_id else "client_id"
raise RuntimeError(
- "gateway.idp.token_url configured but client_id/client_secret missing"
+ f"gateway.idp.token_url is configured with a partial client credential "
+ f"({missing} missing). Configure both client_id and client_secret for "
+ f"the OAuth2 client_credentials grant, or neither to treat token_url "
+ f"as an ambient token endpoint (plain GET returning the token)."
)
+
+ # Mode 1 — generic OAuth2 client_credentials grant.
form = {
"grant_type": "client_credentials",
"client_id": client_id,
diff --git a/tests/gateway/relay/test_identity_token_resolver.py b/tests/gateway/relay/test_identity_token_resolver.py
index b585faec0ab..108412c18d5 100644
--- a/tests/gateway/relay/test_identity_token_resolver.py
+++ b/tests/gateway/relay/test_identity_token_resolver.py
@@ -3,13 +3,17 @@
Covers gateway.relay._resolve_relay_identity_token() — the canonical resolver
shared by the runtime self-provision path and the `hermes gateway enroll` CLI.
-Two modes:
+Three modes:
1. Generic OAuth2 client_credentials when gateway.idp.token_url (or
- GATEWAY_RELAY_IDP_TOKEN_URL) is configured (air-gapped / self-hosted-IdP).
+ GATEWAY_RELAY_IDP_TOKEN_URL) is configured WITH client credentials
+ (air-gapped / self-hosted-IdP).
+ 1b. Ambient token endpoint when token_url is configured WITHOUT client
+ credentials: plain GET, body is the token (raw JWT or JSON envelope).
+ The metadata-server pattern (e.g. Domino's $DOMINO_API_PROXY/access-token).
2. Nous Portal (resolve_nous_access_token) otherwise — the default.
-The HTTP POST and the Nous resolver are monkeypatched; these prove the mode
-SELECTION, the client_credentials request shape, and the fail-closed paths.
+The HTTP calls and the Nous resolver are monkeypatched; these prove the mode
+SELECTION, the request shapes, and the fail-closed paths.
"""
from __future__ import annotations
@@ -75,3 +79,179 @@ def test_raises_when_no_access_token_in_response(monkeypatch):
monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
with pytest.raises(RuntimeError, match="no access_token"):
relay._resolve_relay_identity_token()
+
+
+# ---------------------------------------------------------------------------
+# Mode 1b — ambient token endpoint (token_url set, NO client credentials).
+# The metadata-server pattern: plain GET, response body IS the token, either
+# a raw JWT string (Domino's $DOMINO_API_PROXY/access-token) or a JSON
+# envelope ({"access_token": ...}).
+# ---------------------------------------------------------------------------
+
+_FAKE_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.c2ln"
+
+
+def test_ambient_get_when_no_client_credentials(monkeypatch):
+ """token_url without client_id/secret selects a plain GET, not a raise."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://proxy.local/access-token")
+
+ captured = {}
+
+ def fake_urlopen(req, timeout=None):
+ captured["url"] = req.full_url
+ captured["method"] = req.get_method()
+ captured["body"] = req.data
+ return io.BytesIO((_FAKE_JWT + "\n").encode())
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+
+ token = relay._resolve_relay_identity_token()
+ assert token == _FAKE_JWT # raw body, whitespace-trimmed
+ assert captured["url"] == "https://proxy.local/access-token"
+ assert captured["method"] == "GET"
+ assert captured["body"] is None # no form payload on the ambient path
+
+
+def test_ambient_accepts_json_envelope(monkeypatch):
+ """Ambient endpoints that return {"access_token": ...} JSON also work."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://proxy.local/access-token")
+
+ def fake_urlopen(req, timeout=None):
+ return io.BytesIO(json.dumps({"access_token": _FAKE_JWT}).encode())
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ assert relay._resolve_relay_identity_token() == _FAKE_JWT
+
+
+ "envelope",
+ [
+ {"access_token": 12345678901234567890123456789012}, # number, not string
+ {"access_token": True}, # boolean: str() would coerce to 'True'
+ {"access_token": {"nested": "x"}}, # object
+ {"access_token": ""}, # empty string
+ {"access_token": None},
+ {"token": "wrong-field-name"},
+ ],
+)
+def test_ambient_rejects_non_string_envelope_values(monkeypatch, envelope):
+ """access_token in a JSON envelope must be a non-empty STRING — the same
+ contract as the client_credentials path. No str() coercion of numbers,
+ booleans, or objects into 'tokens'."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://proxy.local/access-token")
+
+ def fake_urlopen(req, timeout=None):
+ return io.BytesIO(json.dumps(envelope).encode())
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ with pytest.raises(RuntimeError, match="ambient"):
+ relay._resolve_relay_identity_token()
+
+
+def test_ambient_rejects_non_token_body(monkeypatch):
+ """A body that is neither a JWT-ish string nor a token envelope fails loudly."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://proxy.local/access-token")
+
+ def fake_urlopen(req, timeout=None):
+ return io.BytesIO(b"<html>404 not found</html>")
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ with pytest.raises(RuntimeError, match="ambient"):
+ relay._resolve_relay_identity_token()
+
+
+def test_ambient_rejects_empty_body(monkeypatch):
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://proxy.local/access-token")
+
+ def fake_urlopen(req, timeout=None):
+ return io.BytesIO(b" \n")
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ with pytest.raises(RuntimeError, match="ambient"):
+ relay._resolve_relay_identity_token()
+
+
+def test_ambient_rejects_short_plaintext_error_words(monkeypatch):
+ """A terse plain-text error body (e.g. 'unauthorized') must not be
+ returned as a credential — it matches the base64url alphabet but is
+ neither a JWT nor plausibly an opaque token."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://proxy.local/access-token")
+
+ for body in ("unauthorized", "error", "access_denied", "null", "forbidden"):
+ def fake_urlopen(req, timeout=None, _b=body):
+ return io.BytesIO(_b.encode())
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ with pytest.raises(RuntimeError, match="ambient"):
+ relay._resolve_relay_identity_token()
+
+
+def test_ambient_accepts_long_opaque_token(monkeypatch):
+ """Non-JWT opaque bearer tokens (long random strings) still work."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://proxy.local/access-token")
+ opaque = "v2_9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b"
+
+ def fake_urlopen(req, timeout=None):
+ return io.BytesIO(opaque.encode())
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ assert relay._resolve_relay_identity_token() == opaque
+
+
+def test_client_credentials_still_selected_when_creds_present(monkeypatch):
+ """Presence of client creds keeps the POST grant — ambient never hijacks it."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://idp.test/token")
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_ID", "agent-client")
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_SECRET", "shh")
+
+ captured = {}
+
+ def fake_urlopen(req, timeout=None):
+ captured["method"] = req.get_method()
+ return io.BytesIO(json.dumps({"access_token": "cc-token"}).encode())
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ assert relay._resolve_relay_identity_token() == "cc-token"
+ assert captured["method"] == "POST"
+
+
+def test_partial_credentials_client_id_only_raises_without_get(monkeypatch):
+ """client_id without client_secret is a misconfig: loud error, no ambient GET."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://idp.test/token")
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_ID", "agent-client")
+
+ def fake_urlopen(req, timeout=None):
+ raise AssertionError("no HTTP request may be issued on partial credentials")
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ with pytest.raises(RuntimeError, match="client_secret missing"):
+ relay._resolve_relay_identity_token()
+
+
+def test_partial_credentials_client_secret_only_raises_without_get(monkeypatch):
+ """client_secret without client_id is a misconfig: loud error, no ambient GET."""
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://idp.test/token")
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_SECRET", "shh")
+
+ def fake_urlopen(req, timeout=None):
+ raise AssertionError("no HTTP request may be issued on partial credentials")
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ with pytest.raises(RuntimeError, match="client_id missing"):
+ relay._resolve_relay_identity_token()
+
+
+def test_ambient_via_config_yaml(monkeypatch):
+ """Ambient mode also engages when token_url comes from config.yaml, not env."""
+ monkeypatch.setattr(
+ "gateway.run._load_gateway_config",
+ lambda: {"gateway": {"idp": {"token_url": "https://proxy.local/access-token"}}},
+ raising=False,
+ )
+
+ def fake_urlopen(req, timeout=None):
+ assert req.get_method() == "GET"
+ return io.BytesIO(_FAKE_JWT.encode())
+
+ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
+ assert relay._resolve_relay_identity_token() == _FAKE_JWT
diff --git a/website/docs/user-guide/messaging/relay.md b/website/docs/user-guide/messaging/relay.md
index a84852134b3..d12ae3edc56 100644
--- a/website/docs/user-guide/messaging/relay.md
+++ b/website/docs/user-guide/messaging/relay.md
@@ -61,9 +61,13 @@ What it does:
1. Resolves a fresh Nous Portal access token from your existing login
(`~/.hermes/auth.json`) — this proves which Nous org (tenant) you own. If
- `gateway.idp.token_url` is configured, a generic OAuth2 client-credentials
- token from your own IdP is used instead (the air-gapped / self-hosted-IdP
- path, no Nous Portal involved).
+ `gateway.idp.token_url` is configured, your own IdP is used instead (the
+ air-gapped / self-hosted-IdP path, no Nous Portal involved): with
+ `client_id`/`client_secret` configured it performs a generic OAuth2
+ client-credentials grant; with neither configured the URL is treated as an
+ ambient token endpoint (plain GET whose response body is the token — the
+ metadata-server pattern, e.g. Domino's `$DOMINO_API_PROXY/access-token`).
+ Configuring only one of the two credentials is an error.
2. POSTs the enrollment token and a gateway id to the connector's
`/relay/enroll` endpoint over TLS.
3. The connector verifies the token (signature, single-use, tenant match),
@@ -105,7 +109,7 @@ separate feature flag. Deployments that don't set it are unaffected.
| `GATEWAY_RELAY_WAKE_URL` / `gateway.relay_wake_url` | env / `config.yaml` | Optional wake-poke target for idle/suspended gateways. |
| `GATEWAY_RELAY_PLATFORMS` | env | Comma-separated list of platforms this gateway fronts over one connection (e.g. `discord,telegram`). Usually stamped by the deployment/orchestrator. |
| `GATEWAY_RELAY_BOT_IDS` | env | JSON map of per-platform bot identities, e.g. `{"discord": {"botId": "…"}}`. Paired with `GATEWAY_RELAY_PLATFORMS`. |
-| `gateway.idp.token_url` | `config.yaml` | When set, enrollment/provisioning authenticates via generic OAuth2 client-credentials against your own IdP instead of Nous Portal. |
+| `gateway.idp.token_url` | `config.yaml` | When set, enrollment/provisioning authenticates against your own IdP instead of Nous Portal: OAuth2 client-credentials when `gateway.idp.client_id`/`client_secret` are also set; otherwise an ambient token endpoint (plain GET returning the token, raw or `{"access_token": …}`). |
## Supported capabilities