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): stop save_config from snapshotting environment_variables into the DB (#34119)
Yassin Kortame9ac84dc8b89
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 50fd85a3932..1afa5019dc1 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -3882,7 +3882,7 @@ class ProxyConfig:del config["include"]return config- async def save_config(self, new_config: dict):+ async def save_config(self, new_config: dict, include_env_vars: bool = False):global prisma_client, general_settings, user_config_file_path, store_model_in_db# Load existing config## DB - writes valid config to db@@ -3899,6 +3899,17 @@ class ProxyConfig:# Make a copy to avoid mutating the original configconfig_to_save = new_config.copy()+ # environment_variables are persisted to the DB only when a caller+ # explicitly opts in. Most callers reach save_config after+ # get_config() merged YAML + OS env into new_config (with+ # os.environ/ placeholders already resolved to plaintext), so+ # persisting them here would snapshot file/container env vars into+ # a config row that then shadows those sources on every restart.+ # The dedicated /config/update path writes env vars directly, so+ # no current caller needs include_env_vars=True.+ if not include_env_vars:+ config_to_save.pop("environment_variables", None)+# SECURITY: Always encrypt environment_variables before DB write.# _encrypt_env_variables_for_db is idempotent — a caller that# already encrypted the values (or re-submitted ciphertext read@@ -3916,6 +3927,38 @@ class ProxyConfig:with open(f"{user_config_file_path}", "w") as config_file:yaml.dump(new_config, config_file, default_flow_style=False)+ async def save_environment_variables(self, updates: dict[str, str | None]) -> None:+ """Persist specific environment variables to the DB config row.++ Each key in ``updates`` is written to the ``environment_variables``+ config row; a ``None`` value deletes that key. Env vars the caller does+ not name are preserved, so a caller that owns a couple of keys can+ update just those without snapshotting unrelated (YAML/OS-sourced)+ values the way a full ``save_config`` write would. No-op when config is+ not DB-backed.+ """+ global prisma_client, general_settings, store_model_in_db+ if prisma_client is None or not (general_settings.get("store_model_in_db", False) is True or store_model_in_db):+ return++ row = await ConfigRepository(prisma_client).table.find_first(where={"param_name": "environment_variables"})+ existing: dict = dict(row.param_value) if row is not None and row.param_value is not None else {}++ to_set = {k: v for k, v in updates.items() if v is not None}+ encrypted = self._encrypt_env_variables_for_db(environment_variables=to_set) if to_set else {}+ deleted_keys = {k for k, v in updates.items() if v is None}+ merged = {**{k: v for k, v in existing.items() if k not in deleted_keys}, **encrypted}++ serialized = json.dumps(merged)+ await ConfigRepository(prisma_client).table.upsert(+ where={"param_name": "environment_variables"},+ data={+ "create": {"param_name": "environment_variables", "param_value": serialized},+ "update": {"param_value": serialized},+ },+ )+ await invalidate_config_param("environment_variables")+def _check_for_os_environ_vars(self, config: dict, depth: int = 0, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> dict:diff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.pyindex a8926d26047..48fa4bebaa3 100644--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py@@ -1041,13 +1041,6 @@ async def update_ui_theme_settings(config = await proxy_config.get_config()before_theme = config.get("litellm_settings", {}).get("ui_theme_config")- # Update config with UI theme settings- if "general_settings" not in config:- config["general_settings"] = {}-- if "environment_variables" not in config:- config["environment_variables"] = {}-# Convert theme config to dicttheme_data = theme_config.model_dump(exclude_none=True)@@ -1056,55 +1049,29 @@ async def update_ui_theme_settings(config["litellm_settings"] = {}config["litellm_settings"]["ui_theme_config"] = theme_data- # Update UI_LOGO_PATH environment variable if logo_url is provided- # If logo_url is empty string, None, or null, remove the environment variable to use default- logo_url = theme_data.get("logo_url")- verbose_proxy_logger.debug(f"Updating logo_url: {logo_url}")-- if (- logo_url and isinstance(logo_url, str) and logo_url.strip()- ): # Check if logo_url exists and is not empty/whitespace- config["environment_variables"]["UI_LOGO_PATH"] = logo_url- os.environ["UI_LOGO_PATH"] = logo_url- verbose_proxy_logger.debug(f"Set UI_LOGO_PATH to: {logo_url}")- else:- # Remove the environment variable to restore default logo- if "UI_LOGO_PATH" in config.get("environment_variables", {}):- del config["environment_variables"]["UI_LOGO_PATH"]- verbose_proxy_logger.debug("Removed UI_LOGO_PATH from config")- if "UI_LOGO_PATH" in os.environ:- del os.environ["UI_LOGO_PATH"]- verbose_proxy_logger.debug("Removed UI_LOGO_PATH from environment")-- # Update LITELLM_FAVICON_URL environment variable if favicon_url is provided- favicon_url = theme_data.get("favicon_url")- verbose_proxy_logger.debug(f"Updating favicon_url: {favicon_url}")-- if (- favicon_url and isinstance(favicon_url, str) and favicon_url.strip()- ): # Check if favicon_url exists and is not empty/whitespace- config["environment_variables"]["LITELLM_FAVICON_URL"] = favicon_url- os.environ["LITELLM_FAVICON_URL"] = favicon_url- verbose_proxy_logger.debug(f"Set LITELLM_FAVICON_URL to: {favicon_url}")- else:- # Remove the environment variable to restore default favicon- if "LITELLM_FAVICON_URL" in config.get("environment_variables", {}):- del config["environment_variables"]["LITELLM_FAVICON_URL"]- verbose_proxy_logger.debug("Removed LITELLM_FAVICON_URL from config")- if "LITELLM_FAVICON_URL" in os.environ:- del os.environ["LITELLM_FAVICON_URL"]- verbose_proxy_logger.debug("Removed LITELLM_FAVICON_URL from environment")-- # Handle environment variable encryption if needed- stored_config = config.copy()- if "environment_variables" in stored_config and len(stored_config["environment_variables"]) > 0:- # Only encrypt if there are environment variables to encrypt- stored_config["environment_variables"] = proxy_config._encrypt_env_variables(- environment_variables=stored_config["environment_variables"]- )+ # UI_LOGO_PATH and LITELLM_FAVICON_URL are the only environment variables+ # this endpoint owns. A non-empty value sets the var; an empty or missing+ # one clears it back to the default. Apply to the live process immediately,+ # then persist only these two keys so an unrelated env var (a YAML/OS value+ # merged in by get_config) is never snapshotted into the DB.+ def _clean(url: str | None) -> str | None:+ return url if url is not None and url.strip() else None++ env_updates: dict[str, str | None] = {+ "UI_LOGO_PATH": _clean(theme_config.logo_url),+ "LITELLM_FAVICON_URL": _clean(theme_config.favicon_url),+ }+ for env_key, env_value in env_updates.items():+ if env_value is not None:+ os.environ[env_key] = env_value+ else:+ os.environ.pop(env_key, None)- # Save the updated config- await proxy_config.save_config(new_config=stored_config)+ # Persist the theme config (litellm_settings). save_config defaults to+ # include_env_vars=False, so it does not snapshot environment_variables.+ await proxy_config.save_config(new_config=config)+ # Persist only the two owned env vars, merged against the existing DB row.+ await proxy_config.save_environment_variables(env_updates)asyncio.create_task(create_config_audit_log(diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.pyindex 93b21c9d3c1..16e17b2cb7c 100644--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py@@ -8,6 +8,7 @@ Pins covered:from __future__ import annotations+import jsonimport osfrom types import SimpleNamespacefrom typing import Any, Dict@@ -407,6 +408,124 @@ async def test_ProxyConfig_save_config_invalid_path_raises(monkeypatch):await pc.save_config({"x": 1})+async def test_ProxyConfig_save_config_db_omits_environment_variables_by_default(monkeypatch):+ """A save_config after get_config() (which resolves os.environ/ placeholders+ to plaintext and merges the environment_variables section) must not snapshot+ those env vars into the DB config row. Persisting them would make a stale DB+ row shadow YAML/container env on every subsequent restart."""+ mock_prisma = MagicMock()+ mock_prisma.insert_data = AsyncMock()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)+ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})+ # a valid salt so the env-var encryption path (reached only if the pop+ # regresses) runs cleanly, making this fail on the assertion below rather+ # than on an incidental encryption crash+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-test-salt-key")++ pc = ProxyConfig()+ cfg = {+ "model_list": [{"model_name": "gpt-4o"}],+ "litellm_settings": {"success_callback": ["langfuse"]},+ "environment_variables": {"OPENAI_API_KEY": "sk-from-yaml"},+ }+ await pc.save_config(cfg)++ mock_prisma.insert_data.assert_awaited_once()+ written = mock_prisma.insert_data.await_args.kwargs["data"]+ assert "environment_variables" not in written+ # unrelated sections are still persisted; model_list is stripped as before+ assert written["litellm_settings"] == {"success_callback": ["langfuse"]}+ assert "model_list" not in written+ # the caller's dict is not mutated (save_config works on a copy)+ assert cfg["environment_variables"] == {"OPENAI_API_KEY": "sk-from-yaml"}+++async def test_ProxyConfig_save_config_db_persists_environment_variables_when_opted_in(monkeypatch):+ """The explicit opt-in path (include_env_vars=True) still persists env vars,+ encrypted, so the dedicated config-update flow can write them."""+ mock_prisma = MagicMock()+ mock_prisma.insert_data = AsyncMock()+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)+ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-test-salt-key")++ pc = ProxyConfig()+ cfg = {"litellm_settings": {}, "environment_variables": {"OPENAI_API_KEY": "sk-explicit"}}+ await pc.save_config(cfg, include_env_vars=True)++ mock_prisma.insert_data.assert_awaited_once()+ written = mock_prisma.insert_data.await_args.kwargs["data"]+ assert set(written["environment_variables"].keys()) == {"OPENAI_API_KEY"}+ # value is encrypted at rest, not the plaintext it came in as+ assert written["environment_variables"]["OPENAI_API_KEY"] != "sk-explicit"+++def _install_fake_config_repo(monkeypatch, existing_row):+ """Route ProxyConfig's ConfigRepository through an in-memory fake that+ records the value written to the environment_variables row."""+ captured: dict = {}++ class _FakeTable:+ async def find_first(self, where):+ return SimpleNamespace(param_value=existing_row) if existing_row is not None else None++ async def upsert(self, where, data):+ captured["value"] = json.loads(data["update"]["param_value"])++ class _FakeRepo:+ def __init__(self, client):+ self.table = _FakeTable()++ monkeypatch.setattr("litellm.proxy.proxy_server.ConfigRepository", _FakeRepo)+ monkeypatch.setattr("litellm.proxy.proxy_server.invalidate_config_param", AsyncMock())+ return captured+++async def test_ProxyConfig_save_environment_variables_merges_sets_and_deletes(monkeypatch):+ """The per-key env-var write updates/deletes only the named keys and leaves+ every other stored key untouched, so an unrelated env var is never lost or+ snapshotted."""+ captured = _install_fake_config_repo(+ monkeypatch,+ existing_row={"EXISTING_KEY": "ciphertext-existing", "UI_LOGO_PATH": "old-logo", "LITELLM_FAVICON_URL": "old"},+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)+ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-test-salt-key")++ pc = ProxyConfig()+ await pc.save_environment_variables({"UI_LOGO_PATH": "new-logo", "LITELLM_FAVICON_URL": None})++ written = captured["value"]+ # unrelated key preserved byte-for-byte+ assert written["EXISTING_KEY"] == "ciphertext-existing"+ # set key updated and encrypted (not the plaintext)+ assert "UI_LOGO_PATH" in written and written["UI_LOGO_PATH"] != "new-logo"+ # None-valued key deleted+ assert "LITELLM_FAVICON_URL" not in written+++async def test_ProxyConfig_save_environment_variables_noop_without_db(monkeypatch):+ """With no DB configured the per-key write must do nothing (never touch the+ config repository)."""+ captured = _install_fake_config_repo(monkeypatch, existing_row={})+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", False)+ monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})++ pc = ProxyConfig()+ await pc.save_environment_variables({"UI_LOGO_PATH": "x"})++ assert "value" not in captured++# ---------------------------------------------------------------------------# ProxyConfig._check_for_os_environ_vars# ---------------------------------------------------------------------------diff --git a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.pyindex 69845ec59c2..671a6cd39ba 100644--- a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py+++ b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py@@ -53,6 +53,7 @@ def mock_proxy_config(monkeypatch):# Add a counter to track save_config callssave_config_call_count = 0+ saved_env_updates: list = []async def mock_save_config(new_config=None):nonlocal mock_config, save_config_call_count@@ -61,13 +62,22 @@ def mock_proxy_config(monkeypatch):mock_config = new_configreturn mock_config+ async def mock_save_environment_variables(updates):+ saved_env_updates.append(updates)+from litellm.proxy.proxy_server import proxy_configmonkeypatch.setattr(proxy_config, "get_config", mock_get_config)monkeypatch.setattr(proxy_config, "save_config", mock_save_config)-- # Return both the config and the call counter- return {"config": mock_config, "save_call_count": lambda: save_config_call_count}+ monkeypatch.setattr(proxy_config, "save_environment_variables", mock_save_environment_variables)++ # Return the config, the save_config call counter, and any env-var updates+ # the endpoint routed through the dedicated save_environment_variables path+ return {+ "config": mock_config,+ "save_call_count": lambda: save_config_call_count,+ "env_updates": lambda: saved_env_updates,+ }@pytest.fixture@@ -840,11 +850,18 @@ class TestProxySettingEndpoints:assert data["status"] == "success"assert data["theme_config"]["logo_url"] == "https://example.com/new-logo.png"- # Verify config was updated- updated_config = mock_proxy_config["config"]- assert "UI_LOGO_PATH" in updated_config["environment_variables"]+ # The logo path is applied to the live process immediately+ assert os.environ["UI_LOGO_PATH"] == "https://example.com/new-logo.png"assert mock_proxy_config["save_call_count"]() == 1+ # env vars are persisted through the dedicated per-key path, and ONLY+ # the two keys this endpoint owns are touched. The unrelated SSO env+ # vars in the merged config are never snapshotted.+ env_updates = mock_proxy_config["env_updates"]()+ assert env_updates == [+ {"UI_LOGO_PATH": "https://example.com/new-logo.png", "LITELLM_FAVICON_URL": None}+ ]+def test_update_ui_theme_settings_with_favicon(self, mock_proxy_config, mock_auth, monkeypatch):@@ -869,13 +886,15 @@ class TestProxySettingEndpoints:== "https://example.com/custom-favicon.ico")- updated_config = mock_proxy_config["config"]- assert "UI_LOGO_PATH" in updated_config["environment_variables"]- assert "LITELLM_FAVICON_URL" in updated_config["environment_variables"]- assert (- updated_config["environment_variables"]["LITELLM_FAVICON_URL"]- == "https://example.com/custom-favicon.ico"- )+ assert os.environ["UI_LOGO_PATH"] == "https://example.com/new-logo.png"+ assert os.environ["LITELLM_FAVICON_URL"] == "https://example.com/custom-favicon.ico"+ # Only the two owned keys are persisted, both with their new values+ assert mock_proxy_config["env_updates"]() == [+ {+ "UI_LOGO_PATH": "https://example.com/new-logo.png",+ "LITELLM_FAVICON_URL": "https://example.com/custom-favicon.ico",+ }+ ]def test_update_ui_theme_settings_clear_favicon(self, mock_proxy_config, mock_auth, monkeypatch