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(backends/litellm): match the caller-key Bearer scheme case-insensitively (RFC 7235) (#3965)
Rajat Nagda848d7a04b489
diff --git a/headroom/backends/litellm.py b/headroom/backends/litellm.pyindex a5a5012cf..c2c5ea858 100644--- a/headroom/backends/litellm.py+++ b/headroom/backends/litellm.py@@ -544,6 +544,25 @@ def _caller_key_travels_to(model: str, key: str) -> bool:return provider not in _REJECTS_ANTHROPIC_KEY+def _caller_key_from_headers(headers: dict[str, str]) -> str:+ """Extract the caller's API key from inbound request headers.++ The ``Authorization`` auth-scheme token is case-insensitive per RFC 7235+ §2.1, so ``Authorization: bearer <key>`` must be read the same as+ ``Bearer <key>``. A case-sensitive ``startswith("Bearer ")`` dropped the+ credential for a lowercase (or otherwise differently-cased) scheme, and the+ request then fell back to the target provider's env key — which may not+ exist, yielding a spurious upstream 401. Only the scheme is case-folded; the+ credential itself is returned verbatim. Falls back to ``x-api-key`` when the+ header carries no bearer credential (matching the prior behavior).+ """+ auth_header = headers.get("authorization", headers.get("Authorization", ""))+ scheme, sep, credentials = auth_header.partition(" ")+ if sep and scheme.lower() == "bearer":+ return credentials+ return headers.get("x-api-key", "")++def get_provider_config(provider: str) -> ProviderConfig:"""Get provider config, with fallback for unknown providers."""if provider in PROVIDER_REGISTRY:@@ -1290,12 +1309,7 @@ class LiteLLMBackend(Backend):# Forwarding x-api-key (e.g. sk-ant-dummy) would override their credentials._env_auth_providers = ("bedrock", "vertex_ai", "vertex_ai_beta", "sagemaker")if self.provider not in _env_auth_providers:- auth_header = headers.get("authorization", headers.get("Authorization", ""))- _caller_key = (- auth_header[7:]- if auth_header.startswith("Bearer ")- else headers.get("x-api-key", "")- )+ _caller_key = _caller_key_from_headers(headers)# Only forward it if it can actually authenticate the TARGET.if _caller_key and _caller_key_travels_to(litellm_model, _caller_key):kwargs["api_key"] = _caller_key@@ -1416,12 +1430,7 @@ class LiteLLMBackend(Backend):# Forwarding x-api-key (e.g. sk-ant-dummy) would override their credentials._env_auth_providers = ("bedrock", "vertex_ai", "vertex_ai_beta", "sagemaker")if self.provider not in _env_auth_providers:- auth_header = headers.get("authorization", headers.get("Authorization", ""))- _caller_key = (- auth_header[7:]- if auth_header.startswith("Bearer ")- else headers.get("x-api-key", "")- )+ _caller_key = _caller_key_from_headers(headers)# Only forward it if it can actually authenticate the TARGET.if _caller_key and _caller_key_travels_to(litellm_model, _caller_key):kwargs["api_key"] = _caller_key@@ -1824,12 +1833,7 @@ class LiteLLMBackend(Backend):# Forwarding x-api-key (e.g. sk-ant-dummy) would override their credentials._env_auth_providers = ("bedrock", "vertex_ai", "vertex_ai_beta", "sagemaker")if self.provider not in _env_auth_providers:- auth_header = headers.get("authorization", headers.get("Authorization", ""))- _caller_key = (- auth_header[7:]- if auth_header.startswith("Bearer ")- else headers.get("x-api-key", "")- )+ _caller_key = _caller_key_from_headers(headers)# Only forward it if it can actually authenticate the TARGET.if _caller_key and _caller_key_travels_to(litellm_model, _caller_key):kwargs["api_key"] = _caller_key@@ -2039,12 +2043,7 @@ class LiteLLMBackend(Backend):# Forwarding x-api-key (e.g. sk-ant-dummy) would override their credentials._env_auth_providers = ("bedrock", "vertex_ai", "vertex_ai_beta", "sagemaker")if self.provider not in _env_auth_providers:- auth_header = headers.get("authorization", headers.get("Authorization", ""))- _caller_key = (- auth_header[7:]- if auth_header.startswith("Bearer ")- else headers.get("x-api-key", "")- )+ _caller_key = _caller_key_from_headers(headers)# Only forward it if it can actually authenticate the TARGET.if _caller_key and _caller_key_travels_to(litellm_model, _caller_key):kwargs["api_key"] = _caller_keydiff --git a/tests/test_litellm_caller_key.py b/tests/test_litellm_caller_key.pyindex d9dd2440c..cc4e4e126 100644--- a/tests/test_litellm_caller_key.py+++ b/tests/test_litellm_caller_key.py@@ -15,7 +15,7 @@ from __future__ import annotationsimport pytest-from headroom.backends.litellm import _caller_key_travels_to+from headroom.backends.litellm import _caller_key_from_headers, _caller_key_travels_toANTHROPIC_KEY = "sk-ant-api03-abc123"@@ -65,3 +65,36 @@ def test_unknown_provider_keeps_the_pass_through() -> None:key -- including when `get_llm_provider` raises on the model string."""assert _caller_key_travels_to("some-self-hosted-thing", ANTHROPIC_KEY) is Trueassert _caller_key_travels_to("", ANTHROPIC_KEY) is True+++# ---------------------------------------------------------------------------+# _caller_key_from_headers — the Authorization scheme is case-insensitive+# (RFC 7235 §2.1), so `bearer <key>` must be read the same as `Bearer <key>`.+# ---------------------------------------------------------------------------+++ "scheme",+ ["Bearer", "bearer", "BEARER", "BeArEr"],+)+def test_bearer_scheme_is_matched_case_insensitively(scheme: str) -> None:+ """A differently-cased Bearer scheme must still yield the caller key."""+ headers = {"authorization": f"{scheme} {ANTHROPIC_KEY}"}+ assert _caller_key_from_headers(headers) == ANTHROPIC_KEY+++def test_uppercase_authorization_header_name_is_accepted() -> None:+ headers = {"Authorization": f"bearer {ANTHROPIC_KEY}"}+ assert _caller_key_from_headers(headers) == ANTHROPIC_KEY+++def test_falls_back_to_x_api_key_without_a_bearer_credential() -> None:+ assert _caller_key_from_headers({"x-api-key": ANTHROPIC_KEY}) == ANTHROPIC_KEY+ # A bare scheme with no credential is not a bearer credential.+ assert _caller_key_from_headers({"authorization": "Bearer"}) == ""+++def test_credential_itself_is_returned_verbatim() -> None:+ """Only the scheme is case-folded; the credential keeps its exact case."""+ mixed = "sk-AbC-123-XyZ"+ assert _caller_key_from_headers({"authorization": f"bearer {mixed}"}) == mixeddiff --git a/tests/test_litellm_openai_passthrough.py b/tests/test_litellm_openai_passthrough.pyindex 430497656..10bd9bf87 100644--- a/tests/test_litellm_openai_passthrough.py+++ b/tests/test_litellm_openai_passthrough.py@@ -259,3 +259,24 @@ async def test_reasoning_params_forwarded_top_level_streaming() -> None:kwargs = mock_acomp.await_args.kwargsassert kwargs["reasoning_effort"] == "high"assert "reasoning_effort" not in kwargs.get("extra_body", {})+++async def test_lowercase_bearer_caller_key_is_forwarded() -> None:+ """A lowercase `authorization: bearer <key>` must still forward the key.++ RFC 7235 §2.1 makes the auth-scheme token case-insensitive. A case-sensitive+ `startswith("Bearer ")` dropped the caller credential for a lowercase scheme,+ so litellm fell back to a (possibly absent) env key and the upstream 401'd.+ """+ backend = make_backend() # provider=openrouter, not env-auth++ with patch("headroom.backends.litellm.acompletion", new_callable=AsyncMock) as mock_acomp:+ mock_acomp.return_value = make_response()++ await backend.send_openai_message(+ request_body(),+ {"authorization": "bearer sk-caller-123"},+ )++ assert mock_acomp.await_args.kwargs.get("api_key") == "sk-caller-123"