Skip to content

The agent that grows with you

fix(config-remote): credentials go only to the configured https origin, never through a redirect

Ben Barclay55805716e745
diff --git a/plugins/config_backends/remote/client.py b/plugins/config_backends/remote/client.py
index c95e78cf48c..112eabae095 100644
--- a/plugins/config_backends/remote/client.py
+++ b/plugins/config_backends/remote/client.py
@@ -15,6 +15,7 @@ from pathlib import Path
from typing import Any, Dict, Optional
from .credentials import plane_token
+from .destination import checked_url, open_credentialed
DEFAULT_URL = "https://config-config.nousresearch.com"
URL_ENV = "HERMES_CONFIG_REMOTE_URL"
@@ -43,6 +44,8 @@ class TransportError(RuntimeError):
def base_url() -> str:
+ """The configured plane origin (+ path prefix). Display only: :func:`request` re-checks it
+ against the credential destination policy before anything is sent."""
return (os.environ.get(URL_ENV, "").strip() or DEFAULT_URL).rstrip("/")
@@ -69,8 +72,12 @@ def _retry_after(value: Optional[str]) -> Optional[float]:
def request(method: str, home: Path, profile: str, *, etag: Optional[str] = None,
body: Optional[Dict[str, Any]] = None) -> Response:
- """One call to ``/v1/config/self?profile=<profile>`` as ``home``'s agent."""
- url = f"{base_url()}/v1/config/self?{urllib.parse.urlencode({'profile': profile})}"
+ """One call to ``/v1/config/self?profile=<profile>`` as ``home``'s agent.
+
+ The destination is checked before the bearer is resolved, and the request never follows a
+ redirect (:mod:`.destination`): raises its :class:`CredentialDestinationError` instead."""
+ plane = checked_url(base_url(), env_name=URL_ENV)
+ url = f"{plane}/v1/config/self?{urllib.parse.urlencode({'profile': profile})}"
headers = {
"Authorization": f"Bearer {plane_token(home)}",
"X-Hermes-Instance-Id": instance_id(),
@@ -84,7 +91,7 @@ def request(method: str, home: Path, profile: str, *, etag: Optional[str] = None
headers["If-None-Match"] = etag
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
- with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT_S) as resp:
+ with open_credentialed(req, timeout=_HTTP_TIMEOUT_S) as resp:
return Response(resp.status, _parse_body(resp.read()), resp.headers.get("ETag"),
_retry_after(resp.headers.get("Retry-After")))
except urllib.error.HTTPError as exc: # every non-2xx, including 304
diff --git a/plugins/config_backends/remote/credentials.py b/plugins/config_backends/remote/credentials.py
index ec088a40c7b..eeb7ecff748 100644
--- a/plugins/config_backends/remote/credentials.py
+++ b/plugins/config_backends/remote/credentials.py
@@ -85,6 +85,8 @@ def _idp_token() -> str:
f"{IDP_ENV_PREFIX}TOKEN_URL is set but {IDP_ENV_PREFIX}CLIENT_ID / {IDP_ENV_PREFIX}CLIENT_SECRET "
"are not: Remote Config needs the OAuth2 client-credentials grant (both values in .env).",
retryable=False)
+ from .destination import CredentialDestinationError, checked_url, open_credentialed
+ checked_url(token_url, env_name=f"{IDP_ENV_PREFIX}TOKEN_URL") # before the secret leaves the process
key = (token_url, client_id, scope)
now = time.monotonic()
with _IDP_LOCK:
@@ -98,8 +100,10 @@ def _idp_token() -> str:
token_url, data=urllib.parse.urlencode(form).encode(), method="POST",
headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"})
try:
- with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT_S) as resp:
+ with open_credentialed(req, timeout=_HTTP_TIMEOUT_S) as resp:
payload = json.loads(resp.read().decode() or "{}")
+ except CredentialDestinationError:
+ raise
except Exception as exc: # noqa: BLE001 — HTTP and network errors alike; the message has no secret
raise PlaneCredentialError(f"IdP token request to {token_url} failed: {exc}", retryable=True) from exc
access_token = payload.get("access_token") if isinstance(payload, dict) else None
diff --git a/plugins/config_backends/remote/destination.py b/plugins/config_backends/remote/destination.py
new file mode 100644
index 00000000000..b02003fa3f5
--- /dev/null
+++ b/plugins/config_backends/remote/destination.py
@@ -0,0 +1,86 @@
+"""Where Remote Config may send a credential (the plane bearer, the IdP client secret).
+
+The plane URL and the IdP token URL are operator-selected (D19: the plane defaults to
+``https://config-config.nousresearch.com`` and an on-prem deployment points it elsewhere), so this
+is a transport policy, not an allow-list of hosts:
+
+- ``https`` only; plain ``http`` only to a loopback host (tests, local development);
+- one unambiguous origin: no userinfo, query or fragment in the configured URL;
+- a credentialed request never follows a redirect, so the credential reaches only the origin the
+ operator configured (a 3xx is refused, not re-authorized hop by hop).
+"""
+from __future__ import annotations
+
+import ipaddress
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from .credentials import PlaneCredentialError
+
+
+class CredentialDestinationError(PlaneCredentialError):
+ """A credential would go somewhere the transport policy forbids. Never retryable: the
+ configuration (or the server's redirect) has to change."""
+
+ def __init__(self, message: str) -> None:
+ super().__init__(message, retryable=False)
+
+
+def _is_loopback(host: str) -> bool:
+ if host == "localhost":
+ return True
+ try:
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ return False
+
+
+def checked_url(url: str, *, env_name: str) -> str:
+ """``url`` when a credential may be sent to it, else :class:`CredentialDestinationError`."""
+ try:
+ parts = urllib.parse.urlsplit(url)
+ host = (parts.hostname or "").lower()
+ parts.port # noqa: B018 — raises ValueError on a malformed port
+ except ValueError as exc:
+ raise CredentialDestinationError(f"{env_name}={url!r} is not a valid URL: {exc}") from exc
+ if not host:
+ raise CredentialDestinationError(f"{env_name}={url!r} has no host.")
+ if parts.username is not None or parts.password is not None or parts.query or parts.fragment:
+ raise CredentialDestinationError(
+ f"{env_name} must be a plain origin and path (no user info, query or fragment); "
+ "Remote Config does not send credentials to an ambiguous destination.")
+ scheme = parts.scheme.lower()
+ if scheme == "https" or (scheme == "http" and _is_loopback(host)):
+ return url
+ raise CredentialDestinationError(
+ f"{env_name} must be an https:// URL (plain http is accepted only for localhost, "
+ f"127.0.0.1 or ::1); Remote Config does not send credentials to {parts.scheme or 'no'}://{host}.")
+
+
+class _RefuseRedirect(urllib.request.BaseHandler):
+ """Every 3xx (308 included, whatever the interpreter's redirect handler knows) is refused."""
+
+ def _refuse(self, req, fp, code, msg, headers):
+ fp.close()
+ raise CredentialDestinationError(
+ f"{req.get_full_url()} answered HTTP {code} redirecting to {headers.get('Location')!r}; "
+ "Remote Config never follows a redirect with credentials. Point the URL at the final "
+ "destination.")
+
+ http_error_301 = http_error_302 = http_error_303 = http_error_307 = http_error_308 = _refuse
+
+
+# build_opener drops its default HTTPRedirectHandler when given a subclass only; give it ours
+# AND remove the default explicitly so nothing earlier in the chain follows a 3xx.
+_OPENER = urllib.request.OpenerDirector()
+for _handler in (urllib.request.ProxyHandler(), urllib.request.UnknownHandler(), urllib.request.HTTPHandler(),
+ urllib.request.HTTPSHandler(), urllib.request.HTTPDefaultErrorHandler(), _RefuseRedirect(),
+ urllib.request.HTTPErrorProcessor()):
+ _OPENER.add_handler(_handler)
+
+
+def open_credentialed(req: urllib.request.Request, *, timeout: float):
+ """``urlopen`` for a request carrying a credential: a 3xx raises
+ :class:`CredentialDestinationError` instead of being followed."""
+ return _OPENER.open(req, timeout=timeout)
diff --git a/tests/plugins/config_backends/test_remote_credential_destination.py b/tests/plugins/config_backends/test_remote_credential_destination.py
new file mode 100644
index 00000000000..bb84e9dc2ca
--- /dev/null
+++ b/tests/plugins/config_backends/test_remote_credential_destination.py
@@ -0,0 +1,233 @@
+"""Credential destination policy (andrexibiza P1-A): the plane bearer and the IdP client secret go
+only to the configured https origin (plain http only to loopback) and never follow a redirect.
+
+Every refusal is asserted BEFORE the credential leaves the process: a capturing transport (or a
+real second listener for redirects) proves nothing was sent.
+"""
+from __future__ import annotations
+
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+import pytest
+
+from plugins.config_backends.remote import client
+from plugins.config_backends.remote import credentials as cred_mod
+from plugins.config_backends.remote import destination
+from plugins.config_backends.remote.credentials import PlaneCredentialError
+
+from .stub_plane import CLIENT_ID, CLIENT_SECRET, INSTANCE, StubPlane, remote_env
+
+PLANE_BEARER = "plane-bearer-secret"
+
+
+class _Listener:
+ """A loopback HTTP server on its own port (its own origin) recording every request; answers
+ each with ``status`` and an optional ``Location``."""
+
+ def __init__(self, status: int = 200, location: str | None = None) -> None:
+ self.seen: list[dict] = []
+ listener = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, format, *args) -> None: # noqa: A002 — base signature
+ pass
+
+ def _any(self):
+ n = int(self.headers.get("Content-Length") or 0)
+ listener.seen.append({"path": self.path, "auth": self.headers.get("Authorization"),
+ "body": self.rfile.read(n).decode() if n else ""})
+ self.send_response(status)
+ if location:
+ self.send_header("Location", location)
+ self.send_header("Content-Length", "2")
+ self.end_headers()
+ self.wfile.write(b"{}")
+
+ do_GET = do_POST = do_PATCH = _any
+
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.url = f"http://127.0.0.1:{self._server.server_address[1]}"
+ threading.Thread(target=self._server.serve_forever, daemon=True).start()
+
+ def close(self) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+
+
+def listeners():
+ made: list[_Listener] = []
+
+ def make(**kw) -> _Listener:
+ made.append(_Listener(**kw))
+ return made[-1]
+
+ yield make
+ for listener in made:
+ listener.close()
+
+
+def nous_bearer(monkeypatch, tmp_path):
+ """Cloud credential path with a known bearer; no IdP configured."""
+ for k in ("GATEWAY_RELAY_IDP_TOKEN_URL", "GATEWAY_RELAY_IDP_CLIENT_ID", "GATEWAY_RELAY_IDP_CLIENT_SECRET"):
+ monkeypatch.delenv(k, raising=False)
+ monkeypatch.setenv("HERMES_CONFIG_INSTANCE_ID", INSTANCE)
+ resolved: list[Path] = []
+
+ def token(home):
+ resolved.append(home)
+ return PLANE_BEARER
+
+ monkeypatch.setattr(client, "plane_token", token)
+ return resolved
+
+
+def captured(monkeypatch):
+ """Replace the credentialed opener: record what WOULD be sent, send nothing."""
+ sent: list = []
+
+ class _Resp:
+ status, headers = 200, {}
+
+ def read(self):
+ return b"{}"
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def open_(req, timeout):
+ sent.append(req)
+ return _Resp()
+
+ monkeypatch.setattr(destination._OPENER, "open", open_)
+ return sent
+
+
+# --- config plane bearer ---------------------------------------------------------------------
+
+ "http://foreign.example:8443/plane", # ambient non-loopback http
+ "http://config-config.nousresearch.com", # HTTPS -> HTTP downgrade of the real default
+ "ftp://plane.example",
+ "https://user:[email protected]", # userinfo: ambiguous destination
+ "https://plane.example/?next=https://evil.example",
+ "https://",
+])
+def test_bearer_refused_before_send_for_forbidden_plane_url(monkeypatch, tmp_path, nous_bearer, captured, url):
+ monkeypatch.setenv(client.URL_ENV, url)
+ with pytest.raises(destination.CredentialDestinationError) as exc:
+ client.request("GET", tmp_path, "default")
+ assert exc.value.retryable is False
+ assert captured == [] # nothing left the process
+ assert nous_bearer == [] # the bearer was never even resolved
+
+
[email protected]("url, expect", [
+ ("", "https://config-config.nousresearch.com/v1/config/self?profile=default"), # D19 default
+ ("https://config.corp.internal:9443/plane/", "https://config.corp.internal:9443/plane/v1/config/self?profile=default"),
+ ("http://localhost:8080", "http://localhost:8080/v1/config/self?profile=default"),
+ ("http://127.0.0.1:9", "http://127.0.0.1:9/v1/config/self?profile=default"),
+ ("http://[::1]:9", "http://[::1]:9/v1/config/self?profile=default"),
+])
+def test_bearer_sent_to_allowed_plane_origin(monkeypatch, tmp_path, nous_bearer, captured, url, expect):
+ monkeypatch.setenv(client.URL_ENV, url)
+ resp = client.request("GET", tmp_path, "default")
+ assert resp.status == 200
+ assert [r.full_url for r in captured] == [expect]
+ assert captured[0].get_header("Authorization") == f"Bearer {PLANE_BEARER}"
+
+
[email protected]("code", [301, 302, 303, 307, 308])
+def test_plane_redirect_is_not_followed_with_the_bearer(monkeypatch, tmp_path, nous_bearer, listeners, code):
+ """A real cross-origin redirect: the plane answers 3xx to another origin; the target never sees
+ a request, let alone the bearer, and the refusal is not retried."""
+ target = listeners()
+ plane = listeners(status=code, location=f"{target.url}/v1/config/self?profile=default")
+ monkeypatch.setenv(client.URL_ENV, plane.url)
+
+ with pytest.raises(destination.CredentialDestinationError) as exc:
+ client.request("GET", tmp_path, "default")
+
+ assert exc.value.retryable is False
+ assert len(plane.seen) == 1 and plane.seen[0]["auth"] == f"Bearer {PLANE_BEARER}"
+ assert target.seen == []
+
+
+def test_boot_fails_closed_on_forbidden_plane_url_without_retry(monkeypatch, tmp_path):
+ """Through the real backend: a forbidden destination is a configuration error, so boot fails
+ closed at once (no retry sleeps) and nothing is sent."""
+ from hermes_cli.config_backend import ConfigBackendUnavailable
+ from plugins.config_backends import remote as remote_pkg
+ from plugins.config_backends.remote import backend as backend_mod
+
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ with StubPlane() as plane:
+ for k, v in remote_env(plane).items():
+ monkeypatch.setenv(k, v)
+ monkeypatch.setenv(client.URL_ENV, plane.url.replace("127.0.0.1", "plane.example"))
+ sleeps: list = []
+ monkeypatch.setattr(backend_mod.time, "sleep", sleeps.append)
+ remote_pkg._reset_for_tests()
+ cred_mod._IDP_CACHE.clear()
+ try:
+ with pytest.raises(ConfigBackendUnavailable, match="https"):
+ remote_pkg.get_remote_backend().boot(home)
+ finally:
+ remote_pkg._reset_for_tests()
+ cred_mod._IDP_CACHE.clear()
+ assert sleeps == []
+ assert plane.requests == [] and plane.token_requests == 0
+
+
+# --- IdP client secret ------------------------------------------------------------------------
+
+def _idp_env(monkeypatch, token_url: str) -> None:
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", token_url)
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_ID", CLIENT_ID)
+ monkeypatch.setenv("GATEWAY_RELAY_IDP_CLIENT_SECRET", CLIENT_SECRET)
+ cred_mod._IDP_CACHE.clear()
+
+
+ "http://foreign.example:8443/token",
+ "http://idp.corp.internal/token", # downgrade: on-prem must still be https
+ "https://user:[email protected]/token",
+ "https://idp.example/token#frag",
+])
+def test_idp_secret_refused_before_send_for_forbidden_token_url(monkeypatch, captured, url):
+ _idp_env(monkeypatch, url)
+ with pytest.raises(destination.CredentialDestinationError) as exc:
+ cred_mod._idp_token()
+ assert exc.value.retryable is False
+ assert captured == []
+
+
+def test_idp_secret_sent_to_allowed_on_prem_https(monkeypatch, captured):
+ _idp_env(monkeypatch, "https://idp.corp.internal/oauth2/token")
+ with pytest.raises(PlaneCredentialError, match="no access_token"): # the capture answers {}
+ cred_mod._idp_token()
+ assert [r.full_url for r in captured] == ["https://idp.corp.internal/oauth2/token"]
+ assert CLIENT_SECRET in captured[0].data.decode()
+
+
[email protected]("code", [302, 307, 308])
+def test_idp_redirect_is_not_followed_with_the_secret(monkeypatch, listeners, code):
+ target = listeners()
+ idp = listeners(status=code, location=f"{target.url}/token")
+ _idp_env(monkeypatch, f"{idp.url}/token")
+
+ with pytest.raises(destination.CredentialDestinationError) as exc:
+ cred_mod._idp_token()
+
+ assert exc.value.retryable is False
+ assert len(idp.seen) == 1 and CLIENT_SECRET in idp.seen[0]["body"]
+ assert target.seen == []