Skip to content

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]

Fix mutation bug: copy lists in get_key_models to prevent corrupting cached UserAPIKeyAuth

yuneng-jiang1755a281bd61
diff --git a/litellm/proxy/auth/model_checks.py b/litellm/proxy/auth/model_checks.py
index ccbc2f01942..13b26eef43f 100644
--- a/litellm/proxy/auth/model_checks.py
+++ b/litellm/proxy/auth/model_checks.py
@@ -108,9 +108,9 @@ def get_key_models(
"""
all_models: List[str] = []
if len(user_api_key_dict.models) > 0:
- all_models = user_api_key_dict.models
+ all_models = list(user_api_key_dict.models) # copy to avoid mutating cached objects
if SpecialModelNames.all_team_models.value in all_models:
- all_models = user_api_key_dict.team_models
+ all_models = list(user_api_key_dict.team_models) # copy to avoid mutating cached objects
if SpecialModelNames.all_proxy_models.value in all_models:
all_models = list(proxy_model_list) # copy to avoid mutating caller's list
if include_model_access_groups:
diff --git a/tests/test_litellm/proxy/auth/test_model_checks.py b/tests/test_litellm/proxy/auth/test_model_checks.py
index 2b484bf975b..c43621d7f71 100644
--- a/tests/test_litellm/proxy/auth/test_model_checks.py
+++ b/tests/test_litellm/proxy/auth/test_model_checks.py
@@ -127,6 +127,34 @@ def test_get_key_models_passes_include_model_access_groups():
assert "model2" in result
+def test_get_key_models_does_not_mutate_input():
+ """
+ get_key_models must not mutate user_api_key_dict.models in-place.
+ _get_models_from_access_groups uses .pop()/.extend() which would corrupt
+ cached UserAPIKeyAuth objects if all_models were an alias instead of a copy.
+ """
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.auth.model_checks import get_key_models
+
+ original_models = ["group-a", "extra-model"]
+ user_api_key_dict = UserAPIKeyAuth(
+ models=list(original_models), # give it a list
+ api_key="test-key",
+ )
+ model_access_groups = {
+ "group-a": ["model1", "model2"],
+ }
+
+ _ = get_key_models(
+ user_api_key_dict=user_api_key_dict,
+ proxy_model_list=["model1", "model2"],
+ model_access_groups=model_access_groups,
+ include_model_access_groups=False,
+ )
+ # The original models list on the auth object must be unchanged
+ assert user_api_key_dict.models == original_models
+
+
@pytest.mark.parametrize(
"key_models,team_models,proxy_model_list,model_list,expected",
[