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): parse string metadata before pre-auth tag merge
shivama5944140e982
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.pyindex 9f6e21521cd..7cd099a7296 100644--- a/litellm/proxy/litellm_pre_call_utils.py+++ b/litellm/proxy/litellm_pre_call_utils.py@@ -1237,7 +1237,15 @@ class LiteLLMProxyRequestSetup:# to _tag_max_budget_check._metadata_variable_name = get_metadata_variable_name_from_kwargs(request_data)metadata = request_data.get(_metadata_variable_name)- if not isinstance(metadata, dict):+ # metadata can arrive as a JSON string (multipart/form-data, extra_body).+ # Parse it so existing tags survive the merge — overwriting the string+ # with {} would let a caller bypass _tag_max_budget_check on an+ # over-budget body tag by also sending a within-budget header tag.+ if isinstance(metadata, str):+ parsed = safe_json_loads(metadata)+ metadata = parsed if isinstance(parsed, dict) else {}+ request_data[_metadata_variable_name] = metadata+ elif not isinstance(metadata, dict):metadata = {}request_data[_metadata_variable_name] = metadatadiff --git a/tests/test_litellm/proxy/credential_endpoints/__init__.py b/tests/test_litellm/proxy/credential_endpoints/__init__.pydeleted file mode 100644index e69de29bb2d..00000000000diff --git a/tests/test_litellm/proxy/credential_endpoints/test_credential_rename_cascade.py b/tests/test_litellm/proxy/credential_endpoints/test_credential_rename_cascade.pydeleted file mode 100644index e8d0e048764..00000000000--- a/tests/test_litellm/proxy/credential_endpoints/test_credential_rename_cascade.py+++ /dev/null@@ -1,165 +0,0 @@-"""-Tests for cascading credential renames into model rows.--When a credential is renamed via PATCH /credentials/{old_name}, every model-row whose `litellm_params.litellm_credential_name` references the old name-must be updated in lockstep — otherwise those models will fail at request-time when the router tries to resolve a credential that no longer exists.-"""--import json-import types-from unittest.mock import AsyncMock, MagicMock--import pytest--import litellm.proxy.proxy_server as ps-from litellm.proxy.common_utils.encrypt_decrypt_utils import encrypt_value_helper-from litellm.proxy.credential_endpoints.endpoints import (- _cascade_rename_credential_in_models,-)---def salt_key(monkeypatch):- """Encrypt/decrypt helpers require a signing key — set one for the test."""- monkeypatch.setenv("LITELLM_SALT_KEY", "test-salt-key-cascade-rename")- yield---def _model_row(model_id: str, credential_name_plain: str | None):- """- Build a fake LiteLLM_ProxyModelTable row whose `litellm_params` mirrors the- on-disk shape (encrypted values, dict-typed JSON column).- """- params: dict = {"model": "gpt-4o"}- if credential_name_plain is not None:- params["litellm_credential_name"] = encrypt_value_helper(- value=credential_name_plain- )- row = MagicMock()- row.model_id = model_id- row.litellm_params = params- return row---async def test_cascade_renames_only_matching_models(salt_key, monkeypatch):- """Only models referencing the old name are updated; others are left alone."""- monkeypatch.setattr(ps, "llm_router", None)-- matching = _model_row("model-1", "old-cred")- other = _model_row("model-2", "different-cred")- no_credential = _model_row("model-3", None)-- tx = types.SimpleNamespace(- litellm_proxymodeltable=types.SimpleNamespace(- find_many=AsyncMock(return_value=[matching, other, no_credential]),- update=AsyncMock(),- )- )-- updated = await _cascade_rename_credential_in_models(- tx=tx,- old_credential_name="old-cred",- new_credential_name="new-cred",- )-- assert updated == 1- tx.litellm_proxymodeltable.update.assert_awaited_once()- call = tx.litellm_proxymodeltable.update.await_args- assert call.kwargs["where"] == {"model_id": "model-1"}-- # Prisma's JSON column expects a serialized string, not a dict.- raw_params = call.kwargs["data"]["litellm_params"]- assert isinstance(raw_params, str)- written_params = json.loads(raw_params)- assert written_params["model"] == "gpt-4o"- # The new credential name is stored encrypted, not plain text.- assert written_params["litellm_credential_name"] != "new-cred"- # And it must round-trip back to the new name.- from litellm.proxy.common_utils.encrypt_decrypt_utils import (- decrypt_value_helper,- )-- assert (- decrypt_value_helper(- value=written_params["litellm_credential_name"],- key="litellm_credential_name",- return_original_value=True,- )- == "new-cred"- )---async def test_cascade_updates_in_memory_router(salt_key, monkeypatch):- """- The router's in-memory model_list holds decrypted credential names. The- cascade must rewrite them so live traffic doesn't try to resolve a name- that no longer exists in litellm.credential_list.- """- fake_router = MagicMock()- fake_router.model_list = [- {"litellm_params": {"litellm_credential_name": "old-cred", "model": "gpt-4o"}},- {- "litellm_params": {- "litellm_credential_name": "other-cred",- "model": "claude",- }- },- {"litellm_params": {"model": "no-creds"}},- ]- monkeypatch.setattr(ps, "llm_router", fake_router)-- matching = _model_row("model-1", "old-cred")- tx = types.SimpleNamespace(- litellm_proxymodeltable=types.SimpleNamespace(- find_many=AsyncMock(return_value=[matching]),- update=AsyncMock(),- )- )-- await _cascade_rename_credential_in_models(- tx=tx,- old_credential_name="old-cred",- new_credential_name="new-cred",- )-- assert (- fake_router.model_list[0]["litellm_params"]["litellm_credential_name"]- == "new-cred"- )- assert (- fake_router.model_list[1]["litellm_params"]["litellm_credential_name"]- == "other-cred"- )- assert "litellm_credential_name" not in fake_router.model_list[2]["litellm_params"]---async def test_cascade_noop_when_no_models_match(salt_key, monkeypatch):- """No matching rows → no updates issued, no in-memory mutation."""- fake_router = MagicMock()- untouched = {- "litellm_params": {"litellm_credential_name": "other-cred", "model": "gpt-4o"}- }- fake_router.model_list = [untouched]- monkeypatch.setattr(ps, "llm_router", fake_router)-- tx = types.SimpleNamespace(- litellm_proxymodeltable=types.SimpleNamespace(- find_many=AsyncMock(return_value=[_model_row("model-2", "other-cred")]),- update=AsyncMock(),- )- )-- updated = await _cascade_rename_credential_in_models(- tx=tx,- old_credential_name="old-cred",- new_credential_name="new-cred",- )-- assert updated == 0- tx.litellm_proxymodeltable.update.assert_not_awaited()- assert untouched["litellm_params"]["litellm_credential_name"] == "other-cred"diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.pyindex 18c11dcc202..19204e8b8ab 100644--- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py+++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py@@ -3991,6 +3991,88 @@ class TestApplyClientTagPolicyPreAuth:assert "metadata" not in data or "tags" not in data["metadata"]+ def test_string_metadata_tags_survive_header_merge(self):+ # metadata can arrive as a JSON string (multipart/form-data, extra_body).+ # The pre-auth merge must parse it so an over-budget body tag isn't+ # silently dropped when a within-budget header tag is also present.+ request_mock = _build_request_mock_with_headers({"x-litellm-tags": "free"})+ data = {+ "model": "gpt-3.5-turbo",+ "metadata": '{"tags": ["paid"]}',+ }+ user_api_key_dict = UserAPIKeyAuth(+ api_key="hashed-key",+ metadata={},+ team_metadata={},+ )++ LiteLLMProxyRequestSetup.apply_client_tag_policy_pre_auth(+ request=request_mock,+ request_data=data,+ user_api_key_dict=user_api_key_dict,+ )++ assert isinstance(data["metadata"], dict)+ assert data["metadata"]["tags"] == ["paid", "free"]++ @pytest.mark.asyncio+ async def test_string_metadata_does_not_bypass_tag_max_budget_check(self):+ """Regression: string metadata containing an over-budget tag must not+ be silently overwritten when an x-litellm-tags header is present."""+ from litellm.proxy._types import LiteLLM_BudgetTable, LiteLLM_TagTable+ from litellm.proxy.auth.auth_checks import _tag_max_budget_check+ from litellm.proxy.utils import ProxyLogging++ request_mock = _build_request_mock_with_headers({"x-litellm-tags": "free"})+ data = {+ "model": "gpt-3.5-turbo",+ "metadata": '{"tags": ["paid"]}',+ }+ user_api_key_dict = UserAPIKeyAuth(+ api_key="hashed-key",+ metadata={},+ team_metadata={},+ )++ LiteLLMProxyRequestSetup.apply_client_tag_policy_pre_auth(+ request=request_mock,+ request_data=data,+ user_api_key_dict=user_api_key_dict,+ )++ paid_tag = LiteLLM_TagTable(+ tag_name="paid",+ spend=0.0,+ litellm_budget_table=LiteLLM_BudgetTable(max_budget=0.10),+ )++ async def mock_get_current_spend(counter_key, fallback_spend):+ if counter_key == "spend:tag:paid":+ return 0.50+ return fallback_spend++ with (+ patch(+ "litellm.proxy.proxy_server.get_current_spend",+ mock_get_current_spend,+ ),+ patch(+ "litellm.proxy.auth.auth_checks.get_tag_objects_batch",+ new_callable=AsyncMock,+ return_value={"paid": paid_tag},+ ),+ ):+ with pytest.raises(litellm.BudgetExceededError) as exc_info:+ await _tag_max_budget_check(+ request_body=data,+ prisma_client=MagicMock(),+ user_api_key_cache=MagicMock(),+ proxy_logging_obj=ProxyLogging(user_api_key_cache=None),+ valid_token=UserAPIKeyAuth(token="test-token"),+ )+ assert exc_info.value.current_cost == 0.50+ assert exc_info.value.max_budget == 0.10+@pytest.mark.asyncioasync def test_header_tags_visible_to_tag_max_budget_check(self):"""End-to-end: helper + ``_tag_max_budget_check`` enforces budget on@@ -4047,6 +4129,8 @@ class TestApplyClientTagPolicyPreAuth:)assert exc_info.value.current_cost == 0.50assert exc_info.value.max_budget == 0.10++# ============================================================================# Tests for #27516: provider hint resolution from deployment when the# user-facing model name has no provider prefix.@@ -4061,9 +4145,7 @@ def test_resolve_provider_from_deployment_uses_litellm_params_model():deployment.litellm_params.custom_llm_provider = Nonerouter.get_deployment_by_model_group_name.return_value = deployment- assert (- _resolve_provider_from_deployment(router, "claude-sonnet-4.6") == "bedrock"- )+ assert _resolve_provider_from_deployment(router, "claude-sonnet-4.6") == "bedrock"def test_resolve_provider_from_deployment_prefers_custom_llm_provider():@@ -4074,9 +4156,7 @@ def test_resolve_provider_from_deployment_prefers_custom_llm_provider():deployment.litellm_params.custom_llm_provider = "bedrock"router.get_deployment_by_model_group_name.return_value = deployment- assert (- _resolve_provider_from_deployment(router, "claude-sonnet-4.6") == "bedrock"- )+ assert _resolve_provider_from_deployment(router, "claude-sonnet-4.6") == "bedrock"def test_resolve_provider_from_deployment_no_match():