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(utils.py): rollback faulty security check on files (#12441)
Krish Dholakiac42880d771b0
diff --git a/litellm/proxy/auth/route_checks.py b/litellm/proxy/auth/route_checks.pyindex 22490919e01..083a93641e4 100644--- a/litellm/proxy/auth/route_checks.py+++ b/litellm/proxy/auth/route_checks.py@@ -99,6 +99,7 @@ class RouteChecks:):passelif _user_role == LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value:+if RouteChecks.is_llm_api_route(route=route):raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,@@ -107,6 +108,7 @@ class RouteChecks:if RouteChecks.check_route_access(route=route, allowed_routes=LiteLLMRoutes.management_routes.value):+# the Admin Viewer is only allowed to call /user/update for their own user_id and can only updateif route == "/user/update":# Check the Request params are valid for PROXY_ADMIN_VIEW_ONLY@@ -123,6 +125,11 @@ class RouteChecks:status_code=status.HTTP_403_FORBIDDEN,detail=f"user not allowed to access this route, role= {_user_role}. Trying to access: {route}",)+ else:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"user not allowed to access this route, role= {_user_role}. Trying to access: {route}",+ )elif (_user_role == LitellmUserRoles.INTERNAL_USER.value@@ -196,8 +203,7 @@ class RouteChecks:return Trueif RouteChecks.check_route_access(- route=route,- allowed_routes=LiteLLMRoutes.mcp_routes.value+ route=route, allowed_routes=LiteLLMRoutes.mcp_routes.value):return Truediff --git a/litellm/proxy/types_utils/utils.py b/litellm/proxy/types_utils/utils.pyindex f3dbfda6b26..e159da49549 100644--- a/litellm/proxy/types_utils/utils.py+++ b/litellm/proxy/types_utils/utils.py@@ -14,9 +14,6 @@ def get_instance_fn(value: str, config_file_path: Optional[str] = None) -> Any:module_name = ".".join(parts[:-1])instance_name = parts[-1]- # Security: Check if the module name contains any dangerous modules that can execute arbitrary code- security_checks(module_name=module_name)-# If config_file_path is provided, use it to determine the module spec and load the moduleif config_file_path is not None:directory = os.path.dirname(config_file_path)@@ -50,37 +47,8 @@ def get_instance_fn(value: str, config_file_path: Optional[str] = None) -> Any:raise e-def security_checks(- module_name: str,-):- """- This function checks if the module name contains any dangerous modules that can execute arbitrary code.-- Reference: https://huntr.com/bounties/1d98bebb-6cf4-46c9-87c3-d3b1972973b5- """- DANGEROUS_MODULES = [- "os",- "sys",- "subprocess",- "shutil",- "socket",- "multiprocessing",- "threading",- "ctypes",- "pickle",- "marshal",- "builtins",- "__builtin__",- ]- # Security: Check if the module name contains any dangerous modules- if any(dangerous in module_name.lower() for dangerous in DANGEROUS_MODULES):- raise ImportError(- f"Importing from module {module_name} is not allowed for security reasons"- )--def validate_custom_validate_return_type(- fn: Optional[Callable[..., Any]]+ fn: Optional[Callable[..., Any]],) -> Optional[Callable[..., Literal[True]]]:if fn is None:return Nonediff --git a/tests/test_litellm/proxy/auth/test_route_checks.py b/tests/test_litellm/proxy/auth/test_route_checks.pynew file mode 100644index 00000000000..a6358e73c36--- /dev/null+++ b/tests/test_litellm/proxy/auth/test_route_checks.py@@ -0,0 +1,91 @@+import asyncio+import os+import sys+from unittest.mock import MagicMock++sys.path.insert(+ 0, os.path.abspath("../../..")+) # Adds the parent directory to the system path++import pytest+from fastapi import HTTPException, Request++from litellm.proxy._types import LiteLLM_UserTable, LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.route_checks import RouteChecks+++def test_non_admin_config_update_route_rejected():+ """Test that non-admin users are rejected when trying to call /config/update"""++ # Create a non-admin user object+ user_obj = LiteLLM_UserTable(+ user_id="test_user",+ user_email="[email protected]",+ user_role=LitellmUserRoles.INTERNAL_USER.value, # Non-admin role+ )++ # Create a non-admin user API key auth+ valid_token = UserAPIKeyAuth(+ user_id="test_user",+ user_role=LitellmUserRoles.INTERNAL_USER.value, # Non-admin role+ )++ # Create a mock request+ request = MagicMock(spec=Request)+ request.query_params = {}++ # Test that calling /config/update route raises HTTPException with 403 status+ with pytest.raises(Exception) as exc_info:+ RouteChecks.non_proxy_admin_allowed_routes_check(+ user_obj=user_obj,+ _user_role=LitellmUserRoles.INTERNAL_USER.value,+ route="/config/update",+ request=request,+ valid_token=valid_token,+ request_data={},+ )++ # Verify the exception is raised with the correct message+ assert (+ "Only proxy admin can be used to generate, delete, update info for new keys/users/teams"+ in str(exc_info.value)+ )+ assert "Route=/config/update" in str(exc_info.value)+ assert "Your role=internal_user" in str(exc_info.value)+++def test_proxy_admin_viewer_config_update_route_rejected():+ """Test that proxy admin viewer users are rejected when trying to call /config/update"""++ # Create a proxy admin viewer user object (read-only admin)+ user_obj = LiteLLM_UserTable(+ user_id="viewer_user",+ user_email="[email protected]",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ )++ # Create a proxy admin viewer user API key auth+ valid_token = UserAPIKeyAuth(+ user_id="viewer_user",+ user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ )++ # Create a mock request+ request = MagicMock(spec=Request)+ request.query_params = {}++ # Test that calling /config/update route raises HTTPException with 403 status+ with pytest.raises(HTTPException) as exc_info:+ RouteChecks.non_proxy_admin_allowed_routes_check(+ user_obj=user_obj,+ _user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ route="/config/update",+ request=request,+ valid_token=valid_token,+ request_data={},+ )++ # Verify the exception is HTTPException with 403 status+ assert exc_info.value.status_code == 403+ assert "user not allowed to access this route" in str(exc_info.value.detail)+ assert "role= proxy_admin_viewer" in str(exc_info.value.detail)diff --git a/tests/test_litellm/proxy/types_utils/test_litellm_proxy_types_utils.py b/tests/test_litellm/proxy/types_utils/test_litellm_proxy_types_utils.pydeleted file mode 100644index 5685489bfce..00000000000--- a/tests/test_litellm/proxy/types_utils/test_litellm_proxy_types_utils.py+++ /dev/null@@ -1,72 +0,0 @@-import json-import os-import sys--import pytest-from fastapi.testclient import TestClient--from litellm.proxy.types_utils.utils import security_checks--sys.path.insert(- 0, os.path.abspath("../../..")-) # Adds the parent directory to the system path---def test_security_checks_blocks_dangerous_modules():- """- Resolves: https://huntr.com/bounties/1d98bebb-6cf4-46c9-87c3-d3b1972973b5-- This test checks if the security_checks function correctly blocks the import of dangerous modules.- """- dangerous_module = "/usr/lib/python3/os.system"- with pytest.raises(ImportError) as exc_info:- security_checks(dangerous_module)-- assert "not allowed for security reasons" in str(exc_info.value)- assert dangerous_module in str(exc_info.value)---def test_security_checks_various_dangerous_modules():- dangerous_modules = [- "subprocess.run",- "socket.socket",- "pickle.loads",- "marshal.loads",- "ctypes.CDLL",- "builtins.eval",- "__builtin__.exec",- "shutil.rmtree",- "multiprocessing.Process",- "threading.Thread",- ]-- for module in dangerous_modules:- with pytest.raises(ImportError) as exc_info:- security_checks(module)- assert "not allowed for security reasons" in str(exc_info.value)- assert module in str(exc_info.value)---def test_security_checks_case_insensitive():- # Test that the check is case-insensitive- variations = ["OS.system", "os.System", "Os.SyStEm", "SUBPROCESS.run"]-- for module in variations:- with pytest.raises(ImportError) as exc_info:- security_checks(module)- assert "not allowed for security reasons" in str(exc_info.value)---def test_security_checks_nested_paths():- # Test nested paths that contain dangerous modules- nested_paths = [- "some/path/to/os/system",- "myproject/utils/subprocess_wrapper",- "lib/helpers/socket_utils",- "../../../system/os.py",- ]-- for path in nested_paths:- with pytest.raises(ImportError) as exc_info:- security_checks(path)- assert "not allowed for security reasons" in str(exc_info.value)