Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(wrap): reject saved bob gateway URLs the proxy would not route (#3975)
trs-80944eafc6d4bc
diff --git a/headroom/providers/wrap_registry.py b/headroom/providers/wrap_registry.pyindex 826fa404d..89542d3ad 100644--- a/headroom/providers/wrap_registry.py+++ b/headroom/providers/wrap_registry.py@@ -20,11 +20,11 @@ from collections.abc import Callable, Mappingfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Literal-from urllib.parse import urlsplit+from urllib.parse import unquote, urlsplitfrom headroom.providers.claude import proxy_base_url as claude_proxy_base_urlfrom headroom.providers.codex import proxy_base_url as codex_proxy_base_url-from headroom.proxy.project_context import with_project_prefix+from headroom.proxy.project_context import split_project_path, with_project_prefix# How an EnvVar's URL is shaped: ``openai_v1`` ends in ``/v1`` (OpenAI-style# clients append ``/chat/completions``); ``anthropic`` is a bare origin@@ -114,10 +114,39 @@ def build_launch_env(return env, display-def _origin_key(url: str) -> tuple[str, str, int | None]:- parts = urlsplit(url.strip())- host = (parts.hostname or "").lower()- return parts.scheme, "127.0.0.1" if host == "localhost" else host, parts.port+def _origin(url: str) -> tuple[str, str, int | None] | None:+ """(scheme, host, port) of ``url``; None when it cannot be an HTTP origin.++ None for an unparsable URL (a non-numeric port makes ``urlsplit(...).port``+ raise) or a missing scheme or host.+ """+ try:+ parts = urlsplit(url)+ port = parts.port+ except ValueError:+ return None+ if not parts.scheme or not parts.hostname:+ return None+ host = parts.hostname # urlsplit lowercases it+ return parts.scheme, "127.0.0.1" if host == "localhost" else host, port+++def _routable_proxy_path(url: str) -> bool:+ """True when Bob's gateway paths appended to ``url`` reach the proxy router.++ Only a bare origin or one ``/p/<project>`` prefix qualifies; anything else+ leaves Bob's paths under a prefix the router never sees. A ``?`` or ``#``+ anywhere fails, even bare: Bob appends to the string, so the paths would+ land in the query or fragment. The path is checked decoded, as the ASGI+ server hands it to the router, so an encoded slash in the project segment+ is the extra segment it becomes, while the ``%20`` that+ ``with_project_prefix`` itself emits is fine. A trailing slash is fine too:+ bobshell's ``AJ()`` (verified in 2.0.5) collapses repeated slashes and+ strips a trailing one before appending.+ """+ if "?" in url or "#" in url:+ return False+ return split_project_path(unquote(urlsplit(url).path))[1] in ("", "/")def bob_preflight(env: Mapping[str, str], settings_path: Path | None = None) -> str | None:@@ -136,16 +165,27 @@ def bob_preflight(env: Mapping[str, str], settings_path: Path | None = None) ->return Noneif not isinstance(saved, str) or not saved.strip():return None- # Same proxy if scheme, host and port agree; a different /p/<project>- # prefix only changes attribution, and the error below tells users to- # point gatewayUrl at the proxy, so that must not then be rejected.- if _origin_key(saved) == _origin_key(env.get("BOB_GATEWAY_URL", "")):- return None+ saved = saved.strip()+ saved_origin = _origin(saved)+ proxy_origin = _origin(env.get("BOB_GATEWAY_URL", ""))+ if saved_origin is None:+ reason = "could not be parsed as an HTTP origin"+ elif proxy_origin is not None and saved_origin == proxy_origin:+ # Same proxy. A different /p/<project> prefix only changes attribution,+ # and the message below tells users to point gatewayUrl at the proxy,+ # so that must not then be rejected; an extra path segment must be.+ if _routable_proxy_path(saved):+ return None+ reason = (+ "is not a URL the proxy can route (use the bare proxy origin, optionally "+ "with one /p/<project> prefix, and no query or fragment)"+ )+ else:+ reason = "overrides BOB_GATEWAY_URL, so Bob would bypass the Headroom proxy"return (- f"Bob's saved gatewayUrl ({saved.strip()}) overrides BOB_GATEWAY_URL, so Bob "- f"would bypass the Headroom proxy. Remove the gatewayUrl entry from {path} "- "(or set it to the proxy URL shown by this wrap) and retry. If your "- "organisation enforces a GatewayUrl policy, Bob cannot be wrapped."+ f"Bob's saved gatewayUrl ({saved}) {reason}. Remove the gatewayUrl "+ f"entry from {path} (or set it to the proxy URL shown by this wrap) and retry. "+ "If your organisation enforces a GatewayUrl policy, Bob cannot be wrapped.")diff --git a/tests/test_cli/test_wrap_bob.py b/tests/test_cli/test_wrap_bob.pyindex 0500047d0..e22b94441 100644--- a/tests/test_cli/test_wrap_bob.py+++ b/tests/test_cli/test_wrap_bob.py@@ -162,6 +162,8 @@ class TestBobPreflight:{"gatewayUrl": "http://127.0.0.1:8787/p/myproj/"}, # already the proxy{"gatewayUrl": "http://127.0.0.1:8787/p/another-project"}, # attribution only{"gatewayUrl": "http://localhost:8787"}, # same proxy, spelled differently+ {"gatewayUrl": "HTTP://LOCALHOST:8787/"}, # case and trailing slash+ {"gatewayUrl": "http://127.0.0.1:8787/p/my%20proj"}, # as with_project_prefix prints it"not json",],)@@ -171,9 +173,37 @@ class TestBobPreflight:def test_passes_when_no_settings_file(self, tmp_path):assert bob_preflight(self.ENV, tmp_path / "missing.json") is None- def test_fails_on_same_host_other_port(self, tmp_path):- path = self._settings(tmp_path, {"gatewayUrl": "http://127.0.0.1:9999"})- assert bob_preflight(self.ENV, path) is not None+ BYPASS = "would bypass the Headroom proxy"+ UNROUTABLE = "not a URL the proxy can route"+ UNPARSABLE = "could not be parsed"++ @pytest.mark.parametrize(+ ("gateway_url", "reason"),+ [+ ("http://127.0.0.1:9999", BYPASS), # same host, other port+ ("https://api.eu-de.bob.ibm.com/inference", BYPASS), # foreign host with a path+ ("https://api.eu-de.bob.ibm.com/?r=1", BYPASS),+ ("http://127.0.0.1:8787/p/myproj/v1", UNROUTABLE), # extra segment+ ("http://127.0.0.1:8787/inference", UNROUTABLE), # path without the /p/ prefix+ ("http://127.0.0.1:8787/p/team%2Fwork", UNROUTABLE), # ASGI decodes into 2 segments+ ("http://127.0.0.1:8787/p/myproj?team=a", UNROUTABLE), # Bob appends after the query+ ("http://127.0.0.1:8787#frag", UNROUTABLE),+ ("http://127.0.0.1:8787/p/myproj?", UNROUTABLE), # bare delimiters parse as empty+ ("http://127.0.0.1:8787#", UNROUTABLE),+ ("http://127.0.0.1:not-a-port", UNPARSABLE), # urlsplit(...).port raises+ ("/", UNPARSABLE), # no scheme or host+ ],+ )+ def test_fails_on_non_proxy_shapes(self, tmp_path, gateway_url, reason):+ path = self._settings(tmp_path, {"gatewayUrl": gateway_url})+ message = bob_preflight(self.ENV, path)+ assert message is not None and str(path) in message and reason in message++ def test_unparsable_env_url_never_matches(self, tmp_path):+ # Two None identities must not compare equal.+ path = self._settings(tmp_path, {"gatewayUrl": "/"})+ assert bob_preflight({"BOB_GATEWAY_URL": "http://127.0.0.1:bad"}, path) is not None+ assert bob_preflight({}, path) is not Nonedef test_fails_on_foreign_gateway(self, tmp_path):path = self._settings(tmp_path, {"gatewayUrl": "https://api.eu-de.bob.ibm.com"})