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
Remove + Check for unsafe `enterprise/` folder imports (#11107)
Krish Dholakiaa44bc9f61398
diff --git a/.circleci/config.yml b/.circleci/config.ymlindex 2319cedbdfa..779f302c947 100644--- a/.circleci/config.yml+++ b/.circleci/config.yml@@ -1349,6 +1349,7 @@ jobs:- run: python ./tests/code_coverage_tests/enforce_llms_folder_style.py- run: python ./tests/documentation_tests/test_circular_imports.py- run: python ./tests/code_coverage_tests/prevent_key_leaks_in_exceptions.py+ - run: python ./tests/code_coverage_tests/check_unsafe_enterprise_import.py- run: helm lint ./deploy/charts/litellm-helmdb_migration_disable_update_check:diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex 6abe507e27c..d9830279f7a 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -352,6 +352,7 @@ router_settings:| CONFIG_FILE_PATH | File path for configuration file| CONFIDENT_API_KEY | API key for DeepEval integration| CUSTOM_TIKTOKEN_CACHE_DIR | Custom directory for Tiktoken cache+| CONFIDENT_API_KEY | API key for Confident AI (Deepeval) Logging service| DATABASE_HOST | Hostname for the database server| DATABASE_NAME | Name of the database| DATABASE_PASSWORD | Password for the database user@@ -507,6 +508,7 @@ router_settings:| LITELLM_GLOBAL_MAX_PARALLEL_REQUEST_RETRY_TIMEOUT | Timeout for retries of parallel requests in LiteLLM| LITELLM_MIGRATION_DIR | Custom migrations directory for prisma migrations, used for baselining db in read-only file systems.| LITELLM_HOSTED_UI | URL of the hosted UI for LiteLLM+| LITELM_ENVIRONMENT | Environment of LiteLLM Instance, used by logging services. Currently only used by DeepEval.| LITELLM_LICENSE | License key for LiteLLM usage| LITELLM_LOCAL_MODEL_COST_MAP | Local configuration for model cost mapping in LiteLLM| LITELLM_LOG | Enable detailed logging for LiteLLMdiff --git a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.pyindex 779d4f2eb37..b4b128b6249 100644--- a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py+++ b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py@@ -7,6 +7,12 @@ import jsonimport osfrom typing import List, Optional+from litellm_enterprise.types.enterprise_callbacks.send_emails import (+ EmailEvent,+ EmailParams,+ SendKeyCreatedEmailEvent,+)+from litellm._logging import verbose_proxy_loggerfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.email_templates.email_footer import EMAIL_FOOTER@@ -17,11 +23,6 @@ from litellm.integrations.email_templates.user_invitation_email import (USER_INVITATION_EMAIL_TEMPLATE,)from litellm.proxy._types import WebhookEvent-from litellm.types.enterprise.enterprise_callbacks.send_emails import (- EmailEvent,- EmailParams,- SendKeyCreatedEmailEvent,-)from litellm.types.integrations.slack_alerting import LITELLM_LOGO_URLdiff --git a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/endpoints.py b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/endpoints.pyindex cc6f0be80f9..61681c27ee9 100644--- a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/endpoints.py+++ b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/endpoints.py@@ -6,11 +6,7 @@ import jsonfrom typing import Dictfrom fastapi import APIRouter, Depends, HTTPException--from litellm._logging import verbose_proxy_logger-from litellm.proxy._types import UserAPIKeyAuth-from litellm.proxy.auth.user_api_key_auth import user_api_key_auth-from litellm.types.enterprise.enterprise_callbacks.send_emails import (+from litellm_enterprise.types.enterprise_callbacks.send_emails import (DefaultEmailSettings,EmailEvent,EmailEventSettings,@@ -18,6 +14,10 @@ from litellm.types.enterprise.enterprise_callbacks.send_emails import (EmailEventSettingsUpdateRequest,)+from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+router = APIRouter()diff --git a/litellm/types/enterprise/enterprise_callbacks/send_emails.py b/enterprise/litellm_enterprise/types/enterprise_callbacks/send_emails.pysimilarity index 100%rename from litellm/types/enterprise/enterprise_callbacks/send_emails.pyrename to enterprise/litellm_enterprise/types/enterprise_callbacks/send_emails.pydiff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 06ac41d6a10..1802b1f25d3 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -2167,6 +2167,10 @@ class CommonProxyErrors(str, enum.Enum):max_parallel_request_limit_reached = ("Crossed TPM / RPM / Max Parallel Request Limit")+ missing_enterprise_package = "Missing litellm-enterprise package. Please install it to use this feature. Run `pip install litellm-enterprise`"+ missing_enterprise_package_docker = (+ "This uses the enterprise folder - only available on the Docker image."+ )class SpendCalculateRequest(LiteLLMPydanticObjectBase):diff --git a/litellm/proxy/common_utils/callback_utils.py b/litellm/proxy/common_utils/callback_utils.pyindex 9f4f370f331..39498202b6b 100644--- a/litellm/proxy/common_utils/callback_utils.py+++ b/litellm/proxy/common_utils/callback_utils.py@@ -56,9 +56,15 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915pii_masking_object = _OPTIONAL_PresidioPIIMasking(**params)imported_list.append(pii_masking_object)elif isinstance(callback, str) and callback == "llamaguard_moderations":- from litellm_enterprise.enterprise_callbacks.llama_guard import (- _ENTERPRISE_LlamaGuard,- )+ try:+ from litellm_enterprise.enterprise_callbacks.llama_guard import (+ _ENTERPRISE_LlamaGuard,+ )+ except ImportError:+ raise Exception(+ "MissingTrying to use Llama Guard"+ + CommonProxyErrors.missing_enterprise_package.value+ )if premium_user is not True:raise Exception(@@ -69,9 +75,15 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915llama_guard_object = _ENTERPRISE_LlamaGuard()imported_list.append(llama_guard_object)elif isinstance(callback, str) and callback == "hide_secrets":- from litellm_enterprise.enterprise_callbacks.secret_detection import (- _ENTERPRISE_SecretDetection,- )+ try:+ from litellm_enterprise.enterprise_callbacks.secret_detection import (+ _ENTERPRISE_SecretDetection,+ )+ except ImportError:+ raise Exception(+ "Trying to use Secret Detection"+ + CommonProxyErrors.missing_enterprise_package.value+ )if premium_user is not True:raise Exception(@@ -82,9 +94,15 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915_secret_detection_object = _ENTERPRISE_SecretDetection()imported_list.append(_secret_detection_object)elif isinstance(callback, str) and callback == "openai_moderations":- from enterprise.enterprise_hooks.openai_moderation import (- _ENTERPRISE_OpenAI_Moderation,- )+ try:+ from enterprise.enterprise_hooks.openai_moderation import (+ _ENTERPRISE_OpenAI_Moderation,+ )+ except ImportError:+ raise Exception(+ "Trying to use OpenAI Moderations Check,"+ + CommonProxyErrors.missing_enterprise_package_docker.value+ )if premium_user is not True:raise Exception(@@ -112,9 +130,15 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915aporia_guardrail_object = AporiaGuardrail()imported_list.append(aporia_guardrail_object)elif isinstance(callback, str) and callback == "google_text_moderation":- from enterprise.enterprise_hooks.google_text_moderation import (- _ENTERPRISE_GoogleTextModeration,- )+ try:+ from enterprise.enterprise_hooks.google_text_moderation import (+ _ENTERPRISE_GoogleTextModeration,+ )+ except ImportError:+ raise Exception(+ "Trying to use Google Text Moderation,"+ + CommonProxyErrors.missing_enterprise_package_docker.value+ )if premium_user is not True:raise Exception(@@ -125,9 +149,15 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915google_text_moderation_obj = _ENTERPRISE_GoogleTextModeration()imported_list.append(google_text_moderation_obj)elif isinstance(callback, str) and callback == "llmguard_moderations":- from litellm_enterprise.enterprise_callbacks.llm_guard import (- _ENTERPRISE_LLMGuard,- )+ try:+ from litellm_enterprise.enterprise_callbacks.llm_guard import (+ _ENTERPRISE_LLMGuard,+ )+ except ImportError:+ raise Exception(+ "Trying to use Llm Guard"+ + CommonProxyErrors.missing_enterprise_package.value+ )if premium_user is not True:raise Exception(@@ -138,9 +168,15 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915llm_guard_moderation_obj = _ENTERPRISE_LLMGuard()imported_list.append(llm_guard_moderation_obj)elif isinstance(callback, str) and callback == "blocked_user_check":- from enterprise.enterprise_hooks.blocked_user_list import (- _ENTERPRISE_BlockedUserList,- )+ try:+ from enterprise.enterprise_hooks.blocked_user_list import (+ _ENTERPRISE_BlockedUserList,+ )+ except ImportError:+ raise Exception(+ "Trying to use Blocked User List"+ + CommonProxyErrors.missing_enterprise_package_docker.value+ )if premium_user is not True:raise Exception(@@ -153,9 +189,15 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915)imported_list.append(blocked_user_list)elif isinstance(callback, str) and callback == "banned_keywords":- from enterprise.enterprise_hooks.banned_keywords import (- _ENTERPRISE_BannedKeywords,- )+ try:+ from enterprise.enterprise_hooks.banned_keywords import (+ _ENTERPRISE_BannedKeywords,+ )+ except ImportError:+ raise Exception(+ "Trying to use Banned Keywords"+ + CommonProxyErrors.missing_enterprise_package_docker.value+ )if premium_user is not True:raise Exception(diff --git a/litellm/proxy/guardrails/guardrail_initializers.py b/litellm/proxy/guardrails/guardrail_initializers.pyindex 468df07ea42..6685dc1393e 100644--- a/litellm/proxy/guardrails/guardrail_initializers.py+++ b/litellm/proxy/guardrails/guardrail_initializers.py@@ -1,5 +1,6 @@# litellm/proxy/guardrails/guardrail_initializers.pyimport litellm+from litellm.proxy._types import CommonProxyErrorsfrom litellm.types.guardrails import *@@ -131,9 +132,15 @@ def initialize_presidio(litellm_params: LitellmParams, guardrail: Guardrail):def initialize_hide_secrets(litellm_params: LitellmParams, guardrail: Guardrail):- from litellm_enterprise.enterprise_callbacks.secret_detection import (- _ENTERPRISE_SecretDetection,- )+ try:+ from litellm_enterprise.enterprise_callbacks.secret_detection import (+ _ENTERPRISE_SecretDetection,+ )+ except ImportError:+ raise Exception(+ "Trying to use Secret Detection"+ + CommonProxyErrors.missing_enterprise_package.value+ )_secret_detection_object = _ENTERPRISE_SecretDetection(detect_secrets_config=litellm_params.detect_secrets_config,diff --git a/litellm/proxy/hooks/key_management_event_hooks.py b/litellm/proxy/hooks/key_management_event_hooks.pyindex dad1cf3910c..0289a929613 100644--- a/litellm/proxy/hooks/key_management_event_hooks.py+++ b/litellm/proxy/hooks/key_management_event_hooks.py@@ -7,6 +7,7 @@ from typing import Any, List, Optionalimport litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy._types import (+ CommonProxyErrors,GenerateKeyRequest,GenerateKeyResponse,KeyRequest,@@ -309,14 +310,27 @@ class KeyManagementEventHooks:@staticmethodasync def _send_key_created_email(response: dict):- from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (- BaseEmailLogger,- )+ try:+ from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (+ BaseEmailLogger,+ )+ except ImportError:+ raise Exception(+ "Trying to use Email Hooks"+ + CommonProxyErrors.missing_enterprise_package.value+ )from litellm.proxy.proxy_server import general_settings, proxy_logging_obj- from litellm.types.enterprise.enterprise_callbacks.send_emails import (- SendKeyCreatedEmailEvent,- )++ try:+ from litellm_enterprise.types.enterprise_callbacks.send_emails import (+ SendKeyCreatedEmailEvent,+ )+ except ImportError:+ raise Exception(+ "Trying to use Email Hooks"+ + CommonProxyErrors.missing_enterprise_package.value+ )event = SendKeyCreatedEmailEvent(virtual_key=response.get("key", ""),diff --git a/litellm/proxy/hooks/user_management_event_hooks.py b/litellm/proxy/hooks/user_management_event_hooks.pyindex eb0b003d23b..cc33f63837c 100644--- a/litellm/proxy/hooks/user_management_event_hooks.py+++ b/litellm/proxy/hooks/user_management_event_hooks.py@@ -7,9 +7,6 @@ import uuidfrom datetime import datetime, timezonefrom typing import Optional-from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (- BaseEmailLogger,-)from pydantic import BaseModelimport litellm@@ -111,17 +108,29 @@ class UserManagementEventHooks:################################################################### V2 USER INVITATION EMAIL #########################################################################- initialized_email_loggers = (- litellm.logging_callback_manager.get_custom_loggers_for_type(- callback_type=BaseEmailLogger+ try:+ from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (+ BaseEmailLogger,)- )- if len(initialized_email_loggers) > 0:- for email_logger in initialized_email_loggers:- if isinstance(email_logger, BaseEmailLogger):- await email_logger.send_user_invitation_email(- event=event,- )++ use_enterprise_email_hooks = True+ except ImportError:+ verbose_proxy_logger.warning(+ "Defaulting to using Legacy Email Hooks."+ + CommonProxyErrors.missing_enterprise_package.value+ )+ use_enterprise_email_hooks = False++ if use_enterprise_email_hooks:+ initialized_email_loggers = litellm.logging_callback_manager.get_custom_loggers_for_type(+ callback_type=BaseEmailLogger # type: ignore+ )+ if len(initialized_email_loggers) > 0:+ for email_logger in initialized_email_loggers:+ if isinstance(email_logger, BaseEmailLogger): # type: ignore+ await email_logger.send_user_invitation_email( # type: ignore+ event=event,+ )################################################################### LEGACY V1 USER INVITATION EMAIL ################diff --git a/litellm/proxy/management_endpoints/customer_endpoints.py b/litellm/proxy/management_endpoints/customer_endpoints.pyindex b75e3644e1c..a0c090653df 100644--- a/litellm/proxy/management_endpoints/customer_endpoints.py+++ b/litellm/proxy/management_endpoints/customer_endpoints.py@@ -102,9 +102,18 @@ async def unblock_user(data: BlockUsers):}'```"""- from enterprise.enterprise_hooks.blocked_user_list import (- _ENTERPRISE_BlockedUserList,- )+ try:+ from enterprise.enterprise_hooks.blocked_user_list import (+ _ENTERPRISE_BlockedUserList,+ )+ except ImportError:+ raise HTTPException(+ status_code=400,+ detail={+ "error": "Blocked user check was never set. This call has no effect."+ + CommonProxyErrors.missing_enterprise_package_docker.value+ },+ )if (not any(isinstance(x, _ENTERPRISE_BlockedUserList) for x in litellm.callbacks)diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.pyindex 453d09a2002..49e2ae300e4 100644--- a/litellm/proxy/spend_tracking/spend_management_endpoints.py+++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py@@ -149,7 +149,13 @@ async def view_spend_tags(```"""- from enterprise.utils import get_spend_by_tags+ try:+ from enterprise.utils import get_spend_by_tags+ except ImportError:+ raise Exception(+ "Trying to use Spend by Tags"+ + CommonProxyErrors.missing_enterprise_package_docker.value+ )from litellm.proxy.proxy_server import prisma_clienttry:@@ -1655,12 +1661,10 @@ async def ui_view_spend_logs( # noqa: PLR0915),user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),status_filter: Optional[str] = fastapi.Query(- default=None,- description="Filter logs by status (e.g., success, failure)"+ default=None, description="Filter logs by status (e.g., success, failure)"),model: Optional[str] = fastapi.Query(- default=None,- description="Filter logs by model"+ default=None, description="Filter logs by model"),):"""@@ -2922,22 +2926,17 @@ async def ui_view_session_spend_logs(def _build_status_filter_condition(status_filter: Optional[str]) -> Dict[str, Any]:"""Helper function to build the status filter condition for database queries.-+Args:status_filter (Optional[str]): The status to filter by. Can be "success" or "failure".-+Returns:Dict[str, Any]: A dictionary containing the status filter condition."""if status_filter is None:return {}-+if status_filter == "success":- return {- "OR": [- {"status": {"equals": "success"}},- {"status": None}- ]- }+ return {"OR": [{"status": {"equals": "success"}}, {"status": None}]}else:return {"status": {"equals": status_filter}}diff --git a/tests/code_coverage_tests/check_unsafe_enterprise_import.py b/tests/code_coverage_tests/check_unsafe_enterprise_import.pynew file mode 100644index 00000000000..dee6b6eeb1c--- /dev/null+++ b/tests/code_coverage_tests/check_unsafe_enterprise_import.py@@ -0,0 +1,95 @@+import ast+import os++class EnterpriseImportFinder(ast.NodeVisitor):+ def __init__(self):+ self.unsafe_imports = []+ self.current_file = None+ self.in_try_block = False+ self.try_blocks = []++ def visit_Try(self, node):+ # Track that we're entering a try block+ self.in_try_block = True+ self.try_blocks.append(node)+ # Visit all nodes in the try block+ for item in node.body:+ self.visit(item)+ # Visit except blocks+ for handler in node.handlers:+ for item in handler.body:+ self.visit(item)+ # Visit else block if it exists+ for item in node.orelse:+ self.visit(item)+ # Visit finally block if it exists+ for item in node.finalbody:+ self.visit(item)+ # We're leaving the try block+ self.try_blocks.pop()+ self.in_try_block = len(self.try_blocks) > 0++ def visit_Import(self, node):+ # Check for direct imports of litellm_enterprise+ for name in node.names:+ if "litellm_enterprise" in name.name or "enterprise" in name.name:+ if not self.in_try_block:+ self.unsafe_imports.append({+ "file": self.current_file,+ "line": node.lineno,+ "import": name.name,+ "context": "direct import"+ })+ self.generic_visit(node)++ def visit_ImportFrom(self, node):+ # Check for from litellm_enterprise imports+ if node.module and ("litellm_enterprise" in node.module or "enterprise" in node.module):+ if not self.in_try_block:+ self.unsafe_imports.append({+ "file": self.current_file,+ "line": node.lineno,+ "import": f"from {node.module}",+ "context": "from import"+ })+ self.generic_visit(node)++def find_unsafe_enterprise_imports_in_file(file_path):+ with open(file_path, "r") as file:+ tree = ast.parse(file.read(), filename=file_path)+ finder = EnterpriseImportFinder()+ finder.current_file = file_path+ finder.visit(tree)+ return finder.unsafe_imports++def find_unsafe_enterprise_imports_in_directory(directory):+ unsafe_imports = []+ for root, _, files in os.walk(directory):+ for file in files:+ if file.endswith(".py"):+ file_path = os.path.join(root, file)+ imports = find_unsafe_enterprise_imports_in_file(file_path)+ if imports:+ unsafe_imports.extend(imports)+ return unsafe_imports++if __name__ == "__main__":+ # Check for unsafe enterprise imports in the litellm directory+ directory_path = "./litellm"+ unsafe_imports = find_unsafe_enterprise_imports_in_directory(directory_path)++ if unsafe_imports:+ print("🚨 UNSAFE ENTERPRISE IMPORTS FOUND (not in try-except blocks):")+ for imp in unsafe_imports:+ print(f"File: {imp['file']}")+ print(f"Line: {imp['line']}")+ print(f"Import: {imp['import']}")+ print(f"Context: {imp['context']}")+ print("---")++ # Raise exception to fail CI/CD+ raise Exception(+ "🚨 Unsafe enterprise imports found. All enterprise imports must be wrapped in try-except blocks."+ )+ else:+ print("✅ No unsafe enterprise imports found.")diff --git a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.pyindex d591a38dee5..71608065c88 100644--- a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py+++ b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py@@ -11,13 +11,13 @@ sys.path.insert(0, os.path.abspath("../../.."))from litellm_enterprise.enterprise_callbacks.send_emails.base_email import (BaseEmailLogger,)--from litellm.proxy._types import Litellm_EntityType, WebhookEvent-from litellm.types.enterprise.enterprise_callbacks.send_emails import (+from litellm_enterprise.types.enterprise_callbacks.send_emails import (EmailEvent,SendKeyCreatedEmailEvent,)+from litellm.proxy._types import Litellm_EntityType, WebhookEvent+@pytest.fixturedef base_email_logger():diff --git a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_endpoints.py b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_endpoints.pyindex 8169c457c24..d1e8f37184a 100644--- a/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_endpoints.py+++ b/tests/litellm/enterprise/enterprise_callbacks/send_emails/test_endpoints.py@@ -17,8 +17,7 @@ from litellm_enterprise.enterprise_callbacks.send_emails.endpoints import (router,update_event_settings,)--from litellm.types.enterprise.enterprise_callbacks.send_emails import (+from litellm_enterprise.types.enterprise_callbacks.send_emails import (DefaultEmailSettings,EmailEvent,EmailEventSettings,