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): initialize the secret manager before resolving os.environ config references (#37544)
Yassin Kortamf22eeb2ce054
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 5adee476f33..0f39ef2e18e 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -639,6 +639,7 @@ from litellm.secret_managers.main import (get_secret_bool,get_secret_str,normalize_nonempty_secret_str,+ secret_manager_would_be_consulted,str_to_bool,)from litellm.types.integrations.slack_alerting import AlertType, SlackAlertingArgs@@ -4380,9 +4381,55 @@ class ProxyConfig:item = self._check_for_os_environ_vars(config=item, depth=depth + 1, max_depth=max_depth)# if the value is a string and starts with "os.environ/" - then it's an environment variableelif isinstance(value, str) and value.startswith("os.environ/"):- config[key] = get_secret(value)+ resolved = get_secret(value)+ if resolved is None and secret_manager_would_be_consulted(value):+ verbose_proxy_logger.warning("%s is absent from the configured secret manager", value)+ config[key] = resolvedreturn config+ def _initialize_secret_manager_from_raw_config(+ self, config: Mapping[str, object], config_file_path: str | None+ ) -> None:+ """+ Bring the secret manager up before `os.environ/<KEY>` references are resolved.++ `_check_for_os_environ_vars` writes whatever it resolves back into the config, so a key+ held only by the secret manager would otherwise become a permanent `None` that the later+ fallbacks in `load_config` can no longer recover from.++ `get_config` also runs on management-endpoint request paths, so this returns early once a+ manager exists rather than rebuilding the client on every request.++ The manager's own settings can only come from real environment variables, so they are+ resolved against a throwaway copy and the config is left untouched for the main pass.+ """+ if litellm.secret_manager_client is not None:+ return++ general_settings: Final = config.get("general_settings")+ if not isinstance(general_settings, dict):+ return++ raw_system: Final = general_settings.get("key_management_system")+ key_management_system: Final = (+ get_secret(raw_system)+ if isinstance(raw_system, str) and raw_system.startswith("os.environ/")+ else raw_system+ )+ if not isinstance(key_management_system, str):+ return++ raw_settings: Final = general_settings.get("key_management_settings")+ if isinstance(raw_settings, dict):+ litellm._key_management_settings = KeyManagementSettings(+ **self._check_for_os_environ_vars(config=copy.deepcopy(raw_settings))+ )++ self.initialize_secret_manager(+ key_management_system=key_management_system,+ config_file_path=config_file_path,+ )+def _get_team_config(self, team_id: str, all_teams_config: list[dict]) -> dict:team_config: dict = {}for team in all_teams_config:@@ -4553,6 +4600,8 @@ class ProxyConfig:printed_yaml: Final = copy.deepcopy(config)printed_yaml.pop("environment_variables", None)+ self._initialize_secret_manager_from_raw_config(config=config, config_file_path=config_file_path)+config = self._check_for_os_environ_vars(config=config)self.update_config_state(config=config)@@ -5123,17 +5172,14 @@ class ProxyConfig:key: general_settings[key] for key in SPEND_LOG_CLEANUP_BOUND_SETTINGS if key in general_settings}- ### LOAD KEY MANAGEMENT SETTINGS FIRST (needed for custom secret manager) ###+ ### LOAD KEY MANAGEMENT SETTINGS ###+ # The secret manager itself is brought up by get_config(), which runs before the+ # `os.environ/` references in this config were resolved. Re-reading the settings here+ # picks up any of them that were themselves secret-manager backed.key_management_settings: Final = general_settings.get("key_management_settings", None)if key_management_settings is not None:litellm._key_management_settings = KeyManagementSettings(**key_management_settings)- ### LOAD SECRET MANAGER ###- key_management_system: Final = 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 kmsuse_google_kms: Final = general_settings.get("use_google_kms", False)load_google_kms(use_google_kms=use_google_kms)diff --git a/litellm/proxy/read_model_list.py b/litellm/proxy/read_model_list.pyindex cdd6680aa40..a1830e7f2bc 100644--- a/litellm/proxy/read_model_list.py+++ b/litellm/proxy/read_model_list.py@@ -9,7 +9,8 @@ effects.Instead we reuse ``ProxyConfig.get_config`` — the actual config reader — so thegateway inherits the same heavy lifting the proxy does: ``include:`` merging,``os.environ/`` + secret-manager resolution, and DB-stored models (when a DB is-configured). It has no proxy-setup side effects. Returns the resolved+configured). Its only proxy-setup side effect is bringing up the configured+secret manager, which is what makes that resolution work. Returns the resolved``model_list``; the Rust side deserializes each entry into its ``Deployment``."""diff --git a/litellm/secret_managers/main.py b/litellm/secret_managers/main.pyindex d1e4b3bb2ce..e89fbbdab65 100644--- a/litellm/secret_managers/main.py+++ b/litellm/secret_managers/main.py@@ -365,6 +365,22 @@ def get_secret(raise e+def secret_manager_would_be_consulted(secret_name: str) -> bool:+ """+ Returns True if a `get_secret` read for `secret_name` would actually reach the hosted manager.++ Mirrors the gating `get_secret` applies below: the manager has to be up and readable, and+ `hosted_keys`, when set, is an allowlist of the names it is consulted for. Callers use this to+ tell "the manager does not have this key" apart from "the manager was never asked".+ """+ if not _should_read_secret_from_secret_manager():+ return False+ key_management_settings: Final = litellm._key_management_settings+ if key_management_settings is None or key_management_settings.hosted_keys is None:+ return True+ return secret_name.removeprefix("os.environ/") in key_management_settings.hosted_keys++def _should_read_secret_from_secret_manager() -> bool:"""Returns True if the secret manager should be used to read the secret, False otherwise@@ -373,11 +389,7 @@ def _should_read_secret_from_secret_manager() -> bool:- If the `_key_management_settings` access mode is "read_only" or "read_and_write", return True- Otherwise, return False"""- if litellm.secret_manager_client is not None:- if litellm._key_management_settings is not None:- if (- litellm._key_management_settings.access_mode == "read_only"- or litellm._key_management_settings.access_mode == "read_and_write"- ):- return True- return False+ key_management_settings: Final = litellm._key_management_settings+ if litellm.secret_manager_client is None or key_management_settings is None:+ return False+ return key_management_settings.access_mode in ("read_only", "read_and_write")diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.pyindex 37a03617a65..58465772b3b 100644--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py@@ -769,6 +769,214 @@ async def test_ProxyConfig_get_config_missing_file_raises(monkeypatch):await pc.get_config(config_file_path="/no/such/path.yaml")+# ---------------------------------------------------------------------------+# ProxyConfig._initialize_secret_manager_from_raw_config+# ---------------------------------------------------------------------------++VAULT_SECRET_MANAGER_MODULE = '''+import os++from litellm.integrations.custom_secret_manager import CustomSecretManager++VAULT = {"LITELLM_MASTER_KEY": "master-from-vault", "MY_PROVIDER_KEY": "provider-from-vault"}+++class VaultSecretManager(CustomSecretManager):+ def __init__(self):+ super().__init__()+ # The loader re-executes this module on every construction, so an in-module counter+ # would reset. Append to a file instead, to count constructions across the whole load.+ with open(os.environ["VAULT_CONSTRUCTION_LOG"], "a") as f:+ f.write("constructed\\n")++ def sync_read_secret(self, secret_name, optional_params=None, timeout=None, **kwargs):+ return VAULT.get(secret_name)++ async def async_read_secret(self, secret_name, optional_params=None, timeout=None, **kwargs):+ return VAULT.get(secret_name)+'''++VAULT_BACKED_CONFIG = """+model_list:+ - model_name: my-model+ litellm_params:+ model: openai/gpt-4o-mini+ api_key: os.environ/MY_PROVIDER_KEY++general_settings:+ master_key: os.environ/LITELLM_MASTER_KEY+ key_management_system: custom+ key_management_settings:+ custom_secret_manager: vault_secret_manager.VaultSecretManager+ hosted_keys:+ - LITELLM_MASTER_KEY+ - MY_PROVIDER_KEY+"""+++def _write_vault_backed_config(tmp_path, monkeypatch, config_yaml: str) -> str:+ """Write a config whose secrets live only in a custom secret manager, never in the env."""+ (tmp_path / "vault_secret_manager.py").write_text(VAULT_SECRET_MANAGER_MODULE)+ config_file = tmp_path / "c.yaml"+ config_file.write_text(config_yaml)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", False)+ monkeypatch.delenv("LITELLM_CONFIG_BUCKET_NAME", raising=False)+ monkeypatch.delenv("LITELLM_MASTER_KEY", raising=False)+ monkeypatch.delenv("MY_PROVIDER_KEY", raising=False)+ monkeypatch.setenv("VAULT_CONSTRUCTION_LOG", str(tmp_path / "constructions.log"))+ monkeypatch.setattr(litellm, "secret_manager_client", None)+ return str(config_file)+++def _construction_count(tmp_path) -> int:+ log = tmp_path / "constructions.log"+ return len(log.read_text().splitlines()) if log.exists() else 0+++async def test_ProxyConfig_get_config_resolves_keys_held_only_by_the_secret_manager(tmp_path, monkeypatch):+ """Regression for GH #35239.++ get_config() used to resolve every ``os.environ/<KEY>`` reference and write the result+ back into the config before the secret manager was initialized, so any key that lived+ only in the manager became a permanent ``None``.+ """+ config_file_path = _write_vault_backed_config(tmp_path, monkeypatch, VAULT_BACKED_CONFIG)++ cfg = await ProxyConfig().get_config(config_file_path=config_file_path)++ assert {+ "master_key": cfg["general_settings"]["master_key"],+ "api_key": cfg["model_list"][0]["litellm_params"]["api_key"],+ "hosted_keys": litellm._key_management_settings.hosted_keys,+ } == {+ "master_key": "master-from-vault",+ "api_key": "provider-from-vault",+ "hosted_keys": ["LITELLM_MASTER_KEY", "MY_PROVIDER_KEY"],+ }+++async def test_ProxyConfig_load_config_builds_the_secret_manager_exactly_once(tmp_path, monkeypatch):+ """The full startup path must not build the manager, then throw it away and build another.++ A discarded client costs a Vault/CyberArk re-auth and leaks a gRPC channel on Google KMS.+ """+ config_file_path = _write_vault_backed_config(tmp_path, monkeypatch, VAULT_BACKED_CONFIG)++ _router, _model_list, general_settings = await ProxyConfig().load_config(+ router=None, config_file_path=config_file_path+ )++ assert {+ "constructions": _construction_count(tmp_path),+ "master_key": general_settings["master_key"],+ } == {"constructions": 1, "master_key": "master-from-vault"}+++async def test_ProxyConfig_get_config_reuses_an_already_initialized_secret_manager(tmp_path, monkeypatch):+ """get_config() also runs on management-endpoint request paths.++ Rebuilding the client on every call would re-execute the custom manager module, drop the+ Vault/CyberArk token caches, and leak a gRPC channel per request on Google KMS.+ """+ config_file_path = _write_vault_backed_config(tmp_path, monkeypatch, VAULT_BACKED_CONFIG)++ await ProxyConfig().get_config(config_file_path=config_file_path)+ first_client = litellm.secret_manager_client+ second = await ProxyConfig().get_config(config_file_path=config_file_path)++ assert {+ "client_reused": litellm.secret_manager_client is first_client,+ "master_key": second["general_settings"]["master_key"],+ } == {"client_reused": True, "master_key": "master-from-vault"}+++async def test_ProxyConfig_get_config_without_key_management_system_leaves_secret_manager_unset(+ tmp_path, monkeypatch+):+ """No ``key_management_system`` means no manager, an unresolvable reference stays None, and+ nothing is warned about: with no manager there is nothing to have been absent from."""+ config_yaml = VAULT_BACKED_CONFIG.replace(" key_management_system: custom\n", "")+ config_file_path = _write_vault_backed_config(tmp_path, monkeypatch, config_yaml)+ warn = MagicMock()+ monkeypatch.setattr("litellm.proxy.proxy_server.verbose_proxy_logger.warning", warn)++ cfg = await ProxyConfig().get_config(config_file_path=config_file_path)++ assert {+ "master_key": cfg["general_settings"]["master_key"],+ "api_key": cfg["model_list"][0]["litellm_params"]["api_key"],+ "client": litellm.secret_manager_client,+ "warned_about": [call.args[1] for call in warn.call_args_list],+ } == {"master_key": None, "api_key": None, "client": None, "warned_about": []}+++async def test_ProxyConfig_get_config_warns_when_a_reference_is_missing_from_the_secret_manager(+ tmp_path, monkeypatch+):+ """A reference the manager cannot resolve is logged, instead of silently becoming None."""+ config_yaml = VAULT_BACKED_CONFIG.replace("MY_PROVIDER_KEY", "NOT_IN_VAULT")+ config_file_path = _write_vault_backed_config(tmp_path, monkeypatch, config_yaml)+ warn = MagicMock()+ monkeypatch.setattr("litellm.proxy.proxy_server.verbose_proxy_logger.warning", warn)++ cfg = await ProxyConfig().get_config(config_file_path=config_file_path)++ assert {+ "api_key": cfg["model_list"][0]["litellm_params"]["api_key"],+ "warned_about": [call.args[1] for call in warn.call_args_list],+ } == {"api_key": None, "warned_about": ["os.environ/NOT_IN_VAULT"]}+++async def test_ProxyConfig_get_config_does_not_warn_for_a_name_outside_hosted_keys(tmp_path, monkeypatch):+ """``hosted_keys`` is an allowlist, so a name outside it is never looked up in the manager.++ Warning about it would claim a lookup that never happened, on every optional env-only+ reference, on every config reload.+ """+ config_yaml = VAULT_BACKED_CONFIG.replace("api_key: os.environ/MY_PROVIDER_KEY", "api_key: os.environ/ENV_ONLY")+ config_file_path = _write_vault_backed_config(tmp_path, monkeypatch, config_yaml)+ warn = MagicMock()+ monkeypatch.setattr("litellm.proxy.proxy_server.verbose_proxy_logger.warning", warn)++ cfg = await ProxyConfig().get_config(config_file_path=config_file_path)++ assert {+ "api_key": cfg["model_list"][0]["litellm_params"]["api_key"],+ "client_is_up": litellm.secret_manager_client is not None,+ "warned_about": [call.args[1] for call in warn.call_args_list],+ } == {"api_key": None, "client_is_up": True, "warned_about": []}+++async def test_ProxyConfig_get_config_does_not_warn_under_write_only_access_mode(tmp_path, monkeypatch):+ """``write_only`` means reads never reach the manager, so an absent name is not its fault.++ That mode exists so the manager can store virtual keys while config secrets stay in the+ environment, which makes env-only references the expected state rather than an error.+ """+ config_yaml = VAULT_BACKED_CONFIG.replace(+ " key_management_settings:\n", " key_management_settings:\n access_mode: write_only\n"+ )+ config_file_path = _write_vault_backed_config(tmp_path, monkeypatch, config_yaml)+ warn = MagicMock()+ monkeypatch.setattr("litellm.proxy.proxy_server.verbose_proxy_logger.warning", warn)++ cfg = await ProxyConfig().get_config(config_file_path=config_file_path)++ assert {+ "master_key": cfg["general_settings"]["master_key"],+ "client_is_up": litellm.secret_manager_client is not None,+ "warned_about": [call.args[1] for call in warn.call_args_list],+ } == {"master_key": None, "client_is_up": True, "warned_about": []}++# ---------------------------------------------------------------------------# ProxyConfig.update_config_state / get_config_state# ---------------------------------------------------------------------------diff --git a/tests/test_litellm/secret_managers/test_secret_managers_main.py b/tests/test_litellm/secret_managers/test_secret_managers_main.pyindex 3631f640136..acc91b691d4 100644--- a/tests/test_litellm/secret_managers/test_secret_managers_main.py+++ b/tests/test_litellm/secret_managers/test_secret_managers_main.py@@ -7,7 +7,14 @@ from unittest.mock import Mock, patchimport pytest-from litellm.secret_managers.main import get_secret, normalize_nonempty_secret_str+import litellm+from litellm.integrations.custom_secret_manager import CustomSecretManager+from litellm.secret_managers.main import (+ get_secret,+ normalize_nonempty_secret_str,+ secret_manager_would_be_consulted,+)+from litellm.types.secret_managers.main import KeyManagementSettings, KeyManagementSystem# Set up logging for debugginglogging.basicConfig(level=logging.DEBUG)@@ -364,3 +371,63 @@ def test_unsupported_oidc_provider():)def test_normalize_nonempty_secret_str(raw, expected):assert normalize_nonempty_secret_str(raw) == expected+++class _SpySecretManager(CustomSecretManager):+ """Records every name the manager is actually asked for."""++ def __init__(self, asked):+ self.asked = asked++ def sync_read_secret(self, secret_name, optional_params=None, timeout=None, **kwargs):+ self.asked.append(secret_name)+ return "a-value"++ async def async_read_secret(self, secret_name, optional_params=None, timeout=None, **kwargs):+ self.asked.append(secret_name)+ return "a-value"+++ ("access_mode", "hosted_keys", "secret_name", "expected"),+ [+ ("read_only", None, "ANY_NAME", True),+ ("read_only", ["ALLOWED"], "ALLOWED", True),+ ("read_only", ["ALLOWED"], "NOT_ALLOWED", False),+ ("read_and_write", ["ALLOWED"], "ALLOWED", True),+ ("write_only", None, "ANY_NAME", False),+ ("write_only", ["ALLOWED"], "ALLOWED", False),+ ],+)+def test_secret_manager_would_be_consulted_matches_get_secret(+ monkeypatch, access_mode, hosted_keys, secret_name, expected+):+ """The predicate must agree with what get_secret actually does, not with a reading of it.++ Callers use it to tell "the manager does not have this key" apart from "the manager was+ never asked", so a predicate that drifts from get_secret's gating makes them state a+ lookup that never happened.+ """+ asked = []+ monkeypatch.setattr(litellm, "secret_manager_client", _SpySecretManager(asked))+ monkeypatch.setattr(litellm, "_key_management_system", KeyManagementSystem.CUSTOM)+ monkeypatch.setattr(+ litellm,+ "_key_management_settings",+ KeyManagementSettings(access_mode=access_mode, hosted_keys=hosted_keys),+ )+ monkeypatch.delenv(secret_name, raising=False)++ predicted = secret_manager_would_be_consulted(f"os.environ/{secret_name}")+ get_secret(f"os.environ/{secret_name}")++ assert {"predicted": predicted, "actually_consulted": bool(asked)} == {+ "predicted": expected,+ "actually_consulted": expected,+ }+++def test_secret_manager_would_be_consulted_is_false_without_a_client(monkeypatch):+ monkeypatch.setattr(litellm, "secret_manager_client", None)++ assert secret_manager_would_be_consulted("os.environ/ANY_NAME") is False