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]

[Feat] Add Custom Secret Manager - Allow users to define and write a custom secret manager (#16297)

Ishaan Jaff630a746c84c8
diff --git a/cookbook/litellm_proxy_server/secret_manager/custom_secret_manager_config.yaml b/cookbook/litellm_proxy_server/secret_manager/custom_secret_manager_config.yaml
new file mode 100644
index 00000000000..3598a9b1b65
--- /dev/null
+++ b/cookbook/litellm_proxy_server/secret_manager/custom_secret_manager_config.yaml
@@ -0,0 +1,20 @@
+general_settings:
+ master_key: os.environ/LITELLM_MASTER_KEY
+ key_management_system: "custom"
+ key_management_settings:
+ custom_secret_manager: my_secret_manager.InMemorySecretManager
+ store_virtual_keys: true
+ prefix_for_stored_virtual_keys: "litellm/"
+ access_mode: "read_and_write"
+
+model_list:
+ - model_name: gpt-4
+ litellm_params:
+ model: openai/gpt-4
+ api_key: os.environ/OPENAI_API_KEY # Read from custom secret manager
+
+ - model_name: claude-3-5-sonnet
+ litellm_params:
+ model: anthropic/claude-3-5-sonnet-20241022
+ api_key: os.environ/ANTHROPIC_API_KEY # Read from custom secret manager
+
diff --git a/cookbook/litellm_proxy_server/secret_manager/my_secret_manager.py b/cookbook/litellm_proxy_server/secret_manager/my_secret_manager.py
new file mode 100644
index 00000000000..b3c1bf608e2
--- /dev/null
+++ b/cookbook/litellm_proxy_server/secret_manager/my_secret_manager.py
@@ -0,0 +1,79 @@
+"""
+Example custom secret manager for LiteLLM Proxy.
+
+This is a simple in-memory secret manager for testing purposes.
+In production, replace this with your actual secret management system.
+"""
+
+from typing import Optional, Union
+
+import httpx
+
+from litellm.integrations.custom_secret_manager import CustomSecretManager
+
+
+class InMemorySecretManager(CustomSecretManager):
+ def __init__(self):
+ super().__init__(secret_manager_name="in_memory_secrets")
+ # Store your secrets in memory
+ print("INITIALIZING CUSTOM SECRET MANAGER IN MEMORY")
+ self.secrets = {}
+ print("CUSTOM SECRET MANAGER IN MEMORY INITIALIZED")
+
+ async def async_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """Read secret asynchronously"""
+ print("READING SECRET ASYNCHRONOUSLY")
+ print("SECRET NAME: %s", secret_name)
+ print("SECRET: %s", self.secrets.get(secret_name))
+ return self.secrets.get(secret_name)
+
+ def sync_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """Read secret synchronously"""
+ from litellm._logging import verbose_proxy_logger
+
+ verbose_proxy_logger.info(f"CUSTOM SECRET MANAGER: LOOKING FOR SECRET: {secret_name}")
+ value = self.secrets.get(secret_name)
+ verbose_proxy_logger.info(f"CUSTOM SECRET MANAGER: READ SECRET: {value}")
+ return value
+
+ async def async_write_secret(
+ self,
+ secret_name: str,
+ secret_value: str,
+ description: Optional[str] = None,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ tags: Optional[Union[dict, list]] = None,
+ ) -> dict:
+ """Write a secret to the in-memory store"""
+ self.secrets[secret_name] = secret_value
+ print("ALL SECRETS=%s", self.secrets)
+ return {
+ "status": "success",
+ "secret_name": secret_name,
+ "description": description,
+ }
+
+ async def async_delete_secret(
+ self,
+ secret_name: str,
+ recovery_window_in_days: Optional[int] = 7,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> dict:
+ """Delete a secret from the in-memory store"""
+ if secret_name in self.secrets:
+ del self.secrets[secret_name]
+ return {"status": "deleted", "secret_name": secret_name}
+ return {"status": "not_found", "secret_name": secret_name}
+
diff --git a/docs/my-website/docs/secret_managers/custom_secret_manager.md b/docs/my-website/docs/secret_managers/custom_secret_manager.md
new file mode 100644
index 00000000000..c51eeeb0727
--- /dev/null
+++ b/docs/my-website/docs/secret_managers/custom_secret_manager.md
@@ -0,0 +1,252 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# Custom Secret Manager
+
+Integrate your custom secret management system with LiteLLM.
+
+## Quick Start
+
+### 1. Create Your Secret Manager Class
+
+Create a new file `my_secret_manager.py` with an in-memory secret store:
+
+```python showLineNumbers title="my_secret_manager.py"
+from typing import Optional, Union
+import httpx
+from litellm.integrations.custom_secret_manager import CustomSecretManager
+
+class InMemorySecretManager(CustomSecretManager):
+ def __init__(self):
+ super().__init__(secret_manager_name="in_memory_secrets")
+ # Store your secrets in memory
+ self.secrets = {
+ "OPENAI_API_KEY": "sk-...",
+ "ANTHROPIC_API_KEY": "sk-ant-...",
+ }
+
+ async def async_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """Read secret asynchronously"""
+ return self.secrets.get(secret_name)
+
+ def sync_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """Read secret synchronously"""
+ return self.secrets.get(secret_name)
+```
+
+### 2. Configure Proxy
+
+Reference your custom secret manager in `config.yaml`:
+
+```yaml showLineNumbers title="config.yaml"
+general_settings:
+ master_key: os.environ/LITELLM_MASTER_KEY
+ key_management_system: custom # 👈 KEY CHANGE
+ key_management_settings:
+ custom_secret_manager: my_secret_manager.InMemorySecretManager # 👈 KEY CHANGE
+
+model_list:
+ - model_name: gpt-4
+ litellm_params:
+ model: openai/gpt-4
+ api_key: os.environ/OPENAI_API_KEY # Read from custom secret manager
+```
+
+### 3. Start LiteLLM Proxy
+
+<Tabs>
+<TabItem value="docker" label="Docker">
+
+Mount your custom secret manager file on the container:
+
+```bash showLineNumbers
+docker run -d \
+ -p 4000:4000 \
+ -e LITELLM_MASTER_KEY=$LITELLM_MASTER_KEY \
+ --name litellm-proxy \
+ -v $(pwd)/config.yaml:/app/config.yaml \
+ -v $(pwd)/my_secret_manager.py:/app/my_secret_manager.py \
+ ghcr.io/berriai/litellm:main-latest \
+ --config /app/config.yaml \
+ --port 4000 \
+ --detailed_debug
+```
+
+</TabItem>
+
+<TabItem value="pip" label="Python Package">
+
+```bash
+litellm --config config.yaml --detailed_debug
+```
+
+</TabItem>
+</Tabs>
+
+## Configuration Options
+
+Customize secret manager behavior in your `config.yaml`:
+
+<Tabs>
+<TabItem value="read_only" label="Read Keys Only">
+
+```yaml showLineNumbers title="config.yaml"
+general_settings:
+ key_management_system: custom
+ key_management_settings:
+ custom_secret_manager: my_secret_manager.InMemorySecretManager
+ hosted_keys: ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"] # Only check these keys
+```
+
+</TabItem>
+
+<TabItem value="write_only" label="Store Virtual Keys">
+
+Store LiteLLM proxy virtual keys in your secret manager:
+
+```yaml showLineNumbers title="config.yaml"
+general_settings:
+ key_management_system: custom
+ key_management_settings:
+ custom_secret_manager: my_secret_manager.InMemorySecretManager
+ access_mode: "write_only"
+ store_virtual_keys: true
+ prefix_for_stored_virtual_keys: "litellm/"
+ description: "LiteLLM virtual key"
+ tags:
+ Environment: "Production"
+ Team: "AI"
+```
+
+</TabItem>
+
+<TabItem value="read_and_write" label="Read + Write">
+
+```yaml showLineNumbers title="config.yaml"
+general_settings:
+ key_management_system: custom
+ key_management_settings:
+ custom_secret_manager: my_secret_manager.InMemorySecretManager
+ access_mode: "read_and_write"
+ hosted_keys: ["OPENAI_API_KEY"]
+ store_virtual_keys: true
+ prefix_for_stored_virtual_keys: "litellm/"
+```
+
+</TabItem>
+</Tabs>
+
+### Available Settings
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `custom_secret_manager` | Path to your custom secret manager class | Required |
+| `access_mode` | `"read_only"`, `"write_only"`, or `"read_and_write"` | `"read_only"` |
+| `hosted_keys` | List of specific keys to check in secret manager | All keys |
+| `store_virtual_keys` | Store LiteLLM virtual keys in secret manager | `false` |
+| `prefix_for_stored_virtual_keys` | Prefix for stored virtual keys | `"litellm/"` |
+| `description` | Description for stored secrets | `None` |
+| `tags` | Tags to apply to stored secrets | `None` |
+
+## Required Methods
+
+Your custom secret manager **must** implement these two methods:
+
+### `async_read_secret()`
+
+```python showLineNumbers
+async def async_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+) -> Optional[str]:
+ """
+ Read a secret asynchronously.
+
+ Returns:
+ Secret value if found, None otherwise
+ """
+ pass
+```
+
+### `sync_read_secret()`
+
+```python showLineNumbers
+def sync_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+) -> Optional[str]:
+ """
+ Read a secret synchronously.
+
+ Returns:
+ Secret value if found, None otherwise
+ """
+ pass
+```
+
+## Optional Methods
+
+Implement these for additional functionality:
+
+### `async_write_secret()`
+
+```python showLineNumbers
+async def async_write_secret(
+ self,
+ secret_name: str,
+ secret_value: str,
+ description: Optional[str] = None,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ tags: Optional[Union[dict, list]] = None,
+) -> dict:
+ """Write a secret to your secret manager"""
+ pass
+```
+
+### `async_delete_secret()`
+
+```python showLineNumbers
+async def async_delete_secret(
+ self,
+ secret_name: str,
+ recovery_window_in_days: Optional[int] = 7,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+) -> dict:
+ """Delete a secret from your secret manager"""
+ pass
+```
+
+## Use Cases
+
+✅ Proprietary vault systems
+✅ Custom authentication (mTLS, OAuth)
+✅ Organization-specific security policies
+✅ Legacy secret storage systems
+✅ Multi-region secret replication
+✅ Secret versioning and rotation
+✅ Compliance requirements (HIPAA, SOC2)
+
+## Example
+
+See [cookbook/litellm_proxy_server/secret_manager/my_secret_manager.py](https://github.com/BerriAI/litellm/blob/main/cookbook/litellm_proxy_server/secret_manager/my_secret_manager.py) for a complete working example with:
+
+- In-memory secret manager implementation
+- Integration with LiteLLM Proxy
+- Read, write, and delete operations
+
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index f7482799668..0b303b8c6af 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -259,6 +259,7 @@ const sidebars = {
"secret_managers/google_secret_manager",
"secret_managers/google_kms",
"secret_managers/hashicorp_vault",
+ "secret_managers/custom_secret_manager",
"oidc"
]
},
diff --git a/litellm/integrations/custom_secret_manager.py b/litellm/integrations/custom_secret_manager.py
new file mode 100644
index 00000000000..2125aef2200
--- /dev/null
+++ b/litellm/integrations/custom_secret_manager.py
@@ -0,0 +1,254 @@
+"""
+Custom Secret Manager Integration
+
+This module provides a base class for implementing custom secret managers in LiteLLM.
+
+Usage:
+ from litellm.integrations.custom_secret_manager import CustomSecretManager
+
+ class MySecretManager(CustomSecretManager):
+ def __init__(self):
+ super().__init__(secret_manager_name="my_secret_manager")
+
+ async def async_read_secret(
+ self,
+ secret_name: str,
+ optional_params=None,
+ timeout=None,
+ ):
+ # Your implementation here
+ return await self._fetch_secret_from_service(secret_name)
+
+ def sync_read_secret(
+ self,
+ secret_name: str,
+ optional_params=None,
+ timeout=None,
+ ):
+ # Your implementation here
+ return self._fetch_secret_from_service_sync(secret_name)
+
+ # Set your custom secret manager
+ import litellm
+ from litellm.types.secret_managers.main import KeyManagementSystem
+
+ litellm.secret_manager_client = MySecretManager()
+ litellm._key_management_system = KeyManagementSystem.CUSTOM
+"""
+
+from abc import abstractmethod
+from typing import Any, Dict, Optional, Union
+
+import httpx
+
+from litellm._logging import verbose_logger
+from litellm.secret_managers.base_secret_manager import BaseSecretManager
+
+
+class CustomSecretManager(BaseSecretManager):
+ """
+ Base class for implementing custom secret managers.
+
+ This class provides a standard interface for implementing custom secret management
+ integrations in LiteLLM. Users can extend this class to integrate their own secret
+ management systems.
+
+ Example:
+ ```python
+ from litellm.integrations.custom_secret_manager import CustomSecretManager
+
+ class MyVaultSecretManager(CustomSecretManager):
+ def __init__(self, vault_url: str, token: str):
+ super().__init__(secret_manager_name="my_vault")
+ self.vault_url = vault_url
+ self.token = token
+
+ async def async_read_secret(self, secret_name: str, optional_params=None, timeout=None):
+ # Implementation for reading secrets from your vault
+ async with httpx.AsyncClient() as client:
+ response = await client.get(
+ f"{self.vault_url}/v1/secret/{secret_name}",
+ headers={"X-Vault-Token": self.token},
+ timeout=timeout
+ )
+ return response.json()["data"]["value"]
+
+ def sync_read_secret(self, secret_name: str, optional_params=None, timeout=None):
+ # Sync implementation
+ with httpx.Client() as client:
+ response = client.get(
+ f"{self.vault_url}/v1/secret/{secret_name}",
+ headers={"X-Vault-Token": self.token},
+ timeout=timeout
+ )
+ return response.json()["data"]["value"]
+ ```
+ """
+
+ def __init__(
+ self,
+ secret_manager_name: Optional[str] = None,
+ **kwargs,
+ ):
+ """
+ Initialize the CustomSecretManager.
+
+ Args:
+ secret_manager_name: A descriptive name for your secret manager.
+ This is used for logging and debugging purposes.
+ **kwargs: Additional keyword arguments to pass to your secret manager.
+ """
+ super().__init__()
+ self.secret_manager_name = secret_manager_name or "custom_secret_manager"
+ verbose_logger.info(
+ "Initialized custom secret manager"
+ )
+
+ @abstractmethod
+ async def async_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """
+ Asynchronously read a secret from your custom secret manager.
+
+ Args:
+ secret_name: Name/path of the secret to read
+ optional_params: Additional parameters specific to your secret manager
+ timeout: Request timeout
+
+ Returns:
+ The secret value if found, None otherwise
+
+ Raises:
+ Exception: If there's an error reading the secret
+ """
+ pass
+
+ @abstractmethod
+ def sync_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """
+ Synchronously read a secret from your custom secret manager.
+
+ Args:
+ secret_name: Name/path of the secret to read
+ optional_params: Additional parameters specific to your secret manager
+ timeout: Request timeout
+
+ Returns:
+ The secret value if found, None otherwise
+
+ Raises:
+ Exception: If there's an error reading the secret
+ """
+ pass
+
+ async def async_write_secret(
+ self,
+ secret_name: str,
+ secret_value: str,
+ description: Optional[str] = None,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ tags: Optional[Union[dict, list]] = None,
+ ) -> Dict[str, Any]:
+ """
+ Asynchronously write a secret to your custom secret manager.
+
+ This is optional to implement. If your secret manager supports writing secrets,
+ you can override this method.
+
+ Args:
+ secret_name: Name/path of the secret to write
+ secret_value: Value to store
+ description: Description of the secret
+ optional_params: Additional parameters specific to your secret manager
+ timeout: Request timeout
+ tags: Optional tags to apply to the secret
+
+ Returns:
+ Response from the secret manager containing write operation details
+
+ Raises:
+ NotImplementedError: If write operations are not supported
+ """
+ raise NotImplementedError(
+ f"Write operations are not implemented for {self.secret_manager_name}. "
+ "Override async_write_secret() to add write support."
+ )
+
+ async def async_delete_secret(
+ self,
+ secret_name: str,
+ recovery_window_in_days: Optional[int] = 7,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> dict:
+ """
+ Asynchronously delete a secret from your custom secret manager.
+
+ This is optional to implement. If your secret manager supports deleting secrets,
+ you can override this method.
+
+ Args:
+ secret_name: Name of the secret to delete
+ recovery_window_in_days: Number of days before permanent deletion (if supported)
+ optional_params: Additional parameters specific to your secret manager
+ timeout: Request timeout
+
+ Returns:
+ Response from the secret manager containing deletion details
+
+ Raises:
+ NotImplementedError: If delete operations are not supported
+ """
+ raise NotImplementedError(
+ f"Delete operations are not implemented for {self.secret_manager_name}. "
+ "Override async_delete_secret() to add delete support."
+ )
+
+ def validate_environment(self) -> bool:
+ """
+ Validate that all required environment variables and configuration are present.
+
+ Override this method to validate your secret manager's configuration.
+
+ Returns:
+ True if the environment is valid
+
+ Raises:
+ ValueError: If required configuration is missing
+ """
+ verbose_logger.debug(
+ "No environment validation configured for custom secret manager"
+ )
+ return True
+
+ async def async_health_check(
+ self, timeout: Optional[Union[float, httpx.Timeout]] = None
+ ) -> bool:
+ """
+ Perform a health check on your secret manager.
+
+ This is optional to implement. Override this method to add health check support.
+
+ Args:
+ timeout: Request timeout
+
+ Returns:
+ True if the secret manager is healthy, False otherwise
+ """
+ verbose_logger.debug(
+ f"Health check not implemented for {self.secret_manager_name}"
+ )
+ return True
+
+ def __repr__(self) -> str:
+ return f"<{self.__class__.__name__}(name={self.secret_manager_name})>"
diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.py
index 21e2c54ec74..28ddb9d4b01 100644
--- a/litellm/proxy/proxy_cli.py
+++ b/litellm/proxy/proxy_cli.py
@@ -683,12 +683,7 @@ def run_server( # noqa: PLR0915
general_settings = _config.get("general_settings", {})
if general_settings is None:
general_settings = {}
- if general_settings:
- ### LOAD SECRET MANAGER ###
- key_management_system = general_settings.get(
- "key_management_system", None
- )
- proxy_config.initialize_secret_manager(key_management_system)
+ ### LOAD KEY MANAGEMENT SETTINGS FIRST (needed for custom secret manager) ###
key_management_settings = general_settings.get(
"key_management_settings", None
)
@@ -698,6 +693,16 @@ def run_server( # noqa: PLR0915
litellm._key_management_settings = KeyManagementSettings(
**key_management_settings
)
+
+ if general_settings:
+ ### LOAD SECRET MANAGER ###
+ key_management_system = general_settings.get(
+ "key_management_system", None
+ )
+ proxy_config.initialize_secret_manager(
+ key_management_system=key_management_system,
+ config_file_path=config
+ )
database_url = general_settings.get("database_url", None)
if database_url is None and os.getenv("DATABASE_URL") is None:
# Use helper function to construct DATABASE_URL from individual variables
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index a437cb705be..f62fec176b4 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -2281,9 +2281,7 @@ class ProxyConfig:
if general_settings is None:
general_settings = {}
if general_settings:
- ### LOAD SECRET MANAGER ###
- key_management_system = general_settings.get("key_management_system", None)
- self.initialize_secret_manager(key_management_system=key_management_system)
+ ### LOAD KEY MANAGEMENT SETTINGS FIRST (needed for custom secret manager) ###
key_management_settings = general_settings.get(
"key_management_settings", None
)
@@ -2291,6 +2289,13 @@ class ProxyConfig:
litellm._key_management_settings = KeyManagementSettings(
**key_management_settings
)
+
+ ### LOAD SECRET MANAGER ###
+ key_management_system = general_settings.get("key_management_system", None)
+ self.initialize_secret_manager(
+ key_management_system=key_management_system,
+ config_file_path=config_file_path
+ )
### [DEPRECATED] LOAD FROM GOOGLE KMS ### old way of loading from google kms
use_google_kms = general_settings.get("use_google_kms", False)
load_google_kms(use_google_kms=use_google_kms)
@@ -2622,7 +2627,9 @@ class ProxyConfig:
litellm.logging_callback_manager.add_litellm_callback(_logger)
pass
- def initialize_secret_manager(self, key_management_system: Optional[str]):
+ def initialize_secret_manager(
+ self, key_management_system: Optional[str], config_file_path: Optional[str] = None
+ ):
"""
Initialize the relevant secret manager if `key_management_system` is provided
"""
@@ -2664,6 +2671,13 @@ class ProxyConfig:
)
CyberArkSecretManager()
+ elif key_management_system == KeyManagementSystem.CUSTOM.value:
+ ### LOAD CUSTOM SECRET MANAGER ###
+ from litellm.secret_managers.custom_secret_manager_loader import (
+ load_custom_secret_manager,
+ )
+
+ load_custom_secret_manager(config_file_path=config_file_path)
else:
raise ValueError("Invalid Key Management System selected")
diff --git a/litellm/secret_managers/custom_secret_manager_loader.py b/litellm/secret_managers/custom_secret_manager_loader.py
new file mode 100644
index 00000000000..bbd0e78686f
--- /dev/null
+++ b/litellm/secret_managers/custom_secret_manager_loader.py
@@ -0,0 +1,94 @@
+"""
+Loader for custom secret managers.
+
+Handles dynamic loading of user-defined secret manager classes from Python files.
+"""
+
+import importlib.util
+import os
+from typing import Optional
+
+import litellm
+from litellm._logging import verbose_proxy_logger
+from litellm.integrations.custom_secret_manager import CustomSecretManager
+from litellm.types.secret_managers.main import KeyManagementSystem
+
+
+def load_custom_secret_manager(config_file_path: Optional[str] = None) -> None:
+ """
+ Load and initialize a custom secret manager from a python file.
+
+ Similar to how custom guardrails are loaded - loads the class from
+ the custom_secret_manager field in key_management_settings.
+
+ Args:
+ config_file_path: Path to the config.yaml file
+
+ Raises:
+ ValueError: If required configuration is missing
+ ImportError: If the custom secret manager module cannot be loaded
+ """
+
+ if not config_file_path:
+ raise ValueError(
+ "CustomSecretManagerException - config_file_path is required to load custom secret manager"
+ )
+
+ # Get the custom_secret_manager class path from settings
+ if litellm._key_management_settings is None:
+ raise ValueError(
+ "CustomSecretManagerException - key_management_settings is required with custom_secret_manager field"
+ )
+
+ custom_secret_manager_path = getattr(
+ litellm._key_management_settings, "custom_secret_manager", None
+ )
+
+ if not custom_secret_manager_path:
+ raise ValueError(
+ "CustomSecretManagerException - custom_secret_manager field is required in key_management_settings"
+ )
+
+ # Split into file_name and class_name (e.g., "my_secret_manager.InMemorySecretManager")
+ _file_name, _class_name = custom_secret_manager_path.split(".")
+ verbose_proxy_logger.debug(
+ "Initializing custom secret manager: %s, file_name: %s, class_name: %s",
+ custom_secret_manager_path,
+ _file_name,
+ _class_name,
+ )
+
+ # Load the module from the same directory as config.yaml
+ directory = os.path.dirname(config_file_path)
+ module_file_path = os.path.join(directory, _file_name) + ".py"
+
+ spec = importlib.util.spec_from_file_location(_class_name, module_file_path) # type: ignore
+ if not spec:
+ raise ImportError(
+ f"Could not find a module specification for {module_file_path}"
+ )
+
+ module = importlib.util.module_from_spec(spec) # type: ignore
+ spec.loader.exec_module(module) # type: ignore
+ _secret_manager_class = getattr(module, _class_name)
+
+ # Validate that it's a CustomSecretManager subclass
+ if not issubclass(_secret_manager_class, CustomSecretManager):
+ raise TypeError(
+ f"CustomSecretManagerException - {_class_name} must be a subclass of CustomSecretManager"
+ )
+
+ # Instantiate the custom secret manager
+ _secret_manager_instance = _secret_manager_class()
+
+ # Set it as the secret manager client
+ litellm.secret_manager_client = _secret_manager_instance
+
+ # Set the key management system to CUSTOM so get_secret knows to use it
+ litellm._key_management_system = KeyManagementSystem.CUSTOM
+
+ verbose_proxy_logger.info(
+ "Successfully initialized custom secret manager: %s",
+ custom_secret_manager_path,
+ )
+
diff --git a/litellm/secret_managers/secret_manager_handler.py b/litellm/secret_managers/secret_manager_handler.py
index fd991296ef6..b93503a8649 100644
--- a/litellm/secret_managers/secret_manager_handler.py
+++ b/litellm/secret_managers/secret_manager_handler.py
@@ -140,6 +140,22 @@ def get_secret_from_manager( # noqa: PLR0915
print_verbose(f"An error occurred - {str(e)}")
raise e
+ elif key_manager == KeyManagementSystem.CUSTOM.value:
+ # Check if client is a CustomSecretManager instance
+ from litellm.integrations.custom_secret_manager import CustomSecretManager
+
+ if isinstance(client, CustomSecretManager):
+ secret = client.sync_read_secret(
+ secret_name=secret_name,
+ optional_params=key_management_settings.model_dump() if key_management_settings else None,
+ )
+ if secret is None:
+ raise ValueError(f"No secret found in Custom Secret Manager for {secret_name}")
+ else:
+ raise ValueError(
+ f"Custom secret manager client must be an instance of CustomSecretManager, got {type(client).__name__}"
+ )
+
elif key_manager == "local":
secret = os.getenv(secret_name)
diff --git a/litellm/types/secret_managers/main.py b/litellm/types/secret_managers/main.py
index dbedb48843e..8d7aa764d69 100644
--- a/litellm/types/secret_managers/main.py
+++ b/litellm/types/secret_managers/main.py
@@ -13,6 +13,7 @@ class KeyManagementSystem(enum.Enum):
CYBERARK = "cyberark"
LOCAL = "local"
AWS_KMS = "aws_kms"
+ CUSTOM = "custom"
class KeyManagementSettings(LiteLLMPydanticObjectBase):
@@ -41,6 +42,11 @@ class KeyManagementSettings(LiteLLMPydanticObjectBase):
description: Optional[str] = None
"""Optional description attached when creating secrets (visible in AWS console)."""
-
tags: Optional[Dict[str, str]] = None
- """Optional tags to attach when creating secrets (e.g. {"Environment": "Prod", "Owner": "AI-Platform"})."""
\ No newline at end of file
+ """Optional tags to attach when creating secrets (e.g. {"Environment": "Prod", "Owner": "AI-Platform"})."""
+
+ custom_secret_manager: Optional[str] = None
+ """
+ Path to custom secret manager class (e.g. "my_secret_manager.InMemorySecretManager")
+ Required when key_management_system is "custom"
+ """
\ No newline at end of file
diff --git a/tests/test_litellm/secret_managers/test_custom_secret_manager.py b/tests/test_litellm/secret_managers/test_custom_secret_manager.py
new file mode 100644
index 00000000000..3314dbfb0ac
--- /dev/null
+++ b/tests/test_litellm/secret_managers/test_custom_secret_manager.py
@@ -0,0 +1,259 @@
+"""
+Test custom secret manager implementation
+"""
+
+import os
+import sys
+from typing import Optional, Union
+
+import httpx
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../..")
+) # Adds the parent directory to the system path
+
+import litellm
+from litellm.integrations.custom_secret_manager import CustomSecretManager
+from litellm.types.secret_managers.main import KeyManagementSystem
+
+
+class TestCustomSecretManager(CustomSecretManager):
+ """
+ Test implementation of a custom secret manager.
+
+ This simulates a simple in-memory secret store for testing purposes.
+ """
+
+ def __init__(self, secrets: Optional[dict] = None):
+ super().__init__(secret_manager_name="test_custom_secret_manager")
+ self.secrets = secrets or {
+ "TEST_API_KEY": "test-api-key-12345",
+ "TEST_SECRET": "super-secret-value",
+ "OPENAI_API_KEY": "sk-test-openai-key",
+ }
+
+ async def async_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """
+ Read a secret from the in-memory store asynchronously.
+ """
+ return self.secrets.get(secret_name)
+
+ def sync_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """
+ Read a secret from the in-memory store synchronously.
+ """
+ return self.secrets.get(secret_name)
+
+ async def async_write_secret(
+ self,
+ secret_name: str,
+ secret_value: str,
+ description: Optional[str] = None,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ tags: Optional[Union[dict, list]] = None,
+ ) -> dict:
+ """
+ Write a secret to the in-memory store.
+ """
+ self.secrets[secret_name] = secret_value
+ return {
+ "secret_name": secret_name,
+ "status": "success",
+ "description": description,
+ }
+
+ async def async_delete_secret(
+ self,
+ secret_name: str,
+ recovery_window_in_days: Optional[int] = 7,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> dict:
+ """
+ Delete a secret from the in-memory store.
+ """
+ if secret_name in self.secrets:
+ del self.secrets[secret_name]
+ return {"secret_name": secret_name, "status": "deleted"}
+ return {"secret_name": secret_name, "status": "not_found"}
+
+
+def test_custom_secret_manager_initialization():
+ """
+ Test that a custom secret manager can be initialized correctly.
+ """
+ secret_manager = TestCustomSecretManager()
+ assert secret_manager.secret_manager_name == "test_custom_secret_manager"
+ assert "TEST_API_KEY" in secret_manager.secrets
+
+
+def test_custom_secret_manager_sync_read():
+ """
+ Test synchronous secret reading.
+ """
+ secret_manager = TestCustomSecretManager()
+
+ # Test reading an existing secret
+ api_key = secret_manager.sync_read_secret("TEST_API_KEY")
+ assert api_key == "test-api-key-12345"
+
+ # Test reading a non-existent secret
+ missing_key = secret_manager.sync_read_secret("NON_EXISTENT_KEY")
+ assert missing_key is None
+
+
+async def test_custom_secret_manager_async_read():
+ """
+ Test asynchronous secret reading.
+ """
+ secret_manager = TestCustomSecretManager()
+
+ # Test reading an existing secret
+ api_key = await secret_manager.async_read_secret("TEST_SECRET")
+ assert api_key == "super-secret-value"
+
+ # Test reading a non-existent secret
+ missing_key = await secret_manager.async_read_secret("NON_EXISTENT_KEY")
+ assert missing_key is None
+
+
+async def test_custom_secret_manager_async_write():
+ """
+ Test asynchronous secret writing.
+ """
+ secret_manager = TestCustomSecretManager()
+
+ # Write a new secret
+ result = await secret_manager.async_write_secret(
+ secret_name="NEW_SECRET",
+ secret_value="new-secret-value",
+ description="A new test secret",
+ )
+
+ assert result["status"] == "success"
+ assert result["secret_name"] == "NEW_SECRET"
+
+ # Verify the secret was written
+ secret_value = secret_manager.sync_read_secret("NEW_SECRET")
+ assert secret_value == "new-secret-value"
+
+
+async def test_custom_secret_manager_async_delete():
+ """
+ Test asynchronous secret deletion.
+ """
+ secret_manager = TestCustomSecretManager()
+
+ # Verify secret exists
+ assert secret_manager.sync_read_secret("TEST_API_KEY") is not None
+
+ # Delete the secret
+ result = await secret_manager.async_delete_secret("TEST_API_KEY")
+ assert result["status"] == "deleted"
+
+ # Verify secret is deleted
+ assert secret_manager.sync_read_secret("TEST_API_KEY") is None
+
+
+def test_custom_secret_manager_integration_with_litellm():
+ """
+ Test that the custom secret manager integrates with LiteLLM's secret management system.
+ """
+ # Create and set the custom secret manager
+ secret_manager = TestCustomSecretManager()
+ litellm.secret_manager_client = secret_manager
+ litellm._key_management_system = KeyManagementSystem.CUSTOM
+
+ # Set access mode to enable secret reading
+ from litellm.types.secret_managers.main import KeyManagementSettings
+ litellm._key_management_settings = KeyManagementSettings(
+ access_mode="read_only"
+ )
+
+ try:
+ # Test getting a secret through LiteLLM's get_secret function
+ from litellm.secret_managers.main import get_secret
+
+ api_key = get_secret("TEST_API_KEY")
+ assert api_key == "test-api-key-12345"
+
+ openai_key = get_secret("OPENAI_API_KEY")
+ assert openai_key == "sk-test-openai-key"
+
+ finally:
+ # Clean up
+ litellm.secret_manager_client = None
+ litellm._key_management_system = None
+ litellm._key_management_settings = None
+
+
+
+class MinimalCustomSecretManager(CustomSecretManager):
+ """
+ Minimal implementation that only implements required methods.
+ """
+
+ def __init__(self):
+ super().__init__(secret_manager_name="minimal_custom")
+
+ async def async_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """
+ Minimal async read implementation.
+ """
+ return f"async-{secret_name}-value"
+
+ def sync_read_secret(
+ self,
+ secret_name: str,
+ optional_params: Optional[dict] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ ) -> Optional[str]:
+ """
+ Minimal sync read implementation.
+ """
+ return f"sync-{secret_name}-value"
+
+
+def test_minimal_custom_secret_manager():
+ """
+ Test that a minimal implementation without write/delete methods works.
+ """
+ secret_manager = MinimalCustomSecretManager()
+
+ # Read should work
+ value = secret_manager.sync_read_secret("TEST_KEY")
+ assert value == "sync-TEST_KEY-value"
+
+ # Write should raise NotImplementedError
+ with pytest.raises(NotImplementedError) as exc_info:
+ import asyncio
+ asyncio.run(secret_manager.async_write_secret("KEY", "value"))
+
+ assert "Write operations are not implemented" in str(exc_info.value)
+
+ # Delete should raise NotImplementedError
+ with pytest.raises(NotImplementedError) as exc_info:
+ import asyncio
+ asyncio.run(secret_manager.async_delete_secret("KEY"))
+
+ assert "Delete operations are not implemented" in str(exc_info.value)