Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(hermes-plugin): retry the health probe when a gateway redirects to its login page (#5984)
Adonis68e66ec89989
diff --git a/examples/hermes-plugin/CONFIGURATION.md b/examples/hermes-plugin/CONFIGURATION.mdindex 1a42f741d..640e27a9e 100644--- a/examples/hermes-plugin/CONFIGURATION.md+++ b/examples/hermes-plugin/CONFIGURATION.md@@ -143,6 +143,39 @@ map can never assert tenant identity, and the plugin's own headers (authenticatitenant, actor) take precedence over the map. The client snapshots the map when itis built, so the headers also cover the startup `/health` probe.+The identity probe stays anonymous first, so no credential is ever sent to an unknown+host. Gateways that answer that anonymous request by *redirecting* to their own login+page are handled like `401`/`403`, but only on a connection that carries gateway headers+(`extra_headers` / `OPENVIKING_EXTRA_HEADERS`): those headers are what declare that an+authenticating gateway sits in front of the endpoint. Cloudflare Access returns `302` with+`Location: https://<team>.cloudflareaccess.com/cdn-cgi/access/login/<host>`, and such a+connection's probe is retried once with **only those gateway headers** — no API key, no+peer identity, since a gateway never asks for them, and no API key is required for that+retry either, because none is sent. If the gateway then lets the probe through to a server+that asks for credentials itself, that `401`/`403` is answered by the ordinary key retry+(bounded: two retries at most). Without that retry a protected server looks "reachable but+not OpenViking", the client is dropped, and memory stays unavailable even though every+authenticated request would have worked. A redirect that survives the gateway retry reports+the gateway and points at `extra_headers` instead of "not valid OpenViking", and the login+URL is never followed.++A `401`/`403` is the endpoint asking for credentials, and the status alone does not say+which kind. An OpenViking server wants the API key; a gateway that answers `401`/`403`+instead of redirecting (oauth2-proxy, many WAFs) wants its own headers. So the probe tries+the key when one is configured, and the gateway headers when they are configured. A+gateway-only deployment has no key to try, so it gets the gateway retry — gating that retry+on a key it never sends is what kept such a deployment from starting at all. With both+configured the key is tried first, as before, and the gateway headers are not retried a+second time.++A redirect on a connection with *no* gateway headers is not retried: a `3xx` from an+endpoint that has not been shown to be OpenViking is not authorization to resend the API+key, so it keeps failing exactly as it did before, and no credential leaves the process.+Every probe request sets `follow_redirects=False`, so the login URL is never fetched even+when a `Location` is present. A `3xx` answered to a retry is never read as a payload+either — a redirect whose body happens to look like `/health` is reported as a redirect,+not as a healthy server.+### Optional peer identityNew connections use the OpenViking user's memory directory by default. Setupdiff --git a/examples/hermes-plugin/__init__.py b/examples/hermes-plugin/__init__.pyindex 33ab9da32..3407799a2 100644--- a/examples/hermes-plugin/__init__.py+++ b/examples/hermes-plugin/__init__.py@@ -267,6 +267,10 @@ def _status_code_from_error(error: Exception) -> Optional[int]:return getattr(getattr(error, "response", None), "status_code", None)+def _is_redirect(status: Optional[int]) -> bool:+ return isinstance(status, int) and 300 <= status < 400++def _format_openviking_exception(error: Exception) -> str:return _sanitize_openviking_error_message(str(error), _status_code_from_error(error))@@ -452,12 +456,103 @@ class _VikingClient:def _anonymous_json(self, path: str) -> dict:"""Probe server identity without disclosing credentials or tenant IDs."""- return self._parse_response(self._httpx.get(f"{self._endpoint}{path}", headers={"Accept": "application/json"}, timeout=3.0))+ resp = self._httpx.get(+ f"{self._endpoint}{path}",+ headers={"Accept": "application/json"},+ timeout=3.0,+ follow_redirects=False,+ )+ status = getattr(resp, "status_code", None)+ if isinstance(status, int) and 300 <= status < 400:+ # An authenticating gateway answered the anonymous probe with a redirect to+ # its own login page. Surface the status instead of parsing the HTML body+ # into an empty dict, so callers can retry with credentials.+ raise _OpenVikingHTTPError(f"HTTP {status}", status)+ return self._parse_response(resp)++ def _probe_retry_headers(self, *, gateway_only: bool) -> dict:+ """Headers a retry may carry, limited to what that response authorizes.++ ``gateway_only`` is the operator's ``extra_headers`` and nothing else: a gateway+ never asks for the OpenViking key, so a redirect retry must not carry it. The other+ set is the one every other request uses (the key, tenant-free).+ """+ if gateway_only:+ return dict(self._extra_headers)+ return self._headers(include_tenant=False)++ def _probe_retry_json(self, *, gateway_only: bool) -> dict:+ """One probe retry with either the gateway headers or the key."""+ resp = self._httpx.get(+ f"{self._endpoint}/health",+ headers=self._probe_retry_headers(gateway_only=gateway_only),+ timeout=3.0,+ follow_redirects=False,+ )+ return self._probe_json(resp, gateway_only=gateway_only)++ def _probe_json(self, resp, *, gateway_only: bool) -> dict:+ """Parse a probe response, never reading a 3xx as if it were a payload.++ ``_parse_response`` only raises at ``>= 400``, so a retry that lands on a redirect+ would otherwise come back as an empty dict (an HTML login page) or — when the+ redirect body happens to be JSON — as a healthy payload. Either way the probe would+ accept an answer nobody gave: the endpoint is still gating the request.+ """+ status = getattr(resp, "status_code", None)+ if _is_redirect(status):+ if gateway_only:+ sent = "extra_headers"+ detail = ("the gateway is still redirecting, so check that the configured "+ "gateway credentials are valid")+ else:+ sent = "the API key"+ detail = ("the endpoint is still redirecting, so check the API key and any "+ "gateway credentials")+ raise _OpenVikingHTTPError(f"HTTP {status} after retrying with {sent}: {detail}", status)+ return self._parse_response(resp)++ def _probe_gateway_retry(self) -> dict:+ """Retry the probe with the operator's gateway headers only.++ Bounded to one extra request, and the redirect destination is never followed. If the+ gateway lets the probe through and the server behind it then asks for credentials+ (401/403), that explicit challenge is answered by the ordinary key retry, so the key+ still stays out of the redirect attempt itself.+ """+ resp = self._httpx.get(+ f"{self._endpoint}/health",+ headers=self._probe_retry_headers(gateway_only=True),+ timeout=3.0,+ follow_redirects=False,+ )+ if getattr(resp, "status_code", None) in (401, 403) and self._api_key:+ return self._probe_retry_json(gateway_only=False)+ return self._probe_json(resp, gateway_only=True)def health_payload(self) -> dict:"""``GET /health``, anonymous first so credentials never reach an unknown host.- Hosted OpenViking requires auth on /health: when an API key is configured and the- anonymous call gets 401/403, retry once with the key (no tenant headers).+ Hosted OpenViking requires auth on /health: an explicit 401/403 challenge is retried+ once with the key (no tenant headers), exactly as it always was.++ A 3xx is a gateway answering. It is retried only when this connection carries gateway+ headers — the operator's declaration that an authenticating gateway (Cloudflare+ Access, oauth2-proxy, ...) fronts the endpoint — and that retry carries nothing but+ those headers: no key, no peer identity, and no API key is required for it, because+ none is sent. If the gateway then lets us through to a server that asks for+ credentials itself, that 401/403 is handled by the ordinary key retry. An ordinary+ redirect from an endpoint that has not been shown to be OpenViking is not+ authorization to resend secrets, so it stays a failure, and the login URL is never+ followed.++ A ``401``/``403`` is the endpoint asking for credentials, and which credential it+ wants is not knowable from the status alone: an OpenViking server wants the key, a+ gateway (oauth2-proxy, many WAFs) wants its own headers and answers 401/403 rather+ than redirecting. So the key is tried when one is configured, and the gateway headers+ are tried when they are — a gateway-only deployment has no key to try, and gating the+ gateway retry on a key it never sends is what kept such a deployment from starting at+ all. When both are configured the key is tried first, which is the pre-existing+ behaviour, and the gateway headers are not retried a second time.Prefer an anonymous probe so credentials are never sent to an unknown host during identity checks.See #78410.@@ -465,9 +560,18 @@ class _VikingClient:try:return self._anonymous_json("/health")except _OpenVikingHTTPError as exc:- if not self._api_key or _status_code_from_error(exc) not in {401, 403}:+ status = _status_code_from_error(exc)+ if _is_redirect(status):+ if not self._extra_headers:+ raise+ return self._probe_gateway_retry()+ if status not in (401, 403):raise- return self._parse_response(self._httpx.get(f"{self._endpoint}/health", headers=self._headers(include_tenant=False), timeout=3.0))+ if self._api_key:+ return self._probe_retry_json(gateway_only=False)+ if self._extra_headers:+ return self._probe_gateway_retry()+ raisedef openapi_payload(self) -> dict:return self._anonymous_json("/openapi.json")diff --git a/examples/hermes-plugin/tests/test_extra_headers.py b/examples/hermes-plugin/tests/test_extra_headers.pyindex de79c8597..f4f5633d9 100644--- a/examples/hermes-plugin/tests/test_extra_headers.py+++ b/examples/hermes-plugin/tests/test_extra_headers.py@@ -9,18 +9,56 @@ linked ``ovcli.conf``); these tests pin the same behaviour for this plugin.import jsonimport threading+from contextlib import suppressfrom http.server import BaseHTTPRequestHandler, HTTPServer-def _start_server(records, *, require_header=None):+def _start_server(records, *, require_header=None, redirect_to=None, plain_redirect_to=None,+ gateway_value=None, require_key=False, key_retry_redirect_to=None):+ """Local stand-in for an OpenViking server.++ ``redirect_to`` models an authenticating gateway that answers header-less requests+ by redirecting to its own login page (Cloudflare Access, oauth2-proxy, ...) instead+ of returning 401/403.++ ``plain_redirect_to`` models an endpoint that simply redirects every request and+ says nothing about being OpenViking — the ordinary 3xx that must never receive+ credentials.++ ``gateway_value`` makes ``require_header`` value-checked: a request that does not+ present exactly this value is answered like a header-less one, modelling a gateway+ token that expired or was rotated.++ ``require_key`` makes the server behind the gateway ask for credentials itself: a+ request that passes the gateway but carries no ``X-API-Key`` gets ``401``.++ ``key_retry_redirect_to`` makes the answer to that key-bearing request a redirect+ whose body is a perfectly healthy-looking payload, modelling a gateway that gates+ the retry too. Nothing may read it as an answer.+ """+class Handler(BaseHTTPRequestHandler):- def do_GET(self):- records.append(dict(self.headers))- if require_header and not self.headers.get(require_header):- status, payload = 403, {"error": "blocked at edge"}- else:- status, payload = 200, {"status": "ok", "healthy": True,- "version": "0.4.18", "auth_mode": "api_key"}+ def _redirect(self, target):+ body = b"<html><head><title>302 Found</title></head><body></body></html>"+ self.send_response(302)+ self.send_header("Location", target)+ self.send_header("Content-Type", "text/html; charset=UTF-8")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def _redirect_with_json(self, target):+ """A redirect that also carries a healthy payload: only the status is honest."""+ raw = json.dumps({"status": "ok", "healthy": True, "version": "0.4.18",+ "auth_mode": "api_key"}).encode()+ self.send_response(302)+ self.send_header("Location", target)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)++ def _json(self, status, payload):raw = json.dumps(payload).encode()self.send_response(status)self.send_header("Content-Type", "application/json")@@ -28,6 +66,32 @@ def _start_server(records, *, require_header=None):self.end_headers()self.wfile.write(raw)+ def do_GET(self):+ records.append(dict(self.headers))+ if plain_redirect_to:+ self._redirect(plain_redirect_to)+ return+ if require_header:+ presented = self.headers.get(require_header)+ authorised = bool(presented) and (+ gateway_value is None or presented == gateway_value+ )+ if not authorised:+ if redirect_to:+ self._redirect(redirect_to)+ return+ self._json(403, {"error": "blocked at edge"})+ return+ if require_key and not self.headers.get("X-API-Key"):+ self._json(401, {"error": {"code": "AuthenticationError",+ "message": "The API key in the request is missing or invalid."}})+ return+ if key_retry_redirect_to:+ self._redirect_with_json(key_retry_redirect_to)+ return+ self._json(200, {"status": "ok", "healthy": True,+ "version": "0.4.18", "auth_mode": "api_key"})+def log_message(self, *_args):pass@@ -144,7 +208,380 @@ def test_startup_health_probe_carries_extra_headers(external_provider):)assert provider._client is not None, "provider dropped the client after a refused probe"assert provider._client._extra_headers == {"CF-Access-Client-Id": "id.access"}+ # A 401/403 is the server itself asking for credentials: that retry keeps sending the+ # key, exactly as it did before gateway support existed.+ assert records[-1].get("X-API-Key") == "test-key", (+ "the retry after 403 stopped carrying the key"+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_startup_probe_retries_when_gateway_redirects_to_login(external_provider):+ """A redirect to a login page means "credentials wanted", not "not OpenViking".++ Cloudflare Access answers a header-less request with ``302`` and+ ``Location: https://<team>.cloudflareaccess.com/cdn-cgi/access/login/<host>``. The+ anonymous identity probe deliberately sends no credentials, so it cannot read that+ HTML page; without a retry the provider reports a reachable server as "not valid+ OpenViking" and drops the client, even though every authenticated request would work.+ """+ records = []+ server, worker = _start_server(+ records,+ require_header="CF-Access-Client-Id",+ redirect_to="https://team.cloudflareaccess.com/cdn-cgi/access/login/openviking.example.com",+ )+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ home, provider, _module, _settings = external_provider("extra-headers-redirect")+ (home / ".env").write_text(+ "OPENVIKING_ENDPOINT=%s\nOPENVIKING_API_KEY=test-key\nOPENVIKING_EXTRA_HEADERS=%s\n"+ % (endpoint, json.dumps({"CF-Access-Client-Id": "id.access"})),+ encoding="utf-8",+ )+ provider.initialize(session_id="gateway-redirect", hermes_home=str(home), platform="cli")+ assert provider._client is not None, (+ "provider dropped a reachable server because the anonymous probe was redirected"+ )+ assert records[-1].get("CF-Access-Client-Id") == "id.access", (+ "the retry after the redirect went out without the resolved headers"+ )+ leaked = [+ r for r in records[-1:]+ if r.get("X-API-Key") or r.get("Authorization") or r.get("X-OpenViking-Actor-Peer")+ ]+ assert not leaked, (+ "the retry after a redirect carried more than the gateway headers: %s"+ % json.dumps(leaked[-1])+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_ordinary_redirect_receives_no_secrets(external_provider):+ """An ordinary 3xx is not authorization to resend credentials.++ Without gateway headers configured there is nothing identifying the endpoint as+ OpenViking, so a redirect must not turn the probe into an authenticated request:+ the API key (``X-API-Key``, ``Authorization``) has to stay unsent, and the endpoint+ stays unusable exactly as it was before this change.+ """+ records = []+ server, worker = _start_server(records, plain_redirect_to="https://example.com/moved")+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ home, provider, _module, _settings = external_provider("plain-redirect")+ (home / ".env").write_text(+ "OPENVIKING_ENDPOINT=%s\nOPENVIKING_API_KEY=test-key\n" % endpoint,+ encoding="utf-8",+ )+ provider.initialize(session_id="plain-redirect", hermes_home=str(home), platform="cli")++ assert records, "startup should have probed /health"+ leaked = [+ r for r in records+ if r.get("X-API-Key") or r.get("Authorization") or r.get("X-OpenViking-Account")+ ]+ assert not leaked, (+ "an ordinary redirect was answered with credentials: %s" % json.dumps(leaked[-1])+ )+ assert len(records) == 1, (+ "the probe retried after an ordinary redirect instead of failing once: %d requests"+ % len(records)+ )+ assert provider._client is None, (+ "a redirecting non-OpenViking endpoint was accepted as a client"+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_gateway_only_deployment_needs_no_api_key(external_provider):+ """A gateway-only deployment: extra_headers set, no OpenViking API key at all.++ The gateway retry carries the operator's headers and nothing else, so it must not be+ gated on a key that request never sends. A loopback OpenViking published through+ Cloudflare Access has exactly this shape.+ """+ records = []+ server, worker = _start_server(+ records,+ require_header="CF-Access-Client-Id",+ redirect_to="https://team.cloudflareaccess.com/cdn-cgi/access/login/openviking.example.com",+ )+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ _, _, module, _ = external_provider("gateway-only-no-key")+ client = module._VikingClient(+ endpoint, "", extra_headers={"CF-Access-Client-Id": "id.access"}+ )+ payload = client.health_payload()++ assert payload.get("status") == "ok", (+ "a gateway-only deployment could not probe /health without an API key"+ )+ assert len(records) == 2, (+ "expected one anonymous probe and one gateway retry, got %d requests" % len(records)+ )+ assert records[1].get("CF-Access-Client-Id") == "id.access"+ assert not (records[1].get("X-API-Key") or records[1].get("Authorization")), (+ "the gateway retry carried credentials it never needed"+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_gateway_redirect_then_key_challenge_is_answered(external_provider):+ """A gateway in front of an API-key-protected /health still starts.++ anonymous -> 302 (gateway), gateway-only retry -> 401 (the server itself asks for+ credentials), key retry -> 200. Three requests at most, and the key stays out of the+ redirect attempt.+ """+ records = []+ server, worker = _start_server(+ records,+ require_header="CF-Access-Client-Id",+ redirect_to="https://team.cloudflareaccess.com/cdn-cgi/access/login/openviking.example.com",+ require_key=True,+ )+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ _, _, module, _ = external_provider("gateway-then-key")+ client = module._VikingClient(+ endpoint, "test-key", extra_headers={"CF-Access-Client-Id": "id.access"}+ )+ payload = client.health_payload()++ assert payload.get("status") == "ok", (+ "the 401 challenge behind the gateway was never answered"+ )+ assert len(records) == 3, (+ "expected probe + gateway retry + key retry, got %d requests" % len(records)+ )+ assert not (records[1].get("X-API-Key") or records[1].get("Authorization")), (+ "the redirect retry carried the key"+ )+ assert records[2].get("X-API-Key") == "test-key", (+ "the explicit 401 challenge went unanswered"+ )+ assert records[2].get("CF-Access-Client-Id") == "id.access"+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_stale_gateway_token_reports_the_gateway_not_openviking(external_provider):+ """An expired gateway token must say so, not "not valid OpenViking".++ The retry stays bounded and the login URL is never followed.+ """+ records = []+ server, worker = _start_server(+ records,+ require_header="CF-Access-Client-Id",+ redirect_to="https://team.cloudflareaccess.com/cdn-cgi/access/login/openviking.example.com",+ gateway_value="rotated-token",+ )+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ _, _, module, _ = external_provider("stale-gateway-token")+ client = module._VikingClient(+ endpoint, "test-key", extra_headers={"CF-Access-Client-Id": "stale-token"}+ )+ message = ""+ try:+ client.health_payload()+ except Exception as exc: # noqa: BLE001 — the message is the point here+ message = str(exc)++ assert "still redirecting" in message or "extra_headers" in message, (+ "a repeated gateway redirect was reported as %r" % message+ )+ assert len(records) == 2, "the retry was not bounded: %d requests" % len(records)+ assert not (records[1].get("X-API-Key") or records[1].get("Authorization")), (+ "the bounded retry carried credentials"+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_gateway_only_deployment_needs_no_api_key_when_gateway_answers_403(external_provider):+ """A gateway-only deployment whose gateway answers ``403`` instead of redirecting.++ Cloudflare Access redirects, but oauth2-proxy and many WAFs answer ``401``/``403``+ to a request that carries no service token. The retry that would satisfy them sends+ the operator's headers and no OpenViking key, so it must not be gated on a key this+ deployment does not have. ``require_header`` with no ``redirect_to`` is exactly that+ shape: the header-less probe is refused, the header-bearing retry is accepted.+ """+ records = []+ server, worker = _start_server(records, require_header="CF-Access-Client-Id")+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ _, _, module, _ = external_provider("gateway-only-403")+ client = module._VikingClient(+ endpoint, "", extra_headers={"CF-Access-Client-Id": "id.access"}+ )+ payload = client.health_payload()++ assert payload.get("status") == "ok", (+ "a gateway-only deployment could not probe a gateway that answers 403"+ )+ assert len(records) == 2, (+ "expected one anonymous probe and one gateway retry, got %d requests" % len(records)+ )+ assert records[1].get("CF-Access-Client-Id") == "id.access"+ assert not (records[1].get("X-API-Key") or records[1].get("Authorization")), (+ "the gateway retry carried credentials it never needed"+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_gateway_only_deployment_starts_when_gateway_answers_403(external_provider):+ """The same shape through provider.initialize(): the client must survive startup."""+ records = []+ server, worker = _start_server(records, require_header="CF-Access-Client-Id")+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ home, provider, _module, _settings = external_provider("gateway-only-403-startup")+ (home / ".env").write_text(+ "OPENVIKING_ENDPOINT=%s\nOPENVIKING_EXTRA_HEADERS=%s\n"+ % (endpoint, json.dumps({"CF-Access-Client-Id": "id.access"})),+ encoding="utf-8",+ )+ provider.initialize(session_id="gateway-only-403", hermes_home=str(home), platform="cli")++ assert provider._client is not None, (+ "provider dropped a reachable, gateway-protected server: the 403 challenge was "+ "never retried with the gateway headers (%d request(s))" % len(records)+ )+ assert any(r.get("CF-Access-Client-Id") == "id.access" for r in records), (+ "no request ever carried the gateway headers"+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_key_retry_that_lands_on_a_redirect_is_not_read_as_a_payload(external_provider):+ """A redirect answered to the key retry must not become a "healthy" payload.++ ``_parse_response`` raises only at ``>= 400``, so a 3xx carrying a healthy-looking+ JSON body would otherwise be returned as the probe result and the endpoint accepted+ — even though the gateway is still gating the request.+ """+ records = []+ server, worker = _start_server(+ records,+ require_key=True,+ key_retry_redirect_to="https://team.cloudflareaccess.com/cdn-cgi/access/login/openviking.example.com",+ )+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ _, _, module, _ = external_provider("key-retry-redirect")+ client = module._VikingClient(endpoint, "test-key")+ message = ""+ payload = None+ try:+ payload = client.health_payload()+ except Exception as exc: # noqa: BLE001 — the message is the point here+ message = str(exc)++ assert not (isinstance(payload, dict) and payload.get("status") == "ok"), (+ "a redirect answered to the key retry was accepted as a healthy payload: %r" % (payload,)+ )+ assert "302" in message and "redirecting" in message, (+ "a redirect answered to the key retry was reported as %r" % message+ )+ assert len(records) == 2, "the retry was not bounded: %d requests" % len(records)+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+++def test_redirect_destination_is_never_requested(external_provider):+ """The login URL must not be fetched — proven by a second listener as the target.++ A single listener cannot tell a followed redirect from an unfollowed one: if the+ ``Location`` names another host, nothing in the test process would observe the+ request. So the target is a second stub on loopback, and it must stay empty.+ """+ target_records = []+ target, target_worker = _start_server(target_records)+ destination = "http://127.0.0.1:%d/cdn-cgi/access/login" % target.server_port+ records = []+ server, worker = _start_server(records, plain_redirect_to=destination)+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ _, _, module, _ = external_provider("redirect-destination")+ client = module._VikingClient(endpoint, "test-key")+ with suppress(Exception):+ client.health_payload()++ assert not target_records, (+ "the redirect destination was requested %d time(s): %s"+ % (len(target_records), json.dumps(target_records))+ )+ assert len(records) == 1, (+ "the probe did not fail once on an ordinary redirect: %d requests" % len(records)+ )+ finally:+ server.shutdown()+ server.server_close()+ worker.join(timeout=5)+ target.shutdown()+ target.server_close()+ target_worker.join(timeout=5)+++def test_gateway_redirect_destination_is_never_requested(external_provider):+ """Same for the gateway path: the retry must not follow the login URL either."""+ target_records = []+ target, target_worker = _start_server(target_records)+ destination = "http://127.0.0.1:%d/cdn-cgi/access/login" % target.server_port+ records = []+ server, worker = _start_server(+ records,+ require_header="CF-Access-Client-Id",+ redirect_to=destination,+ gateway_value="rotated-token",+ )+ endpoint = "http://127.0.0.1:%d" % server.server_port+ try:+ _, _, module, _ = external_provider("gateway-redirect-destination")+ client = module._VikingClient(+ endpoint, "test-key", extra_headers={"CF-Access-Client-Id": "stale-token"}+ )+ with suppress(Exception):+ client.health_payload()++ assert not target_records, (+ "the gateway retry followed the login URL (%d request(s) at the destination)"+ % len(target_records)+ )+ assert len(records) == 2, "the retry was not bounded: %d requests" % len(records)finally:server.shutdown()server.server_close()worker.join(timeout=5)+ target.shutdown()+ target.server_close()+ target_worker.join(timeout=5)