Skip to content

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.

fix(proxy): route /v1/models to the x-headroom-base-url upstream (#4308)

Younes Beriane6ef52c204768
diff --git a/headroom/providers/proxy_routes.py b/headroom/providers/proxy_routes.py
index 643aee69b..cba7eccfd 100644
--- a/headroom/providers/proxy_routes.py
+++ b/headroom/providers/proxy_routes.py
@@ -498,8 +498,19 @@ def register_provider_routes(app: FastAPI, proxy: Any) -> None:
VERTEX_STREAM_RAW_PREDICT.name,
)
- @app.get("/v1/models")
- async def list_models(request: Request):
+ async def _model_metadata_route(request: Request) -> tuple[str, str]:
+ # A caller-named upstream wins, as in the catch-all and the chat
+ # handlers: model discovery must reach the same gateway as inference.
+ custom_base = request.headers.get("x-headroom-base-url", "").strip()
+ if custom_base:
+ if not await is_safe_upstream_url_async(custom_base):
+ logger.warning("rejecting unsafe x-headroom-base-url: %r", custom_base)
+ raise HTTPException(status_code=400, detail="Rejected unsafe upstream base URL")
+ # Only the destination is overridden: keep the provider the request's
+ # auth selects, so Anthropic-auth requests still get model-id
+ # sanitization in handle_passthrough.
+ provider_name = proxy.provider_runtime.model_metadata_provider(dict(request.headers))
+ return provider_name, custom_base.rstrip("/")
headers = dict(request.headers)
provider_name = proxy.provider_runtime.model_metadata_provider(headers)
base_url = (
@@ -507,6 +518,11 @@ def register_provider_routes(app: FastAPI, proxy: Any) -> None:
if provider_name == "openai"
else _api_target(proxy, provider_name)
)
+ return provider_name, base_url
+
+ @app.get("/v1/models")
+ async def list_models(request: Request):
+ provider_name, base_url = await _model_metadata_route(request)
return await handle_model_metadata_endpoint(
proxy,
request,
@@ -517,13 +533,7 @@ def register_provider_routes(app: FastAPI, proxy: Any) -> None:
@app.get("/v1/models/{model_id}")
async def get_model(request: Request, model_id: str):
- headers = dict(request.headers)
- provider_name = proxy.provider_runtime.model_metadata_provider(headers)
- base_url = (
- _openai_compatible_base_url(proxy, headers)
- if provider_name == "openai"
- else _api_target(proxy, provider_name)
- )
+ provider_name, base_url = await _model_metadata_route(request)
return await handle_model_metadata_endpoint(
proxy,
request,
diff --git a/tests/test_proxy/test_model_metadata_passthrough_sanitization.py b/tests/test_proxy/test_model_metadata_passthrough_sanitization.py
new file mode 100644
index 000000000..ce80a6e19
--- /dev/null
+++ b/tests/test_proxy/test_model_metadata_passthrough_sanitization.py
@@ -0,0 +1,63 @@
+"""``GET /v1/models/{id}`` with ``x-headroom-base-url`` keeps the selected provider.
+
+The header only overrides the destination. An Anthropic-authenticated request
+(``x-api-key``) must still go through ``handle_passthrough``'s Anthropic
+model-id sanitization, so Claude Code's ``[1m]`` context-tier suffix never
+reaches the named gateway (#4302). These tests run the real
+``handle_passthrough`` and fake only the upstream HTTP transport, asserting the
+outbound URL.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip("fastapi")
+
+import httpx # noqa: E402
+from fastapi.testclient import TestClient # noqa: E402
+
+from headroom.proxy.server import ProxyConfig, create_app # noqa: E402
+
+GATEWAY = "https://gateway.example"
+
+
+def real_passthrough(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setenv("HEADROOM_REQUIRE_RUST_CORE", "false")
+ monkeypatch.setenv("HEADROOM_ALLOWED_BASE_URLS", "gateway.example")
+ outbound: list[httpx.Request] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ outbound.append(request)
+ return httpx.Response(200, json={"data": []})
+
+ config = ProxyConfig(
+ optimize=False,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ )
+ with TestClient(create_app(config)) as c:
+ c.app.state.proxy.http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+ yield c, outbound
+
+
+def test_anthropic_auth_with_header_upstream_sanitizes_model_id(real_passthrough) -> None:
+ client, outbound = real_passthrough
+ resp = client.get(
+ "/v1/models/claude-opus-4-8%5B1m%5D",
+ headers={"x-api-key": "sk-ant-test", "x-headroom-base-url": GATEWAY},
+ )
+ assert resp.status_code == 200
+ assert [str(r.url) for r in outbound] == [f"{GATEWAY}/v1/models/claude-opus-4-8"]
+
+
+def test_bearer_auth_with_header_upstream_leaves_model_id_untouched(real_passthrough) -> None:
+ client, outbound = real_passthrough
+ resp = client.get(
+ "/v1/models/some-model%5B1m%5D",
+ headers={"authorization": "Bearer k", "x-headroom-base-url": GATEWAY},
+ )
+ assert resp.status_code == 200
+ assert [str(r.url) for r in outbound] == [f"{GATEWAY}/v1/models/some-model[1m]"]
diff --git a/tests/test_proxy/test_model_metadata_upstream_header.py b/tests/test_proxy/test_model_metadata_upstream_header.py
new file mode 100644
index 000000000..06da834f6
--- /dev/null
+++ b/tests/test_proxy/test_model_metadata_upstream_header.py
@@ -0,0 +1,89 @@
+"""``GET /v1/models`` and ``/v1/models/{id}`` must honor ``x-headroom-base-url``.
+
+The catch-all passthrough and the chat handlers already route to the
+caller-named upstream; model discovery used to ignore the header and hit the
+default OpenAI upstream (#4302). An unsafe named upstream is rejected with 400
+exactly like the catch-all.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip("fastapi")
+
+from fastapi import Response # noqa: E402
+from fastapi.testclient import TestClient # noqa: E402
+
+from headroom.proxy.server import HeadroomProxy, ProxyConfig, create_app # noqa: E402
+
+GATEWAY = "https://gateway.example"
+
+
+_CALLS: list[tuple[str, str, str]] = []
+
+
[email protected](scope="module")
+def client():
+ # One app for the module: proxy shutdown dominates the runtime otherwise.
+ mp = pytest.MonkeyPatch()
+ mp.setenv("HEADROOM_REQUIRE_RUST_CORE", "false")
+
+ async def fake_passthrough(self, request, base_url, sub_path=None, *args, **kwargs):
+ _CALLS.append((base_url, sub_path, request.url.path))
+ return Response(content=b'{"data": []}', media_type="application/json")
+
+ mp.setattr(HeadroomProxy, "handle_passthrough", fake_passthrough)
+ config = ProxyConfig(
+ optimize=False,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ )
+ try:
+ with TestClient(create_app(config)) as c:
+ yield c
+ finally:
+ mp.undo()
+
+
+def captured(client, monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str, str]]:
+ monkeypatch.setenv("HEADROOM_ALLOWED_BASE_URLS", "gateway.example")
+ _CALLS.clear()
+ return _CALLS
+
+
+def test_list_models_routes_to_header_upstream(client, captured) -> None:
+ resp = client.get(
+ "/v1/models",
+ headers={"authorization": "Bearer k", "x-headroom-base-url": GATEWAY + "/"},
+ )
+ assert resp.status_code == 200
+ assert [c[0] for c in captured] == [GATEWAY]
+
+
+def test_get_model_routes_to_header_upstream(client, captured) -> None:
+ resp = client.get(
+ "/v1/models/some-model",
+ headers={"authorization": "Bearer k", "x-headroom-base-url": GATEWAY},
+ )
+ assert resp.status_code == 200
+ assert [c[0] for c in captured] == [GATEWAY]
+
+
+def test_no_header_keeps_default_upstream(client, captured) -> None:
+ resp = client.get("/v1/models", headers={"authorization": "Bearer k"})
+ assert resp.status_code == 200
+ assert captured and captured[0][0] != GATEWAY
+
+
[email protected]("path", ["/v1/models", "/v1/models/some-model"])
+def test_unsafe_header_upstream_rejected(client, captured, monkeypatch, path) -> None:
+ monkeypatch.delenv("HEADROOM_ALLOWED_BASE_URLS", raising=False)
+ resp = client.get(
+ path,
+ headers={"authorization": "Bearer k", "x-headroom-base-url": "http://127.0.0.1:9"},
+ )
+ assert resp.status_code == 400
+ assert captured == []