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(proxy): sanitize redaction controls at ingress
user7497674661e8
diff --git a/litellm/litellm_core_utils/redact_messages.py b/litellm/litellm_core_utils/redact_messages.pyindex 0d7a204c4e9..1837ecb1170 100644--- a/litellm/litellm_core_utils/redact_messages.py+++ b/litellm/litellm_core_utils/redact_messages.py@@ -239,15 +239,12 @@ def should_redact_message_logging(model_call_details: dict) -> bool:Determine if message logging should be redacted.Priority order:- 1. Global setting (litellm.turn_off_message_logging)- 2. Dynamic parameter (turn_off_message_logging in request)- 3. Headers (litellm-disable-message-redaction / litellm-enable-message-redaction)+ 1. Dynamic parameter (turn_off_message_logging in request)+ 2. Headers (litellm-disable-message-redaction / litellm-enable-message-redaction)+ 3. Global setting (litellm.turn_off_message_logging)"""litellm_params = model_call_details.get("litellm_params", {})- if litellm.turn_off_message_logging is True:- return True-metadata_field = get_metadata_variable_name_from_kwargs(litellm_params)metadata = litellm_params.get(metadata_field, {})if not isinstance(metadata, dict):@@ -259,6 +256,13 @@ def should_redact_message_logging(model_call_details: dict) -> bool:# Get headers from the metadatarequest_headers = metadata.get("headers", {})+ # Check for headers that explicitly control redaction+ if request_headers and bool(+ request_headers.get("litellm-disable-message-redaction", False)+ ):+ # User explicitly disabled redaction via header+ return False+possible_enable_headers = ["litellm-enable-message-redaction", # old header. maintain backwards compatibility"x-litellm-enable-message-redaction", # new header@@ -278,18 +282,12 @@ def should_redact_message_logging(model_call_details: dict) -> bool:# Dynamic parameter is explicitly set, use itreturn dynamic_turn_off- if request_headers and bool(- request_headers.get("litellm-disable-message-redaction", False)- ):- # User explicitly disabled redaction via header- return False-# Priority 2: Check if header explicitly enables redactionif is_redaction_enabled_via_header:return True# Priority 3: Fall back to global setting- return False+ return litellm.turn_off_message_logging is Truedef redact_message_input_output_from_logging(diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.pyindex 2f7dcb2afb3..c40f6914089 100644--- a/litellm/proxy/litellm_pre_call_utils.py+++ b/litellm/proxy/litellm_pre_call_utils.py@@ -142,10 +142,35 @@ _UNTRUSTED_METADATA_CONTROL_FIELDS = ("_pipeline_managed_guardrails",)+_UNTRUSTED_REQUEST_HEADER_CONTROL_FIELDS = frozenset(+ {+ "litellm-disable-message-redaction",+ }+)_CLIENT_MOCK_CONTROL_FIELDS = frozenset({"mock_response", "mock_tool_calls"})_ALLOW_CLIENT_MOCK_RESPONSE_METADATA_KEY = "allow_client_mock_response"+def _strip_untrusted_request_header_controls(headers: Any) -> None:+ if not isinstance(headers, dict):+ return++ for header_name in list(headers.keys()):+ if (+ isinstance(header_name, str)+ and header_name.lower() in _UNTRUSTED_REQUEST_HEADER_CONTROL_FIELDS+ ):+ headers.pop(header_name, None)+++def _is_false_like(value: Any) -> bool:+ if isinstance(value, bool):+ return value is False+ if isinstance(value, str):+ return value.strip().lower() in {"false", "0", "no", "off"}+ return False++def _key_or_team_allows_client_mock_response(user_api_key_dict: UserAPIKeyAuth,) -> bool:@@ -1061,6 +1086,13 @@ async def add_litellm_data_to_request( # noqa: PLR0915forward_llm_provider_auth_headers=forward_llm_auth,authenticated_with_header=authenticated_with_header,)+ _strip_untrusted_request_header_controls(_headers)+ if (+ litellm.turn_off_message_logging is True+ and "turn_off_message_logging" in data+ and _is_false_like(data["turn_off_message_logging"])+ ):+ data.pop("turn_off_message_logging", None)verbose_proxy_logger.debug(f"Request Headers: {_headers}")verbose_proxy_logger.debug(f"Raw Headers: {_raw_headers}")@@ -1198,6 +1230,7 @@ async def add_litellm_data_to_request( # noqa: PLR0915for _meta_key in ("metadata", "litellm_metadata"):_user_meta = data.get(_meta_key)if isinstance(_user_meta, dict):+ _strip_untrusted_request_header_controls(_user_meta.get("headers"))for _k in [kfor k in _user_metadiff --git a/tests/litellm_utils_tests/test_utils.py b/tests/litellm_utils_tests/test_utils.pyindex 261375aa9a9..e4dbe5f9f30 100644--- a/tests/litellm_utils_tests/test_utils.py+++ b/tests/litellm_utils_tests/test_utils.py@@ -750,7 +750,7 @@ def test_redact_msgs_from_logs_with_dynamic_params():In all tests litellm.turn_off_message_logging is True- 1. When standard_callback_dynamic_params.turn_off_message_logging is False: global redaction still wins.+ 1. When standard_callback_dynamic_params.turn_off_message_logging is False (or not set): No redaction should occur. User has opted out of redaction.2. When standard_callback_dynamic_params.turn_off_message_logging is True: Redaction should occur. User has opted in to redaction.3. standard_callback_dynamic_params.turn_off_message_logging not set, litellm.turn_off_message_logging is True: Redaction should occur."""@@ -784,7 +784,7 @@ def test_redact_msgs_from_logs_with_dynamic_params():function_id="1234",)- # Test Case 1: standard_callback_dynamic_params = False+ # Test Case 1: standard_callback_dynamic_params = False (or not set)standard_callback_dynamic_params = StandardCallbackDynamicParams(turn_off_message_logging=False)@@ -795,8 +795,8 @@ def test_redact_msgs_from_logs_with_dynamic_params():result=response_obj,model_call_details=litellm_logging_obj.model_call_details,)- # Assert global redaction still occurred- assert _redacted_response_obj.choices[0].message.content == "redacted-by-litellm"+ # Assert no redaction occurred+ assert _redacted_response_obj.choices[0].message.content == test_content# Test Case 2: standard_callback_dynamic_params = Truestandard_callback_dynamic_params = StandardCallbackDynamicParams(@@ -812,7 +812,7 @@ def test_redact_msgs_from_logs_with_dynamic_params():# Assert redaction occurredassert _redacted_response_obj.choices[0].message.content == "redacted-by-litellm"- # Test Case 3: standard_callback_dynamic_params does not override litellm.turn_off_message_logging+ # Test Case 3: standard_callback_dynamic_params does not set turn_off_message_logging# since litellm.turn_off_message_logging is True redaction should occurstandard_callback_dynamic_params = StandardCallbackDynamicParams()litellm_logging_obj.model_call_details["standard_callback_dynamic_params"] = (diff --git a/tests/logging_callback_tests/test_logging_redaction_e2e_test.py b/tests/logging_callback_tests/test_logging_redaction_e2e_test.pyindex 181f13e06d0..08d0abd272e 100644--- a/tests/logging_callback_tests/test_logging_redaction_e2e_test.py+++ b/tests/logging_callback_tests/test_logging_redaction_e2e_test.py@@ -460,16 +460,15 @@ async def test_disable_redaction_header_responses_api():standard_logging_payload = test_custom_logger.logged_standard_logging_payloadassert standard_logging_payload is not None- # Verify that global redaction is not disabled by the header+ # Verify that the direct SDK path still honors the explicit header.print("logged standard logging payload for ResponsesAPI with disable header",json.dumps(standard_logging_payload, indent=2, default=str),)response = standard_logging_payload["response"]- assert response["output"][0]["content"][0]["text"] == "redacted-by-litellm"- assert "This is a test response" not in json.dumps(standard_logging_payload)- assert standard_logging_payload["messages"][0]["content"] == "redacted-by-litellm"+ assert response["output"][0]["content"][0]["text"] == "This is a test response"+ assert standard_logging_payload["messages"][0]["content"] == "hi"@pytest.mark.asynciodiff --git a/tests/test_litellm/litellm_core_utils/test_redact_messages.py b/tests/test_litellm/litellm_core_utils/test_redact_messages.pyindex 58464b2fbd7..d266e594c77 100644--- a/tests/test_litellm/litellm_core_utils/test_redact_messages.py+++ b/tests/test_litellm/litellm_core_utils/test_redact_messages.py@@ -8,7 +8,11 @@ but litellm_params["litellm_metadata"] is None.import pytestimport litellm-from litellm.litellm_core_utils.redact_messages import should_redact_message_logging+from litellm.litellm_core_utils.redact_messages import (+ perform_redaction,+ should_redact_message_logging,+)+from litellm.responses.main import mock_responses_api_response@pytest.fixture(autouse=True)@@ -68,13 +72,13 @@ class TestShouldRedactMessageLogging:assert should_redact_message_logging(details) is Truedef test_disable_redaction_via_header_proxy_flow(self):- """Global redaction should override litellm-disable-message-redaction."""+ """Core helper still honors the explicit disable-redaction header."""litellm.turn_off_message_logging = Truedetails = _make_model_call_details(metadata_headers={"litellm-disable-message-redaction": "true"},litellm_metadata=None,)- assert should_redact_message_logging(details) is True+ assert should_redact_message_logging(details) is Falsedef test_disable_redaction_via_header_when_global_off(self):"""litellm-disable-message-redaction is still honored when global redaction is off."""@@ -134,15 +138,15 @@ class TestShouldRedactMessageLogging:)assert should_redact_message_logging(details) is False- def test_global_redaction_overrides_dynamic_param_false(self):- """Global redaction cannot be disabled by a dynamic parameter."""+ def test_dynamic_param_false_overrides_global_redaction(self):+ """Dynamic turn_off_message_logging=False should take precedence."""litellm.turn_off_message_logging = Truedetails = _make_model_call_details(metadata_headers={},litellm_metadata=None,standard_callback_dynamic_params={"turn_off_message_logging": False},)- assert should_redact_message_logging(details) is True+ assert should_redact_message_logging(details) is False# ---- non-dict metadata safety ----@@ -162,3 +166,99 @@ class TestShouldRedactMessageLogging:litellm_metadata=None,)assert should_redact_message_logging(details) is True+++class TestPerformRedaction:+ def test_redacts_standard_logging_and_responses_api_dicts(self):+ details = {+ "messages": [{"role": "user", "content": "sensitive input"}],+ "prompt": "sensitive prompt",+ "input": "sensitive input",+ "standard_logging_object": {+ "messages": [{"role": "user", "content": "sensitive input"}],+ "response": {+ "output": [+ {"text": "top-level text"},+ {"content": [{"text": "nested text"}]},+ {"type": "reasoning", "summary": [{"text": "reasoning"}]},+ ],+ "usage": {"total_tokens": 1},+ },+ },+ }+ result = {+ "output": [+ {"text": "top-level result"},+ {"content": [{"text": "nested result"}]},+ {"type": "reasoning", "summary": [{"text": "reasoning result"}]},+ ],+ "usage": {"total_tokens": 1},+ }++ redacted = perform_redaction(details, result)++ assert details["messages"] == [+ {"role": "user", "content": "redacted-by-litellm"}+ ]+ assert details["prompt"] == ""+ assert details["input"] == ""++ logged_response = details["standard_logging_object"]["response"]+ assert logged_response["usage"] == {"total_tokens": 1}+ assert logged_response["output"][0]["text"] == "redacted-by-litellm"+ assert logged_response["output"][1]["content"][0]["text"] == (+ "redacted-by-litellm"+ )+ assert logged_response["output"][2]["summary"][0]["text"] == (+ "redacted-by-litellm"+ )++ assert redacted["usage"] == {"total_tokens": 1}+ assert redacted["output"][0]["text"] == "redacted-by-litellm"+ assert redacted["output"][1]["content"][0]["text"] == "redacted-by-litellm"+ assert redacted["output"][2]["summary"][0]["text"] == "redacted-by-litellm"+ assert result["output"][0]["text"] == "top-level result"++ def test_redacts_model_response_dict_choices(self):+ result = {+ "choices": [+ {+ "message": {+ "content": "message content",+ "reasoning_content": "message reasoning",+ "thinking_blocks": ["thinking"],+ "audio": {"data": "audio"},+ }+ },+ {+ "delta": {+ "content": "delta content",+ "reasoning_content": "delta reasoning",+ "thinking_blocks": ["delta thinking"],+ "audio": {"data": "audio"},+ }+ },+ ]+ }++ redacted = perform_redaction({}, result)++ message = redacted["choices"][0]["message"]+ assert message["content"] == "redacted-by-litellm"+ assert message["reasoning_content"] == "redacted-by-litellm"+ assert message["thinking_blocks"] is None+ assert message["audio"] is None++ delta = redacted["choices"][1]["delta"]+ assert delta["content"] == "redacted-by-litellm"+ assert delta["reasoning_content"] == "redacted-by-litellm"+ assert delta["thinking_blocks"] is None+ assert delta["audio"] is None++ def test_redacts_responses_api_response_object(self):+ response = mock_responses_api_response("sensitive output")++ redacted = perform_redaction({}, response)++ assert redacted.output[0].content[0].text == "redacted-by-litellm"+ assert response.output[0].content[0].text == "sensitive output"diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.pyindex d06740745c2..d462a1b7cad 100644--- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py+++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py@@ -628,6 +628,64 @@ async def test_add_litellm_data_to_request_allows_client_mock_response_with_admiassert updated["mock_tool_calls"] == [{"id": "call_1"}]+async def test_add_litellm_data_to_request_strips_client_redaction_bypass_controls():+ request_mock = MagicMock(spec=Request)+ request_mock.url.path = "/v1/chat/completions"+ request_mock.url = MagicMock()+ request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions"+ request_mock.method = "POST"+ request_mock.query_params = {}+ request_mock.headers = {+ "Content-Type": "application/json",+ "litellm-disable-message-redaction": "true",+ }+ request_mock.client = MagicMock()+ request_mock.client.host = "127.0.0.1"++ original_turn_off_message_logging = litellm.turn_off_message_logging+ litellm.turn_off_message_logging = True+ try:+ updated = await add_litellm_data_to_request(+ data={+ "model": "gpt-3.5-turbo",+ "messages": [{"role": "user", "content": "hello"}],+ "turn_off_message_logging": False,+ "metadata": {"headers": {"litellm-disable-message-redaction": "true"}},+ "litellm_metadata": json.dumps(+ {"headers": {"LiteLLM-Disable-Message-Redaction": "true"}}+ ),+ },+ request=request_mock,+ user_api_key_dict=UserAPIKeyAuth(api_key="hashed-key"),+ proxy_config=MagicMock(),+ general_settings={},+ version="test-version",+ )+ finally:+ litellm.turn_off_message_logging = original_turn_off_message_logging++ assert "turn_off_message_logging" not in updated+ assert "litellm-disable-message-redaction" not in {+ header.lower() for header in updated["metadata"]["headers"]+ }+ assert "litellm-disable-message-redaction" not in {+ header.lower()+ for header in updated["metadata"]["requester_metadata"].get("headers", {})+ }+ assert "litellm-disable-message-redaction" not in {+ header.lower() for header in updated["proxy_server_request"]["headers"]+ }+ assert "litellm-disable-message-redaction" not in {+ header.lower()+ for header in updated["proxy_server_request"]["body"]["metadata"]["headers"]+ }+ assert "litellm-disable-message-redaction" not in {+ header.lower()+ for header in (updated.get("litellm_metadata") or {}).get("headers", {})+ }++@pytest.mark.asyncioasync def test_add_litellm_data_to_request_ignores_x_litellm_tags_header_without_permission():"""Regression: the `x-litellm-tags` header bypassed the body-metadata