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): expand _guardrail_modification_check to cover all bypass keys
userdc8e03b91f8f
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex 56958a88f6d..1f4b5311baf 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -327,15 +327,46 @@ def _global_proxy_budget_check()+_GUARDRAIL_MODIFICATION_KEYS: tuple = (+ "guardrails",+ "disable_global_guardrails",+ "disable_global_guardrail",+ "opted_out_global_guardrails",+)++def _guardrail_modification_check(request_body: dict, team_object: Optional[LiteLLM_TeamTable]) -> None:- _request_metadata: dict = request_body.get("metadata", {}) or {}- if not _request_metadata.get("guardrails"):- return+ """+ Reject user-supplied metadata flags that would modify guardrail behavior+ unless the team has explicit permission. Checked keys include the plural+ ``guardrails`` list plus the per-request toggles that influence whether+ default-on guardrails run (``disable_global_guardrails``,+ ``disable_global_guardrail`` singular, and ``opted_out_global_guardrails``).+ User-supplied values for the bypass toggles are also silently ignored by+ ``_get_admin_metadata`` at read time; this check adds defense in depth by+ failing loudly at the auth layer so operators see an explicit 403 instead+ of a confusing silent-ignore.+ """from litellm.proxy.guardrails.guardrail_helpers import can_modify_guardrails+ def _user_requested_modification(container: Any) -> bool:+ if not isinstance(container, dict):+ return False+ return any(container.get(key) for key in _GUARDRAIL_MODIFICATION_KEYS)++ # Check both metadata keys — callers can populate either depending on the+ # endpoint. Cover the top-level too so root-level injection is rejected.+ modifies = (+ _user_requested_modification(request_body.get("metadata"))+ or _user_requested_modification(request_body.get("litellm_metadata"))+ or _user_requested_modification(request_body)+ )+ if not modifies:+ return+if not can_modify_guardrails(team_object):raise HTTPException(status_code=403,@@ -451,9 +482,9 @@ async def common_checks( # noqa: PLR0915model=_model,team_object=team_object,llm_router=llm_router,- team_model_aliases=valid_token.team_model_aliases- if valid_token- else None,+ team_model_aliases=(+ valid_token.team_model_aliases if valid_token else None+ ),):raise ProxyException(message=f"Team not allowed to access model. Team={team_object.team_id}, Model={_model}. Allowed team models = {team_object.models}",diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.pyindex bd659ed518f..a3d24fc8bf6 100644--- a/tests/test_litellm/proxy/auth/test_auth_checks.py+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py@@ -62,9 +62,9 @@ def reset_constants_module():# Reload modules before testimportlib.reload(constants)importlib.reload(auth_checks)-+yield-+# Reload modules after test to clean upimportlib.reload(constants)importlib.reload(auth_checks)@@ -157,9 +157,9 @@ def test_experimental_ui_token_ignores_litellm_ui_session_duration(expires = datetime.fromisoformat(token_data["expires"].replace("Z", "+00:00"))now = get_utc_datetime()# Must be ~10 min, NOT 24h. If LITELLM_UI_SESSION_DURATION were incorrectly used, this would fail.- assert expires <= now + timedelta(minutes=11), (- "Experimental UI must use 10-min expiry, not LITELLM_UI_SESSION_DURATION"- )+ assert expires <= now + timedelta(+ minutes=11+ ), "Experimental UI must use 10-min expiry, not LITELLM_UI_SESSION_DURATION"def test_get_experimental_ui_login_jwt_auth_token_invalid(@@ -293,13 +293,15 @@ def test_get_cli_jwt_auth_token_custom_expiration(# Set custom expiration to 48 hoursmonkeypatch.setenv("LITELLM_CLI_JWT_EXPIRATION_HOURS", "48")-+# Reload the constants module to pick up the new env varimportlib.reload(constants)# Also reload auth_checks to pick up the new constant valueimportlib.reload(auth_checks)-- token = auth_checks.ExperimentalUIJWTToken.get_cli_jwt_auth_token(valid_sso_user_defined_values)++ token = auth_checks.ExperimentalUIJWTToken.get_cli_jwt_auth_token(+ valid_sso_user_defined_values+ )# Decrypt and verify token contentsdecrypted_token = decrypt_value_helper(@@ -315,7 +317,6 @@ def test_get_cli_jwt_auth_token_custom_expiration(assert expires <= get_utc_datetime() + timedelta(hours=48, minutes=1)-@pytest.mark.asyncioasync def test_default_internal_user_params_with_get_user_object(monkeypatch):"""Test that default_internal_user_params is used when creating a new user via get_user_object"""@@ -436,7 +437,9 @@ async def test_get_user_object_upsert_includes_user_email():mock_prisma_client.db.litellm_usertable.create.assert_called_once()creation_args = mock_prisma_client.db.litellm_usertable.create.call_args[1]["data"]- assert "user_email" in creation_args, "user_email should be included when upserting a new user"+ assert (+ "user_email" in creation_args+ ), "user_email should be included when upserting a new user"assert creation_args["user_email"] == "[email protected]"assert creation_args["user_id"] == "new_test_user"@@ -463,7 +466,9 @@ def test_log_budget_lookup_failure_skips_user_not_found():@pytest.mark.asyncio-@patch("litellm.proxy.management_endpoints.team_endpoints.new_team", new_callable=AsyncMock)+@patch(+ "litellm.proxy.management_endpoints.team_endpoints.new_team", new_callable=AsyncMock+)async def test_get_team_db_check_calls_new_team_on_upsert(mock_new_team, monkeypatch):"""Test that _get_team_db_check correctly calls the `new_team` function@@ -497,8 +502,12 @@ async def test_get_team_db_check_calls_new_team_on_upsert(mock_new_team, monkeyp@pytest.mark.asyncio-@patch("litellm.proxy.management_endpoints.team_endpoints.new_team", new_callable=AsyncMock)-async def test_get_team_db_check_does_not_call_new_team_if_exists(mock_new_team, monkeypatch):+@patch(+ "litellm.proxy.management_endpoints.team_endpoints.new_team", new_callable=AsyncMock+)+async def test_get_team_db_check_does_not_call_new_team_if_exists(+ mock_new_team, monkeypatch+):"""Test that _get_team_db_check does NOT call the `new_team` functionif the team already exists in the database.@@ -541,8 +550,9 @@ async def test_vector_store_access_check_early_returns(if vector_store_registry:vector_store_registry.get_vector_store_ids_to_run.return_value = None- with patch("litellm.proxy.proxy_server.prisma_client", prisma_client), patch(- "litellm.vector_store_registry", vector_store_registry+ with (+ patch("litellm.proxy.proxy_server.prisma_client", prisma_client),+ patch("litellm.vector_store_registry", vector_store_registry),):result = await vector_store_access_check(request_body=request_body,@@ -639,8 +649,9 @@ async def test_vector_store_access_check_with_permissions():mock_vector_store_registry = MagicMock()mock_vector_store_registry.get_vector_store_ids_to_run.return_value = ["store-1"]- with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), patch(- "litellm.vector_store_registry", mock_vector_store_registry+ with (+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),+ patch("litellm.vector_store_registry", mock_vector_store_registry),):result = await vector_store_access_check(request_body=request_body,@@ -653,8 +664,9 @@ async def test_vector_store_access_check_with_permissions():# Test with denied accessmock_vector_store_registry.get_vector_store_ids_to_run.return_value = ["store-3"]- with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), patch(- "litellm.vector_store_registry", mock_vector_store_registry+ with (+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),+ patch("litellm.vector_store_registry", mock_vector_store_registry),):with pytest.raises(ProxyException) as exc_info:await vector_store_access_check(@@ -687,8 +699,9 @@ async def test_vector_store_access_check_with_team_permissions():"team-store-allowed"]- with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), patch(- "litellm.vector_store_registry", mock_vector_store_registry+ with (+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),+ patch("litellm.vector_store_registry", mock_vector_store_registry),):result = await vector_store_access_check(request_body=request_body,@@ -702,8 +715,9 @@ async def test_vector_store_access_check_with_team_permissions():"team-store-denied"]- with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client), patch(- "litellm.vector_store_registry", mock_vector_store_registry+ with (+ patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),+ patch("litellm.vector_store_registry", mock_vector_store_registry),):with pytest.raises(ProxyException) as exc_info:await vector_store_access_check(@@ -1598,12 +1612,15 @@ async def test_custom_auth_common_checks_opt_in():mock_request = MagicMock()# Default (no flag) — common_checks should NOT be called- with patch(- "litellm.proxy.auth.user_api_key_auth.common_checks",- new_callable=AsyncMock,- ) as mock_common, patch(- "litellm.proxy.proxy_server.general_settings",- {},+ with (+ patch(+ "litellm.proxy.auth.user_api_key_auth.common_checks",+ new_callable=AsyncMock,+ ) as mock_common,+ patch(+ "litellm.proxy.proxy_server.general_settings",+ {},+ ),):mock_common.return_value = Trueresult = await _run_post_custom_auth_checks(@@ -1616,12 +1633,15 @@ async def test_custom_auth_common_checks_opt_in():mock_common.assert_not_called()# With flag=True — common_checks SHOULD be called- with patch(- "litellm.proxy.auth.user_api_key_auth.common_checks",- new_callable=AsyncMock,- ) as mock_common, patch(- "litellm.proxy.proxy_server.general_settings",- {"custom_auth_run_common_checks": True},+ with (+ patch(+ "litellm.proxy.auth.user_api_key_auth.common_checks",+ new_callable=AsyncMock,+ ) as mock_common,+ patch(+ "litellm.proxy.proxy_server.general_settings",+ {"custom_auth_run_common_checks": True},+ ),):mock_common.return_value = Trueresult = await _run_post_custom_auth_checks(@@ -1660,9 +1680,7 @@ async def test_virtual_key_budget_check_reads_from_spend_counter():return 1.5return fallback_spend- with patch(- "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend- ):+ with patch("litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend):with pytest.raises(litellm.BudgetExceededError) as exc_info:await _virtual_key_max_budget_check(valid_token=valid_token,@@ -1692,9 +1710,7 @@ async def test_virtual_key_budget_check_fallback_no_counter():async def mock_get_current_spend(counter_key, fallback_spend):return fallback_spend- with patch(- "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend- ):+ with patch("litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend):with pytest.raises(litellm.BudgetExceededError) as exc_info:await _virtual_key_max_budget_check(valid_token=valid_token,@@ -1723,9 +1739,7 @@ async def test_team_budget_check_reads_from_spend_counter():return 1.5return fallback_spend- with patch(- "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend- ):+ with patch("litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend):with pytest.raises(litellm.BudgetExceededError) as exc_info:await _team_max_budget_check(team_object=team_object,@@ -1763,12 +1777,13 @@ async def test_team_member_budget_check_reads_from_spend_counter():return 1.5return fallback_spend- with patch(- "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend- ), patch(- "litellm.proxy.auth.auth_checks.get_team_membership",- new_callable=AsyncMock,- return_value=team_membership,+ with (+ patch("litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend),+ patch(+ "litellm.proxy.auth.auth_checks.get_team_membership",+ new_callable=AsyncMock,+ return_value=team_membership,+ ),):with pytest.raises(litellm.BudgetExceededError) as exc_info:await _check_team_member_budget(@@ -1780,3 +1795,105 @@ async def test_team_member_budget_check_reads_from_spend_counter():proxy_logging_obj=proxy_logging_obj,)assert exc_info.value.current_cost == 1.5+++class TestGuardrailModificationCheck:+ """Defense-in-depth: `_guardrail_modification_check` must 403 when the+ caller's metadata attempts to modify any guardrail-related key and the+ team lacks the `modify_guardrails` permission. Checks both the+ historically-covered `guardrails` list and the bypass toggles that+ `_get_admin_metadata` silently ignores at read time.+ """++ def _call(self, request_body):+ from litellm.proxy.auth.auth_checks import _guardrail_modification_check++ team_object = MagicMock()+ team_object.metadata = {} # no permission+ return _guardrail_modification_check(+ request_body=request_body, team_object=team_object+ )++ def test_noop_when_no_guardrail_keys_present(self):+ # no-op — should return silently+ self._call({"metadata": {"unrelated": "value"}})++ def test_rejects_guardrails_list(self):+ from fastapi import HTTPException++ with patch(+ "litellm.proxy.guardrails.guardrail_helpers.can_modify_guardrails",+ return_value=False,+ ):+ with pytest.raises(HTTPException) as exc:+ self._call({"metadata": {"guardrails": ["custom"]}})+ assert exc.value.status_code == 403++ def test_rejects_disable_global_guardrails_plural(self):+ from fastapi import HTTPException++ with patch(+ "litellm.proxy.guardrails.guardrail_helpers.can_modify_guardrails",+ return_value=False,+ ):+ with pytest.raises(HTTPException) as exc:+ self._call({"metadata": {"disable_global_guardrails": True}})+ assert exc.value.status_code == 403++ def test_rejects_disable_global_guardrail_singular(self):+ """VERIA-28's originally-reported singular-key typo variant."""+ from fastapi import HTTPException++ with patch(+ "litellm.proxy.guardrails.guardrail_helpers.can_modify_guardrails",+ return_value=False,+ ):+ with pytest.raises(HTTPException) as exc:+ self._call({"metadata": {"disable_global_guardrail": True}})+ assert exc.value.status_code == 403++ def test_rejects_opted_out_global_guardrails(self):+ from fastapi import HTTPException++ with patch(+ "litellm.proxy.guardrails.guardrail_helpers.can_modify_guardrails",+ return_value=False,+ ):+ with pytest.raises(HTTPException) as exc:+ self._call(+ {"metadata": {"opted_out_global_guardrails": ["some_guardrail"]}}+ )+ assert exc.value.status_code == 403++ def test_rejects_injection_via_litellm_metadata_key(self):+ """Caller can populate the OTHER metadata key; that must also 403."""+ from fastapi import HTTPException++ with patch(+ "litellm.proxy.guardrails.guardrail_helpers.can_modify_guardrails",+ return_value=False,+ ):+ with pytest.raises(HTTPException) as exc:+ self._call({"litellm_metadata": {"disable_global_guardrails": True}})+ assert exc.value.status_code == 403++ def test_rejects_root_level_injection(self):+ """Top-level injection (`request_body["disable_global_guardrails"]`)+ was VERIA-28's easiest variant to hit — keep it rejected."""+ from fastapi import HTTPException++ with patch(+ "litellm.proxy.guardrails.guardrail_helpers.can_modify_guardrails",+ return_value=False,+ ):+ with pytest.raises(HTTPException) as exc:+ self._call({"disable_global_guardrails": True})+ assert exc.value.status_code == 403++ def test_allows_when_team_has_permission(self):+ with patch(+ "litellm.proxy.guardrails.guardrail_helpers.can_modify_guardrails",+ return_value=True,+ ):+ # no-op, should not raise+ self._call({"metadata": {"disable_global_guardrails": True}})