The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(auth): gate oauth2-proxy header trust on premium + privileged-field denylist
user3c9a8690d1e6
diff --git a/litellm/proxy/auth/oauth2_proxy_hook.py b/litellm/proxy/auth/oauth2_proxy_hook.pyindex 0dc696bc455..341d2b477b0 100644--- a/litellm/proxy/auth/oauth2_proxy_hook.py+++ b/litellm/proxy/auth/oauth2_proxy_hook.py@@ -1,19 +1,78 @@-from typing import Any, Dict+from typing import Any, Dict, FrozenSetfrom fastapi import Requestfrom litellm._logging import verbose_proxy_logger-from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy._types import CommonProxyErrors, UserAPIKeyAuth++# Fields on ``UserAPIKeyAuth`` that grant privileges directly (``user_role``+# is the canonical privesc — coerced from the string ``"proxy_admin"`` into+# ``LitellmUserRoles.PROXY_ADMIN`` by Pydantic) or break trust assumptions+# (``api_key`` / ``token`` short-circuit the validated-key contract;+# ``permissions`` / ``allowed_routes`` directly grant route access; budget+# and limit fields can be set to wild values to bypass enforcement;+# ``metadata`` is too broad to safely admit from caller-controlled headers).+#+# Operators who legitimately need any of these to flow from a trusted+# upstream proxy should switch to JWT authentication, which validates a+# signature on the assertion rather than blindly trusting headers.+PRIVILEGED_OAUTH2_PROXY_FIELDS: FrozenSet[str] = frozenset(+ {+ "user_role",+ "api_key",+ "token",+ "key_alias",+ "key_name",+ "permissions",+ "allowed_routes",+ "max_budget",+ "spend",+ "model_max_budget",+ "model_spend",+ "tpm_limit",+ "rpm_limit",+ "team_max_budget",+ "team_spend",+ "blocked",+ "metadata",+ }+)async def handle_oauth2_proxy_request(request: Request) -> UserAPIKeyAuth:"""- Handle request from oauth2 proxy.+ Resolve a ``UserAPIKeyAuth`` from request headers per the admin-set+ ``oauth2_config_mappings``.++ The auth model assumes the proxy is deployed behind a trusted OAuth2+ reverse proxy that injects authenticated identity headers (e.g.+ oauth2-proxy, Authelia). Two safeguards above and beyond that+ deployment assumption:++ 1. **Premium gate.** The sibling auth paths (``enable_oauth2_auth``+ and ``enable_jwt_auth``) require ``premium_user``; this path+ previously did not, which let any open-source deployment turn+ the feature on without realising it requires a hardened+ deployment topology.+ 2. **Privileged-field denylist.** ``oauth2_config_mappings`` maps+ header names to ``UserAPIKeyAuth`` fields. Without a denylist,+ an admin who maps the wrong header to ``user_role`` (or who+ hasn't fully locked down their reverse proxy) lets any caller+ set the ``user_role`` header to ``"proxy_admin"`` and gain full+ admin privileges — Pydantic coerces the string into the enum.+ Mapping any privileged field is rejected at startup-style auth+ time so the misconfiguration surfaces loudly rather than as a+ silent privesc."""- from litellm.proxy.proxy_server import general_settings+ from litellm.proxy.proxy_server import general_settings, premium_user++ if premium_user is not True:+ raise ValueError(+ "Oauth2 proxy auth is an enterprise-only feature. "+ + CommonProxyErrors.not_premium_user.value+ )verbose_proxy_logger.debug("Handling oauth2 proxy request")- # Define the OAuth2 config mappingsoauth2_config_mappings: Dict[str, str] = (general_settings.get("oauth2_config_mappings") or {})@@ -21,21 +80,33 @@ async def handle_oauth2_proxy_request(request: Request) -> UserAPIKeyAuth:if not oauth2_config_mappings:raise ValueError("Oauth2 config mappings not found in general_settings")- # Initialize a dictionary to store the mapped values- auth_data: Dict[str, Any] = {}- # Extract values from headers based on the mappings+ privileged_mapped = sorted(+ set(oauth2_config_mappings.keys()) & PRIVILEGED_OAUTH2_PROXY_FIELDS+ )+ if privileged_mapped:+ raise ValueError(+ "Oauth2 proxy auth refuses to map privileged UserAPIKeyAuth "+ f"fields from request headers: {privileged_mapped}. These "+ "fields would grant privileges (e.g. proxy_admin), bypass "+ "budget enforcement, or short-circuit key validation if a "+ "caller can spoof the corresponding header. If you need a "+ "trusted upstream to assert one of these, use JWT auth "+ "(signature-validated) instead of header-trust."+ )++ auth_data: Dict[str, Any] = {}for key, header in oauth2_config_mappings.items():value = request.headers.get(header)- if value:- # Convert max_budget to float if present- if key == "max_budget":- auth_data[key] = float(value)- # Convert models to list if present- elif key == "models":- auth_data[key] = [model.strip() for model in value.split(",")]- else:- auth_data[key] = value+ if not value:+ continue+ if key == "max_budget":+ auth_data[key] = float(value)+ elif key == "models":+ auth_data[key] = [model.strip() for model in value.split(",")]+ else:+ auth_data[key] = value+verbose_proxy_logger.debug("Auth data before creating UserAPIKeyAuth object: keys=%s",list(auth_data.keys()),@@ -45,5 +116,4 @@ async def handle_oauth2_proxy_request(request: Request) -> UserAPIKeyAuth:"UserAPIKeyAuth object created with keys: %s",list(user_api_key_auth.__fields_set__),)- # Create and return UserAPIKeyAuth objectreturn user_api_key_authdiff --git a/tests/test_litellm/proxy/auth/test_oauth2_proxy_hook.py b/tests/test_litellm/proxy/auth/test_oauth2_proxy_hook.pynew file mode 100644index 00000000000..87f8c45087e--- /dev/null+++ b/tests/test_litellm/proxy/auth/test_oauth2_proxy_hook.py@@ -0,0 +1,189 @@+"""+Regression tests for the OAuth2-proxy header-forgery fix+(GHSA-5c3m-qffq-4r9m).++The hook reads HTTP request headers per ``oauth2_config_mappings`` and+constructs a ``UserAPIKeyAuth`` from them. Two separate failure modes+the fix closes:++1. The path was not gated on ``premium_user`` (the sibling+ ``enable_oauth2_auth`` and ``enable_jwt_auth`` paths are). Open-source+ deployments could enable the feature without realising it requires+ a hardened deployment topology.+2. Any ``UserAPIKeyAuth`` field could be mapped from a header — including+ ``user_role``, which Pydantic coerces from the string ``"proxy_admin"``+ into ``LitellmUserRoles.PROXY_ADMIN``. An attacker who reaches the+ proxy directly (or via a misconfigured reverse proxy) sets the mapped+ header and gains full admin privileges.+"""++import os+import sys+from unittest.mock import patch++import pytest+from fastapi import Request+from starlette.datastructures import Headers++sys.path.insert(0, os.path.abspath("../../../.."))++from litellm.proxy._types import LitellmUserRoles+from litellm.proxy.auth.oauth2_proxy_hook import (+ PRIVILEGED_OAUTH2_PROXY_FIELDS,+ handle_oauth2_proxy_request,+)+++def _request_with_headers(headers: dict) -> Request:+ scope = {+ "type": "http",+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()],+ }+ request = Request(scope=scope)+ request._headers = Headers(headers)+ return request+++def premium_proxy_settings(monkeypatch):+ """+ Patch the proxy_server module attributes the hook reads so each test+ starts from "premium=True, mapping={user_id: x-user-id}".+ """+ import litellm.proxy.proxy_server as proxy_server++ monkeypatch.setattr(proxy_server, "premium_user", True, raising=False)+ monkeypatch.setattr(+ proxy_server,+ "general_settings",+ {"oauth2_config_mappings": {"user_id": "x-user-id"}},+ raising=False,+ )+++async def test_returns_auth_for_simple_user_id_mapping(premium_proxy_settings):+ request = _request_with_headers({"x-user-id": "alice"})++ auth = await handle_oauth2_proxy_request(request)++ assert auth.user_id == "alice"+ assert auth.user_role is None+++async def test_rejects_when_not_premium(monkeypatch):+ import litellm.proxy.proxy_server as proxy_server++ monkeypatch.setattr(proxy_server, "premium_user", False, raising=False)+ monkeypatch.setattr(+ proxy_server,+ "general_settings",+ {"oauth2_config_mappings": {"user_id": "x-user-id"}},+ raising=False,+ )+ request = _request_with_headers({"x-user-id": "alice"})++ with pytest.raises(ValueError, match="enterprise"):+ await handle_oauth2_proxy_request(request)+++ "privileged_field",+ sorted(PRIVILEGED_OAUTH2_PROXY_FIELDS),+)+async def test_refuses_to_map_privileged_fields(monkeypatch, privileged_field):+ """+ The exact privesc shape from GHSA-5c3m-qffq-4r9m: an admin maps+ ``user_role`` (or any other privileged field) to a header and a+ caller forges ``X-User-Role: proxy_admin``. The hook must reject+ this configuration outright at request time.+ """+ import litellm.proxy.proxy_server as proxy_server++ monkeypatch.setattr(proxy_server, "premium_user", True, raising=False)+ monkeypatch.setattr(+ proxy_server,+ "general_settings",+ {"oauth2_config_mappings": {privileged_field: f"x-{privileged_field}"}},+ raising=False,+ )+ request = _request_with_headers({f"x-{privileged_field}": "proxy_admin"})++ with pytest.raises(ValueError) as exc:+ await handle_oauth2_proxy_request(request)+ assert privileged_field in str(exc.value)+++async def test_user_role_header_forgery_attack_is_blocked(monkeypatch):+ """+ End-to-end shape from the GHSA: with ``user_role`` mapped, a forged+ ``X-User-Role: proxy_admin`` header would have produced a+ ``UserAPIKeyAuth`` with PROXY_ADMIN role. Now the request raises+ before any auth object is constructed.+ """+ import litellm.proxy.proxy_server as proxy_server++ monkeypatch.setattr(proxy_server, "premium_user", True, raising=False)+ monkeypatch.setattr(+ proxy_server,+ "general_settings",+ {+ "oauth2_config_mappings": {+ "user_id": "x-user-id",+ "user_role": "x-user-role",+ }+ },+ raising=False,+ )+ request = _request_with_headers(+ {+ "x-user-id": "attacker",+ "x-user-role": LitellmUserRoles.PROXY_ADMIN.value,+ }+ )++ with pytest.raises(ValueError, match="user_role"):+ await handle_oauth2_proxy_request(request)+++async def test_safe_fields_still_pass_through(monkeypatch):+ """+ Sanity check that non-privileged fields (the documented use case+ for OAuth2 proxy auth — asserting identity from a trusted upstream)+ still work after the fix.+ """+ import litellm.proxy.proxy_server as proxy_server++ monkeypatch.setattr(proxy_server, "premium_user", True, raising=False)+ monkeypatch.setattr(+ proxy_server,+ "general_settings",+ {+ "oauth2_config_mappings": {+ "user_id": "x-user-id",+ "user_email": "x-user-email",+ "team_id": "x-team-id",+ "models": "x-models",+ }+ },+ raising=False,+ )+ request = _request_with_headers(+ {+ "x-user-id": "alice",+ "x-user-email": "[email protected]",+ "x-team-id": "team-corp",+ "x-models": "gpt-4, gpt-3.5-turbo",+ }+ )++ auth = await handle_oauth2_proxy_request(request)++ assert auth.user_id == "alice"+ assert auth.user_email == "[email protected]"+ assert auth.team_id == "team-corp"+ assert auth.models == ["gpt-4", "gpt-3.5-turbo"]