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]

fix(proxy): unset DB environment variables removed from the row on every worker by row revision (#46709)

Mateo Wang610443519af0
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20261015120000_add_environment_variables_revision_trigger/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20261015120000_add_environment_variables_revision_trigger/migration.sql
new file mode 100644
index 00000000000..67e75896cc4
--- /dev/null
+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20261015120000_add_environment_variables_revision_trigger/migration.sql
@@ -0,0 +1,23 @@
+SET LOCAL lock_timeout = '10s';
+
+CREATE SEQUENCE IF NOT EXISTS "litellm_environment_variables_revision_seq";
+GRANT USAGE ON SEQUENCE "litellm_environment_variables_revision_seq" TO PUBLIC;
+
+CREATE OR REPLACE FUNCTION litellm_bump_environment_variables_revision() RETURNS TRIGGER AS $$
+DECLARE
+ next_revision BIGINT := nextval(format('%I.litellm_environment_variables_revision_seq', TG_TABLE_SCHEMA)::regclass);
+BEGIN
+ IF TG_OP = 'UPDATE' THEN
+ NEW."reload_revision" := GREATEST(next_revision, OLD."reload_revision" + 1);
+ ELSE
+ NEW."reload_revision" := next_revision;
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+DROP TRIGGER IF EXISTS "litellm_environment_variables_revision" ON "LiteLLM_Config";
+CREATE TRIGGER "litellm_environment_variables_revision"
+BEFORE INSERT OR UPDATE ON "LiteLLM_Config"
+FOR EACH ROW WHEN (NEW."param_name" = 'environment_variables')
+EXECUTE PROCEDURE litellm_bump_environment_variables_revision();
diff --git a/litellm/proxy/db/prisma_client.py b/litellm/proxy/db/prisma_client.py
index 78da03150dc..53971ed412c 100644
--- a/litellm/proxy/db/prisma_client.py
+++ b/litellm/proxy/db/prisma_client.py
@@ -4,6 +4,7 @@ database token (AWS RDS IAM or Microsoft Entra ID) fresh.
"""
import asyncio
+import importlib.resources
import os
import random
import signal
@@ -37,6 +38,8 @@ if TYPE_CHECKING:
from prisma import Prisma
from prisma.types import HttpConfig
+_ENVIRONMENT_VARIABLES_REVISION_MIGRATION: Final = "20261015120000_add_environment_variables_revision_trigger"
+
__all__ = (
"IAMEndpoint",
"PrismaManager",
@@ -990,6 +993,36 @@ class PrismaManager:
return
ProxyExtrasDBManager.apply_replica_identity_full_if_requested()
+ @staticmethod
+ def _apply_environment_variables_revision_trigger() -> None:
+ try:
+ from litellm_proxy_extras.prisma_toolchain import (
+ prisma_command_timeout,
+ run_prisma,
+ )
+ except ImportError:
+ return
+ migration: Final = (
+ importlib.resources.files("litellm_proxy_extras")
+ / "migrations"
+ / _ENVIRONMENT_VARIABLES_REVISION_MIGRATION
+ / "migration.sql"
+ )
+ if not migration.is_file():
+ return
+ try:
+ run_prisma(
+ ["prisma", "db", "execute", "--schema", "schema.prisma", "--file", str(migration)],
+ timeout=prisma_command_timeout(),
+ env=os.environ.copy(),
+ )
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
+ verbose_proxy_logger.warning(
+ "Could not create the environment_variables revision trigger after prisma db push, so a removed "
+ "DB environment variable stays set on running proxies until they restart: %s",
+ e,
+ )
+
@staticmethod
def _raise_if_partitioned_spend_logs() -> None:
"""`prisma db push` rewrites a doc-partitioned LiteLLM_SpendLogs
@@ -1066,6 +1099,7 @@ class PrismaManager:
stdout=None,
stderr=None,
)
+ PrismaManager._apply_environment_variables_revision_trigger()
PrismaManager._apply_replica_identity_full_if_requested()
return True
except subprocess.TimeoutExpired as e:
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index 592c732bfd3..54f4ca25974 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -322,9 +322,9 @@ def _credentials_table(prisma_client: PrismaClient) -> TableActions[CredentialIt
)
-def _config_table(prisma_client: PrismaClient) -> _ConfigTableActions:
+def _config_table(prisma_client: PrismaClient, *, use_writer: bool = False) -> _ConfigTableActions:
return cast( # cast-ok: ConfigRepository.table hides the write actions this module needs on that same object
- "_ConfigTableActions", ConfigRepository(prisma_client).table
+ "_ConfigTableActions", ConfigRepository(prisma_client, use_writer=use_writer).table
)
@@ -5566,7 +5566,7 @@ async def rotate_master_key(
await publish_config_change(redis_cache=coordination_redis_cache(), object_type="litellm_proxymodeltable")
# 3. process config table
try:
- config = await _config_table(prisma_client).find_many()
+ config = await _config_table(prisma_client, use_writer=True).find_many()
except Exception:
config = None
@@ -5589,7 +5589,7 @@ async def rotate_master_key(
if encrypted_env_vars:
await _config_table(prisma_client).update(
where={"param_name": "environment_variables"},
- data={"param_value": prisma.Json(encrypted_env_vars)},
+ data={"param_value": prisma.Json({**environment_variables_dict, **encrypted_env_vars})},
)
try:
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 3de3dccc532..16b831fc8e9 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -4,6 +4,7 @@ import enum
import importlib
import inspect
import io
+import itertools
import os
import random
import re
@@ -551,6 +552,7 @@ from litellm.proxy.config_resolvers.settings_rules import (
from litellm.proxy.config_resolvers.settings_rules import (
JsonValue as SettingsJsonValue,
)
+from litellm.proxy.config_resolvers.sso import SSO_FIELD_ENV_VARS
from litellm.proxy.container_endpoints.endpoints import router as container_router
from litellm.proxy.credential_endpoints.endpoints import router as credential_router
from litellm.proxy.db.create_views import SupportsRawQueries
@@ -2225,9 +2227,9 @@ class _InvitationAcceptTxManager(Protocol):
_ProxyModelRow: TypeAlias = "prisma_models.LiteLLM_ProxyModelTable"
-def _config_param_table(client: PrismaClient | None) -> TableActions[_ConfigParamRow]:
+def _config_param_table(client: PrismaClient | None, *, use_writer: bool = False) -> TableActions[_ConfigParamRow]:
return cast( # cast-ok: this is prisma's LiteLLM_Config actions object, which parses its Json column to a mapping
- "TableActions[_ConfigParamRow]", ConfigRepository(client).table
+ "TableActions[_ConfigParamRow]", ConfigRepository(client, use_writer=use_writer).table
)
@@ -5565,6 +5567,23 @@ def _as_settings_mapping(value: object) -> Mapping[str, SettingsJsonValue]:
return _SETTINGS_MAPPING.validate_python(value)
+_SSO_ENVIRONMENT_VARIABLES: Final = frozenset(SSO_FIELD_ENV_VARS.values())
+_ENVIRONMENT_VALUES: Final = TypeAdapter(Mapping[str, str])
+
+
+def _config_row_revision(row: object) -> int | None:
+ revision: Final[object] = getattr(row, "reload_revision", None)
+ return revision if isinstance(revision, int) and not isinstance(revision, bool) else None
+
+
+def _restore_environment(keys: frozenset[str], values: Mapping[str, str]) -> None:
+ for key in keys:
+ if (value := values.get(key)) is None:
+ os.environ.pop(key, None)
+ else:
+ os.environ[key] = value
+
+
def _get_field_default(field_info: FieldInfo) -> JsonValue:
if field_info.default is PydanticUndefined:
return None
@@ -5726,6 +5745,12 @@ class ProxyConfig:
self.router_settings: Final[SettingsStore] = SettingsStore("router_settings")
self.litellm_settings: Final[SettingsStore] = SettingsStore("litellm_settings")
self.environment_variables: Final[SettingsStore] = SettingsStore("environment_variables")
+ self._environment_before_db: Mapping[str, str] | None = None
+ self._db_environment_revision: int | None = None
+ self._environment_read_numbers: Final = itertools.count(1)
+ self._latest_applied_environment_read: int = 0
+ self._db_environment_keys: frozenset[str] = frozenset()
+ self._sso_environment_removals: frozenset[str] = frozenset()
self._warned_shadowed_keys: frozenset[tuple[Section, str]] = frozenset()
self._db_config_callback_entries: Mapping[tuple[str, str], _DbCallbackRegistration] = MappingProxyType({})
self._settings_stores: Final[Mapping[Section, SettingsStore]] = MappingProxyType(
@@ -6030,7 +6055,7 @@ class ProxyConfig:
if prisma_client is None or not (general_settings.get("store_model_in_db", False) is True or store_model_in_db):
return
- row: Final[_ConfigParamRow | None] = await _config_param_table(prisma_client).find_first(
+ row: Final[_ConfigParamRow | None] = await _config_param_table(prisma_client, use_writer=True).find_first(
where={"param_name": "environment_variables"}
)
existing: Final[dict] = dict(row.param_value) if row is not None and row.param_value is not None else {}
@@ -8364,6 +8389,8 @@ class ProxyConfig:
verbose_proxy_logger.info("'store_model_in_db' is not True, skipping db updates")
return config
+ environment_before_db: Final = self._captured_environment_before_db()
+ environment_read: Final = next(self._environment_read_numbers)
sections: Final = tuple(self._settings_stores)
responses: Final = await asyncio.gather(*(get_config_param(prisma_client, section) for section in sections))
for section, response in zip(sections, responses):
@@ -8377,6 +8404,10 @@ class ProxyConfig:
)
if section == "litellm_settings":
self._apply_litellm_settings_db_values(self._prepared_db_settings_values(section, param_value))
+ elif section == "environment_variables":
+ await self._apply_db_environment_variables_row(
+ prisma_client, response, environment_before_db, environment_read
+ )
else:
self._settings_stores[section].apply_db_row(
section,
@@ -8386,6 +8417,49 @@ class ProxyConfig:
self._warn_about_shadowed_db_settings()
return self._config_with_resolved_settings(config)
+ async def _apply_db_environment_variables_row(
+ self, prisma_client: PrismaClient, row: object, environment_before_db: Mapping[str, str], read: int
+ ) -> None:
+ current: Final = await self._environment_row_not_behind_the_applied_one(prisma_client, row)
+ if current is None or (param_value := getattr(current, "param_value", None)) is None:
+ return
+ self._apply_db_environment_variables(param_value, _config_row_revision(current), environment_before_db, read)
+
+ async def _environment_row_not_behind_the_applied_one(
+ self, prisma_client: PrismaClient, row: object
+ ) -> object | None:
+ if not self._is_behind_applied_environment_revision(row):
+ return row
+ applied_revision: Final = self._db_environment_revision
+ try:
+ writer_row: Final = await call_with_db_reconnect_retry(
+ prisma_client,
+ lambda: ConfigRepository(prisma_client, use_writer=True).table.find_unique(
+ where={"param_name": "environment_variables"}
+ ),
+ reason="environment_variables_writer_read_failure",
+ )
+ except Exception as e:
+ if not (
+ PrismaDBExceptionHandler.is_database_transport_error(e)
+ or PrismaDBExceptionHandler.is_database_connection_error(e)
+ ):
+ raise
+ verbose_proxy_logger.warning(
+ "Could not read environment_variables from the writer database, keeping the current environment "
+ "variables until the next config sync: %s",
+ e,
+ )
+ return None
+ return writer_row if self._db_environment_revision == applied_revision else None
+
+ def _is_behind_applied_environment_revision(self, row: object) -> bool:
+ applied_revision: Final = self._db_environment_revision
+ if applied_revision is None or row is None:
+ return False
+ revision: Final = _config_row_revision(row)
+ return revision is None or revision < applied_revision
+
def _warn_about_shadowed_db_settings(self) -> None:
shadowed: Final[frozenset[tuple[Section, str]]] = frozenset(
(section, key) for section, store in self._settings_stores.items() for key in store.shadowed_db_keys()
@@ -8397,21 +8471,47 @@ class ProxyConfig:
self._warned_shadowed_keys = shadowed
def _prepared_db_settings_values(self, section: Section, value: object) -> Mapping[str, SettingsJsonValue]:
- if section == "environment_variables":
- decrypted: Final = self.decrypt_and_set_db_env_variables(
- dict(_as_settings_mapping(value)), return_original_value=True
- )
- normalized: Final = {
- **decrypted,
- **{key.upper(): decrypted_value for key, decrypted_value in decrypted.items()},
- }
- for key, decrypted_value in normalized.items():
- os.environ[key] = decrypted_value
- return _as_settings_mapping(normalized)
-
scrubbed: Final = _scrub_db_overlay_remote_module_loads(section=section, db_value=value)
return _as_settings_mapping(scrubbed)
+ def _apply_db_environment_variables(
+ self, value: object, revision: int | None, environment_before_db: Mapping[str, str], read: int
+ ) -> None:
+ if read < self._latest_applied_environment_read:
+ return
+ self._latest_applied_environment_read = read
+ applied_revision: Final = self._db_environment_revision
+ row: Final = _as_settings_mapping(value)
+ decrypted: Final = _ENVIRONMENT_VALUES.validate_python(
+ self.decrypt_and_set_db_env_variables(dict(row), return_original_value=True)
+ )
+ applied: Final = {**decrypted, **{key.upper(): decrypted_value for key, decrypted_value in decrypted.items()}}
+ os.environ.update(applied)
+ if revision is None or revision == applied_revision:
+ self._db_environment_keys = self._db_environment_keys | frozenset(applied)
+ else:
+ stored: Final = frozenset(key for key, stored_value in row.items() if stored_value is not None)
+ still_stored: Final = stored | frozenset(key.upper() for key in stored)
+ removed: Final = self._db_environment_keys - still_stored
+ _restore_environment(removed - _SSO_ENVIRONMENT_VARIABLES, environment_before_db)
+ self._sso_environment_removals = (
+ self._sso_environment_removals | (removed & _SSO_ENVIRONMENT_VARIABLES)
+ ) - still_stored
+ self._db_environment_keys = (self._db_environment_keys & still_stored) | frozenset(applied)
+ self._db_environment_revision = revision
+ self.environment_variables.apply_db_row("environment_variables", _as_settings_mapping(applied))
+
+ def _restore_sso_environment_removals(self, sso_table_keys: frozenset[str]) -> None:
+ _restore_environment(
+ self._sso_environment_removals - sso_table_keys, self._environment_before_db or MappingProxyType({})
+ )
+ self._sso_environment_removals = frozenset()
+
+ def _captured_environment_before_db(self) -> Mapping[str, str]:
+ if self._environment_before_db is None:
+ self._environment_before_db = MappingProxyType(dict(os.environ))
+ return self._environment_before_db
+
def _apply_litellm_settings_db_values(self, db_values: Mapping[str, SettingsJsonValue]) -> None:
self.litellm_settings.apply_db_row("litellm_settings", db_values)
for key in LITELLM_SETTINGS_SAFE_DB_OVERRIDES:
@@ -8645,6 +8745,8 @@ class ProxyConfig:
if self._should_load_db_object(object_type="sso_settings"):
await self._init_sso_settings_in_db(prisma_client=prisma_client)
+ else:
+ self._restore_sso_environment_removals(frozenset())
if self._should_load_db_object(object_type="cache_settings"):
from litellm.proxy.management_endpoints.cache_settings_endpoints import (
CacheSettingsManager,
@@ -8821,6 +8923,11 @@ class ProxyConfig:
sso_settings.sso_settings.pop("ui_access_mode", None)
uppercase_sso_settings: Final = {key.upper(): value for key, value in sso_settings.sso_settings.items()}
self.decrypt_and_set_db_env_variables(environment_variables=uppercase_sso_settings)
+ self._restore_sso_environment_removals(
+ frozenset()
+ if sso_settings is None
+ else frozenset(key.upper() for key, value in sso_settings.sso_settings.items() if value)
+ )
except Exception as e:
verbose_proxy_logger.exception(
"litellm.proxy.proxy_server.py::ProxyConfig:_init_sso_settings_in_db - %s", e
@@ -18783,7 +18890,7 @@ async def update_config(
proxy_config.reject_config_owned_writes(section_name="router_settings", changed_keys=router_settings_updates)
async def _read_section(param_name: str) -> dict:
- row: Final[_ConfigParamRow | None] = await _config_param_table(prisma_client).find_first(
+ row: Final[_ConfigParamRow | None] = await _config_param_table(prisma_client, use_writer=True).find_first(
where={"param_name": param_name}
)
if row is None or row.param_value is None:
diff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py
index 4ece88f757d..d51e1167888 100644
--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py
+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py
@@ -1326,7 +1326,7 @@ async def update_sso_settings(
# Remove SSO-related env vars from config.environment_variables
try:
- env_var_entry: Final = await _config_param_db(ConfigRepository(prisma_client)).find_unique(
+ env_var_entry: Final = await _config_param_db(ConfigRepository(prisma_client, use_writer=True)).find_unique(
where={"param_name": "environment_variables"}
)
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 36ace3c1697..e34093a7caf 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -4559,11 +4559,12 @@ litellm_config_cache: Final[DualCache] = DualCache(
class _ConfigRow:
"""Mimics the Prisma litellm_config row shape for cached entries."""
- __slots__ = ("param_name", "param_value")
+ __slots__ = ("param_name", "param_value", "reload_revision")
- def __init__(self, param_name: str, param_value: object) -> None:
+ def __init__(self, param_name: str, param_value: object, reload_revision: int | None = None) -> None:
self.param_name = param_name
self.param_value = param_value
+ self.reload_revision = reload_revision
CONFIG_PARAMS_TARGET: Final = "config_params"
@@ -4574,14 +4575,23 @@ def _config_cache_key(param_name: str) -> str:
def _pack_config_row(row: Any) -> dict[str, object]:
- return {"param_name": row.param_name, "param_value": row.param_value}
+ return {
+ "param_name": row.param_name,
+ "param_value": row.param_value,
+ "reload_revision": getattr(row, "reload_revision", None),
+ }
def _unpack_config_row(cached: object) -> _ConfigRow | None:
if cached is None or cached == _CONFIG_CACHE_MISS:
return None
if isinstance(cached, dict):
- return _ConfigRow(cached["param_name"], cached["param_value"])
+ revision: Final = cached.get("reload_revision")
+ return _ConfigRow(
+ cached["param_name"],
+ cached["param_value"],
+ revision if isinstance(revision, int) and not isinstance(revision, bool) else None,
+ )
return None
diff --git a/tests/integration/configuration/test_effective_settings.py b/tests/integration/configuration/test_effective_settings.py
index 7f6313e209e..014cfd3a866 100644
--- a/tests/integration/configuration/test_effective_settings.py
+++ b/tests/integration/configuration/test_effective_settings.py
@@ -1,5 +1,7 @@
import json
import os
+import subprocess
+import sys
import uuid
from collections.abc import Callable, Iterator
from contextlib import contextmanager
@@ -7,9 +9,13 @@ from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Final
+from urllib.parse import parse_qs, urlsplit, urlunsplit
import httpx
+import psycopg
import pytest
+from psycopg import sql
+from psycopg.types.json import Jsonb
from pydantic import BaseModel, JsonValue, TypeAdapter
from tests.integration._support.client import Gateway, eventually, object_value, string_value
@@ -1111,3 +1117,585 @@ def test_credential_value_update_and_model_reload_reach_provider(gateway: Gatewa
observed.raise_for_status()
assert len(observed.json()["requests"]) == 1, (value, reload, observed.text)
assert observed.json()["requests"][0]["authorization"] == f"Bearer {value}"
+
+
+_ENVIRONMENT_VARIABLES_REVISION_MIGRATION: Final = (
+ "litellm-proxy-extras/litellm_proxy_extras/migrations/"
+ "20261015120000_add_environment_variables_revision_trigger/migration.sql"
+)
+
+
+def _prisma(*arguments: str) -> None:
+ subprocess.run((sys.executable, "-I", "-m", "prisma", *arguments), check=True, capture_output=True, text=True)
+
+
+def _push_schema() -> None:
+ _prisma("db", "push", "--schema", "litellm/proxy/schema.prisma", "--skip-generate")
+
+
+def _push_schema_with_environment_variables_revision_trigger() -> None:
+ _push_schema()
+ _prisma(
+ "db", "execute", "--schema", "litellm/proxy/schema.prisma", "--file", _ENVIRONMENT_VARIABLES_REVISION_MIGRATION
+ )
+
+
+def _provider_echoing_its_key(source: str) -> Callable[[Request], Reply]:
+ def provider(request: Request) -> Reply:
+ assert request.method == "POST"
+ assert request.target == "/v1/chat/completions", request.target
+ return _completion_reply(f"{source} {request.headers['authorization']}")
+
+ return provider
+
+
+def _environment_variables_proxy_config(
+ directory: Path, gateway: Gateway, alias: str, config_file_provider: Wire
+) -> Path:
+ config: Final = directory / "environment-variables-proxy.yaml"
+ config.write_text(
+ json.dumps(
+ {
+ "model_list": [{"model_name": alias, "litellm_params": {"model": "openai/gpt-4o-mini"}}],
+ "general_settings": {"master_key": gateway.key, "store_model_in_db": True},
+ "environment_variables": {"OPENAI_BASE_URL": config_file_provider.url + "/v1"},
+ }
+ )
+ )
+ return config
+
+
+def _environment_variables_proxy_environment(database_url: str, process_key: str) -> dict[str, str]:
+ return {
+ "DATABASE_URL": database_url,
+ "DISABLE_SCHEMA_UPDATE": "true",
+ "LITELLM_CONFIG_PARAM_CACHE_TTL_SECONDS": "1",
+ "OPENAI_API_KEY": process_key,
+ "PROXY_CONFIG_RELOAD_INTERVAL_SECONDS": "2",
+ }
+
+
+def _chat_answer(proxy: Gateway, alias: str) -> str:
+ response: Final = proxy.request(
+ "POST", "/v1/chat/completions", {"model": alias, "messages": [{"role": "user", "content": "which key"}]}
+ )
+ assert response.status_code == 200, response.text
+ return string_value(object_value(object_value(response.json()["choices"][0])["message"])["content"])
+
+
+def test_removing_db_environment_variables_restores_process_and_config_file_values_on_every_proxy(
+ gateway: Gateway, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ alias: Final = "environment-variables-" + marker
+ process_key: Final = "process-key-" + marker
+ database_key: Final = "database-key-" + marker
+
+ with (
+ scratch_database() as database_url,
+ wire_server(_provider_echoing_its_key("config-file")) as config_file_provider,
+ wire_server(_provider_echoing_its_key("database")) as database_provider,
+ ):
+ monkeypatch.setenv("DATABASE_URL", database_url)
+ _push_schema_with_environment_variables_revision_trigger()
+ config: Final = _environment_variables_proxy_config(tmp_path, gateway, alias, config_file_provider)
+ environment: Final = _environment_variables_proxy_environment(database_url, process_key)
+ removed: Final = ("DATABASE_URL_READ_REPLICA", "OPENAI_API_BASE", "OPENAI_BASE_URL")
+ from_process_and_config_file: Final = f"config-file Bearer {process_key}"
+ from_database: Final = f"database Bearer {database_key}"
+ with owned_proxy(
+ gateway, tmp_path / "first", environment, config=config, database_setup=(), remove_environment=removed
+ ) as first:
+ assert _chat_answer(first, alias) == from_process_and_config_file
+
+ stored: Final = first.request(
+ "POST",
+ "/config/update",
+ {
+ "environment_variables": {
+ "OPENAI_API_KEY": database_key,
+ "OPENAI_BASE_URL": database_provider.url + "/v1",
+ }
+ },
+ )
+ assert stored.status_code == 200, stored.text
+ eventually(lambda: _chat_answer(first, alias), lambda value: value == from_database, seconds=30)
+
+ with owned_proxy(
+ gateway, tmp_path / "peer", environment, config=config, database_setup=(), remove_environment=removed
+ ) as peer_booted_with_the_row_stored:
+
+ def answers() -> tuple[str, str]:
+ return (_chat_answer(first, alias), _chat_answer(peer_booted_with_the_row_stored, alias))
+
+ eventually(answers, lambda values: values == (from_database,) * 2, seconds=30)
+
+ unset: Final = first.request(
+ "POST",
+ "/config/update",
+ {"environment_variables": {"OPENAI_API_KEY": None, "OPENAI_BASE_URL": None}},
+ )
+ assert unset.status_code == 200, unset.text
+ assert _config_section(database_url, "environment_variables") == {
+ "OPENAI_API_KEY": None,
+ "OPENAI_BASE_URL": None,
+ }
+ eventually(answers, lambda values: values == (from_process_and_config_file,) * 2, seconds=30)
+
+
+def test_a_proxy_that_pushes_its_own_schema_unsets_a_removed_db_environment_variable(
+ gateway: Gateway, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ alias: Final = "environment-variables-db-push-" + marker
+ process_key: Final = "process-key-" + marker
+ database_key: Final = "database-key-" + marker
+
+ with (
+ scratch_database() as database_url,
+ wire_server(_provider_echoing_its_key("config-file")) as config_file_provider,
+ wire_server(_provider_echoing_its_key("database")) as database_provider,
+ ):
+ monkeypatch.setenv("DATABASE_URL", database_url)
+ config: Final = _environment_variables_proxy_config(tmp_path, gateway, alias, config_file_provider)
+ environment: Final = {
+ **_environment_variables_proxy_environment(database_url, process_key),
+ "DISABLE_SCHEMA_UPDATE": "false",
+ }
+ from_process_and_config_file: Final = f"config-file Bearer {process_key}"
+ with owned_proxy(
+ gateway,
+ tmp_path / "proxy",
+ environment,
+ config=config,
+ remove_environment=("DATABASE_URL_READ_REPLICA", "OPENAI_API_BASE", "OPENAI_BASE_URL"),
+ ) as proxy:
+ assert _chat_answer(proxy, alias) == from_process_and_config_file
+ stored: Final = proxy.request(
+ "POST",
+ "/config/update",
+ {
+ "environment_variables": {
+ "OPENAI_API_KEY": database_key,
+ "OPENAI_BASE_URL": database_provider.url + "/v1",
+ }
+ },
+ )
+ assert stored.status_code == 200, stored.text
+ eventually(
+ lambda: _chat_answer(proxy, alias), lambda value: value == f"database Bearer {database_key}", seconds=30
+ )
+
+ unset: Final = proxy.request(
+ "POST",
+ "/config/update",
+ {"environment_variables": {"OPENAI_API_KEY": None, "OPENAI_BASE_URL": None}},
+ )
+ assert unset.status_code == 200, unset.text
+ eventually(
+ lambda: _chat_answer(proxy, alias), lambda value: value == from_process_and_config_file, seconds=30
+ )
+
+
+def _environment_variables_row(database_url: str) -> dict[str, JsonValue]:
+ return read_rows(
+ 'SELECT param_value, reload_revision FROM "LiteLLM_Config" WHERE param_name = %s',
+ ("environment_variables",),
+ database_url=database_url,
+ )[0]
+
+
+def _load_environment_variables_row(replica_url: str, row: dict[str, JsonValue]) -> None:
+ with psycopg.connect(replica_url, autocommit=True) as replica:
+ replica.execute(
+ 'INSERT INTO "LiteLLM_Config" (param_name, param_value, reload_revision) VALUES (%s, %s, %s) '
+ "ON CONFLICT (param_name) DO UPDATE "
+ "SET param_value = EXCLUDED.param_value, reload_revision = EXCLUDED.reload_revision",
+ ("environment_variables", Jsonb(row["param_value"]), row["reload_revision"]),
+ )
+
+
+def test_a_read_replica_back_on_an_older_row_does_not_bring_back_a_removed_db_environment_variable(
+ gateway: Gateway, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ alias: Final = "environment-variables-replica-" + marker
+ process_key: Final = "process-key-" + marker
+ database_key: Final = "database-key-" + marker
+
+ with (
+ scratch_database() as writer_url,
+ scratch_database() as replica_url,
+ wire_server(_provider_echoing_its_key("config-file")) as config_file_provider,
+ wire_server(_provider_echoing_its_key("database")) as database_provider,
+ wire_server(_provider_echoing_its_key("writer")) as writer_provider,
+ ):
+ monkeypatch.setenv("DATABASE_URL", replica_url)
+ _push_schema()
+ monkeypatch.setenv("DATABASE_URL", writer_url)
+ _push_schema_with_environment_variables_revision_trigger()
+ config: Final = _environment_variables_proxy_config(tmp_path, gateway, alias, config_file_provider)
+ environment: Final = {
+ **_environment_variables_proxy_environment(writer_url, process_key),
+ "DATABASE_URL_READ_REPLICA": replica_url,
+ }
+ from_process_and_config_file: Final = f"config-file Bearer {process_key}"
+ with owned_proxy(
+ gateway,
+ tmp_path / "replica-reader",
+ environment,
+ config=config,
+ database_setup=(),
+ remove_environment=("OPENAI_API_BASE", "OPENAI_BASE_URL"),
+ ) as proxy:
+ assert _chat_answer(proxy, alias) == from_process_and_config_file
+
+ stored: Final = proxy.request(
+ "POST",
+ "/config/update",
+ {
+ "environment_variables": {
+ "OPENAI_API_KEY": database_key,
+ "OPENAI_BASE_URL": database_provider.url + "/v1",
+ }
+ },
+ )
+ assert stored.status_code == 200, stored.text
+ row_holding_the_key: Final = _environment_variables_row(writer_url)
+ _load_environment_variables_row(replica_url, row_holding_the_key)
+ eventually(
+ lambda: _chat_answer(proxy, alias),
+ lambda value: value == f"database Bearer {database_key}",
+ seconds=30,
+ )
+
+ unset: Final = proxy.request(
+ "POST", "/config/update", {"environment_variables": {"OPENAI_API_KEY": None, "OPENAI_BASE_URL": None}}
+ )
+ assert unset.status_code == 200, unset.text
+ _load_environment_variables_row(replica_url, _environment_variables_row(writer_url))
+ eventually(
+ lambda: _chat_answer(proxy, alias), lambda value: value == from_process_and_config_file, seconds=30
+ )
+
+ _load_environment_variables_row(replica_url, row_holding_the_key)
+ _save_environment_variables_as(writer_url, {"OPENAI_BASE_URL": writer_provider.url + "/v1"})
+ eventually(
+ lambda: _chat_answer(proxy, alias),
+ lambda value: value == f"writer Bearer {process_key}",
+ seconds=30,
+ )
+
+
+_CAPPED_WRITER_ROLE_PASSWORD: Final = "integration-capped-writer-password"
+
+
+@contextmanager
+def _database_owned_by_a_login_role() -> Iterator[tuple[str, str, str]]:
+ role: Final = f"integration_capped_writer_{uuid.uuid4().hex}"
+ with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as admin:
+ admin.execute(
+ sql.SQL("CREATE ROLE {} LOGIN PASSWORD {} NOSUPERUSER NOINHERIT").format(
+ sql.Identifier(role), sql.Literal(_CAPPED_WRITER_ROLE_PASSWORD)
+ )
+ )
+ try:
+ with scratch_database() as admin_url:
+ parsed: Final = urlsplit(admin_url)
+ admin.execute(
+ sql.SQL("ALTER DATABASE {} OWNER TO {}").format(
+ sql.Identifier(parsed.path.lstrip("/")), sql.Identifier(role)
+ )
+ )
+ host: Final = parsed.netloc.rpartition("@")[2]
+ yield (
+ role,
+ admin_url,
+ urlunsplit(parsed._replace(netloc=f"{role}:{_CAPPED_WRITER_ROLE_PASSWORD}@{host}")),
+ )
+ finally:
+ admin.execute(sql.SQL("DROP ROLE {}").format(sql.Identifier(role)))
+
+
+def _set_connection_limit(admin_url: str, role: str, limit: int) -> None:
+ with psycopg.connect(admin_url, autocommit=True) as admin:
+ admin.execute(sql.SQL("ALTER ROLE {} CONNECTION LIMIT {}").format(sql.Identifier(role), sql.Literal(limit)))
+
+
+def _open_connections(database_url: str, role: str) -> JsonValue:
+ return read_rows(
+ "SELECT count(*) AS connections FROM pg_stat_activity WHERE usename = %s",
+ (role,),
+ database_url=database_url,
+ )[0]["connections"]
+
+
+def test_a_writer_database_out_of_connections_keeps_the_applied_db_environment_variables(
+ gateway: Gateway, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ alias: Final = "environment-variables-capped-writer-" + marker
+ process_key: Final = "process-key-" + marker
+ database_key: Final = "database-key-" + marker
+
+ with (
+ _database_owned_by_a_login_role() as (role, writer_admin_url, writer_url),
+ scratch_database() as replica_url,
+ wire_server(_provider_echoing_its_key("config-file")) as config_file_provider,
+ wire_server(_provider_echoing_its_key("database")) as database_provider,
+ wire_server(_provider_echoing_its_key("writer")) as writer_provider,
+ ):
+ monkeypatch.setenv("DATABASE_URL", replica_url)
+ _push_schema()
+ monkeypatch.setenv("DATABASE_URL", writer_url)
+ _push_schema_with_environment_variables_revision_trigger()
+ config: Final = _environment_variables_proxy_config(tmp_path, gateway, alias, config_file_provider)
+ parsed_writer_url: Final = urlsplit(writer_url)
+ writer_url_dropping_idle_connections: Final = urlunsplit(
+ parsed_writer_url._replace(
+ query="&".join(part for part in (parsed_writer_url.query, "max_idle_connection_lifetime=1") if part)
+ )
+ )
+ environment: Final = {
+ **_environment_variables_proxy_environment(writer_url_dropping_idle_connections, process_key),
+ "DATABASE_URL_READ_REPLICA": replica_url,
+ }
+ from_process_and_config_file: Final = f"config-file Bearer {process_key}"
+ with owned_proxy(
+ gateway,
+ tmp_path / "capped-writer",
+ environment,
+ config=config,
+ database_setup=(),
+ remove_environment=("OPENAI_API_BASE", "OPENAI_BASE_URL"),
+ ) as proxy:
+ stored: Final = proxy.request(
+ "POST",
+ "/config/update",
+ {
+ "environment_variables": {
+ "OPENAI_API_KEY": database_key,
+ "OPENAI_BASE_URL": database_provider.url + "/v1",
+ }
+ },
+ )
+ assert stored.status_code == 200, stored.text
+ row_holding_the_key: Final = _environment_variables_row(writer_admin_url)
+ _load_environment_variables_row(replica_url, row_holding_the_key)
+ eventually(
+ lambda: _chat_answer(proxy, alias),
+ lambda value: value == f"database Bearer {database_key}",
+ seconds=30,
+ )
+
+ unset: Final = proxy.request(
+ "POST", "/config/update", {"environment_variables": {"OPENAI_API_KEY": None, "OPENAI_BASE_URL": None}}
+ )
+ assert unset.status_code == 200, unset.text
+ _load_environment_variables_row(replica_url, _environment_variables_row(writer_admin_url))
+ eventually(
+ lambda: _chat_answer(proxy, alias), lambda value: value == from_process_and_config_file, seconds=30
+ )
+
+ _load_environment_variables_row(replica_url, row_holding_the_key)
+ _set_connection_limit(writer_admin_url, role, 0)
+ with pytest.raises(psycopg.OperationalError):
+ psycopg.connect(writer_url).close()
+ eventually(lambda: _open_connections(writer_admin_url, role), lambda count: count == 0, seconds=30)
+
+ config_read: Final = proxy.request("GET", "/get/config/callbacks")
+ assert config_read.status_code == 200, config_read.text
+ assert _chat_answer(proxy, alias) == from_process_and_config_file
+
+ _set_connection_limit(writer_admin_url, role, -1)
+ _save_environment_variables_as(writer_admin_url, {"OPENAI_BASE_URL": writer_provider.url + "/v1"})
+ eventually(
+ lambda: _chat_answer(proxy, alias),
+ lambda value: value == f"writer Bearer {process_key}",
+ seconds=30,
+ )
+
+
+def _sign_in_client_id(proxy: Gateway) -> str | None:
+ response: Final = httpx.get(
+ str(proxy.client.base_url).rstrip("/") + "/sso/key/generate",
+ follow_redirects=False,
+ trust_env=False,
+ timeout=30,
+ )
+ if not response.is_redirect:
+ assert response.status_code == 200, response.text
+ return None
+ return parse_qs(urlsplit(response.headers["location"]).query)["client_id"][0]
+
+
+def test_an_sso_client_removed_from_db_environment_variables_stops_sign_in_on_every_proxy(
+ gateway: Gateway, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ marker: Final = uuid.uuid4().hex
+ environment_row_client: Final = "environment-row-client-" + marker
+ sso_table_client: Final = "sso-table-client-" + marker
+
+ with scratch_database() as database_url, wire_server(_provider_echoing_its_key("config-file")) as provider:
+ monkeypatch.setenv("DATABASE_URL", database_url)
+ _push_schema_with_environment_variables_revision_trigger()
+ config: Final = _environment_variables_proxy_config(tmp_path, gateway, "sso-" + marker, provider)
+ environment: Final = _environment_variables_proxy_environment(database_url, "process-key-" + marker)
+ removed: Final = (
+ "DATABASE_URL_READ_REPLICA",
+ "GENERIC_CLIENT_ID",
+ "GOOGLE_CLIENT_ID",
+ "GOOGLE_CLIENT_SECRET",
+ "MICROSOFT_CLIENT_ID",
+ "PROXY_BASE_URL",
+ )
+ with (
+ owned_proxy(
+ gateway, tmp_path / "first", environment, config=config, database_setup=(), remove_environment=removed
+ ) as first,
+ owned_proxy(
+ gateway, tmp_path / "peer", environment, config=config, database_setup=(), remove_environment=removed
+ ) as peer,
+ ):
+
+ def sign_in_clients() -> tuple[str | None, str | None]:
+ return (_sign_in_client_id(first), _sign_in_client_id(peer))
+
+ def store_environment_row_client(client_id: str | None, secret: str | None) -> None:
+ response: Final = first.request(
+ "POST",
+ "/config/update",
+ {"environment_variables": {"GOOGLE_CLIENT_ID": client_id, "GOOGLE_CLIENT_SECRET": secret}},
+ )
+ assert response.status_code == 200, response.text
+
+ assert sign_in_clients() == (None, None)
+
+ store_environment_row_client(environment_row_client, "environment-row-secret")
+ eventually(sign_in_clients, lambda clients: clients == (environment_row_client,) * 2, seconds=30)
+
+ store_environment_row_client(None, None)
+ eventually(sign_in_clients, lambda clients: clients == (None, None), seconds=30)
+
+ store_environment_row_client(environment_row_client, "environment-row-secret")
+ eventually(sign_in_clients, lambda clients: clients == (environment_row_client,) * 2, seconds=30)
+ moved: Final = first.request(
+ "PATCH",
+ "/update/sso_settings",
+ {"google_client_id": sso_table_client, "google_client_secret": "sso-table-secret"},
+ )
+ assert moved.status_code == 200, moved.text
+ eventually(sign_in_clients, lambda clients: clients == (sso_table_client,) * 2, seconds=30)
+
+
+_TABLE_ONLY_ROLE_PASSWORD: Final = "integration-table-only-password"
+
+
+@contextmanager
+def _login_role_with_no_sequence_grants() -> Iterator[str]:
+ role: Final = f"integration_table_only_{uuid.uuid4().hex}"
+ with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as admin:
+ admin.execute(
+ sql.SQL("CREATE ROLE {} LOGIN PASSWORD {} NOSUPERUSER NOINHERIT").format(
+ sql.Identifier(role), sql.Literal(_TABLE_ONLY_ROLE_PASSWORD)
+ )
+ )
+ try:
+ yield role
+ finally:
+ admin.execute(sql.SQL("DROP ROLE {}").format(sql.Identifier(role)))
+
+
+def _save_environment_variables_as(database_url: str, values: dict[str, str]) -> None:
+ with psycopg.connect(database_url, autocommit=True) as writer:
+ writer.execute(
+ 'INSERT INTO "LiteLLM_Config" (param_name, param_value) VALUES (%s, %s) '
+ "ON CONFLICT (param_name) DO UPDATE SET param_value = EXCLUDED.param_value",
+ ("environment_variables", Jsonb(values)),
+ )
+
+
+def _environment_variables_revision(database_url: str) -> JsonValue:
+ return read_rows(
+ 'SELECT reload_revision FROM "LiteLLM_Config" WHERE param_name = %s',
+ ("environment_variables",),
+ database_url=database_url,
+ )[0]["reload_revision"]
+
+
+def test_a_database_role_with_no_sequence_grants_can_still_save_db_environment_variables(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ with _login_role_with_no_sequence_grants() as role, scratch_database() as database_url:
+ monkeypatch.setenv("DATABASE_URL", database_url)
+ _push_schema_with_environment_variables_revision_trigger()
+ with psycopg.connect(database_url, autocommit=True) as owner:
+ owner.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(sql.Identifier(role)))
+ owner.execute(
+ sql.SQL("GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public TO {}").format(
+ sql.Identifier(role)
+ )
+ )
+ parsed: Final = urlsplit(database_url)
+ role_url: Final = urlunsplit(
+ parsed._replace(netloc=f"{role}:{_TABLE_ONLY_ROLE_PASSWORD}@{parsed.netloc.rpartition('@')[2]}")
+ )
+
+ _save_environment_variables_as(role_url, {"TABLE_ONLY_ROLE_KEY": "stored"})
+ first: Final = _environment_variables_revision(database_url)
+ _save_environment_variables_as(role_url, {})
+ second: Final = _environment_variables_revision(database_url)
+
+ assert isinstance(first, int) and isinstance(second, int)
+ assert 0 < first < second
+
+
+def test_db_environment_variables_revision_keeps_rising_after_its_sequence_falls_behind_the_row(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ with scratch_database() as database_url:
+ monkeypatch.setenv("DATABASE_URL", database_url)
+ _push_schema_with_environment_variables_revision_trigger()
+ for value in ("first", "second", "third"):
+ _save_environment_variables_as(database_url, {"SEQUENCE_BEHIND_KEY": value})
+ before_the_sequence_restarts: Final = _environment_variables_revision(database_url)
+ with psycopg.connect(database_url, autocommit=True) as owner:
+ owner.execute('ALTER SEQUENCE "litellm_environment_variables_revision_seq" RESTART WITH 1')
+
+ _save_environment_variables_as(database_url, {})
+ after_the_sequence_restarts: Final = _environment_variables_revision(database_url)
+
+ assert isinstance(before_the_sequence_restarts, int) and isinstance(after_the_sequence_restarts, int)
+ assert after_the_sequence_restarts > before_the_sequence_restarts
+
+
+def test_db_environment_variables_saved_from_a_session_outside_the_tables_schema_still_get_a_revision(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ schema: Final = "litellm_tenant"
+ table: Final = sql.SQL('{}."LiteLLM_Config"').format(sql.Identifier(schema))
+ with scratch_database() as database_url:
+ monkeypatch.setenv("DATABASE_URL", f"{database_url}?schema={schema}")
+ _push_schema_with_environment_variables_revision_trigger()
+
+ def save_and_read_revision(values: dict[str, str]) -> object:
+ with psycopg.connect(database_url, autocommit=True) as writer:
+ writer.execute(
+ sql.SQL(
+ "INSERT INTO {} (param_name, param_value) VALUES (%s, %s) "
+ "ON CONFLICT (param_name) DO UPDATE SET param_value = EXCLUDED.param_value"
+ ).format(table),
+ ("environment_variables", Jsonb(values)),
+ )
+ row: Final = writer.execute(
+ sql.SQL("SELECT reload_revision FROM {} WHERE param_name = %s").format(table),
+ ("environment_variables",),
+ ).fetchone()
+ assert row is not None
+ return row[0]
+
+ first: Final = save_and_read_revision({"TENANT_SCHEMA_KEY": "stored"})
+ second: Final = save_and_read_revision({})
+
+ assert isinstance(first, int) and isinstance(second, int)
+ assert 0 < first < second
diff --git a/tests/unit/proxy/db/test_prisma_client.py b/tests/unit/proxy/db/test_prisma_client.py
index 99b500ec315..4b776bfbb1a 100644
--- a/tests/unit/proxy/db/test_prisma_client.py
+++ b/tests/unit/proxy/db/test_prisma_client.py
@@ -1,4 +1,5 @@
import asyncio
+import importlib.resources
import json
import os
import signal
@@ -202,6 +203,19 @@ async def test_recreate_prisma_client_recovers_from_disconnected_client(
DB_PUSH_ARGV = ["db", "push", "--accept-data-loss", "--skip-generate"]
+ENVIRONMENT_VARIABLES_REVISION_TRIGGER_ARGV = [
+ "db",
+ "execute",
+ "--schema",
+ "schema.prisma",
+ "--file",
+ str(
+ importlib.resources.files("litellm_proxy_extras")
+ / "migrations"
+ / "20261015120000_add_environment_variables_revision_trigger"
+ / "migration.sql"
+ ),
+]
def test_db_push_applies_replica_identity_full_when_requested(monkeypatch, fake_prisma_cli, unset_database_url):
@@ -221,7 +235,7 @@ def test_db_push_applies_replica_identity_full_when_requested(monkeypatch, fake_
assert PrismaManager.setup_database(use_migrate=False) is True
- assert fake_prisma_cli.calls == [DB_PUSH_ARGV]
+ assert fake_prisma_cli.calls == [DB_PUSH_ARGV, ENVIRONMENT_VARIABLES_REVISION_TRIGGER_ARGV]
assert applied == [True]
@@ -254,7 +268,7 @@ def test_db_push_proceeds_when_spend_logs_is_not_partitioned(monkeypatch, fake_p
)
assert PrismaManager.setup_database(use_migrate=False) is True
- assert fake_prisma_cli.calls == [DB_PUSH_ARGV]
+ assert fake_prisma_cli.calls == [DB_PUSH_ARGV, ENVIRONMENT_VARIABLES_REVISION_TRIGGER_ARGV]
def _entra_jwt(expires_in_seconds: int) -> str:
@@ -447,7 +461,7 @@ def test_db_push_timeout_takes_its_process_tree_with_it(fake_prisma_cli, unset_d
monkeypatch.setenv("FAKE_PRISMA_HANG_FIRST", "1")
assert PrismaManager.setup_database(use_migrate=False) is True
- assert fake_prisma_cli.calls == [DB_PUSH_ARGV, DB_PUSH_ARGV]
+ assert fake_prisma_cli.calls == [DB_PUSH_ARGV, DB_PUSH_ARGV, ENVIRONMENT_VARIABLES_REVISION_TRIGGER_ARGV]
assert fake_prisma_cli.grandchild_is_gone(within_seconds=5)
diff --git a/tests/unit/proxy/management_endpoints/test_key_management_endpoints.py b/tests/unit/proxy/management_endpoints/test_key_management_endpoints.py
index 57e0a4fc47c..a5ebf41eebd 100644
--- a/tests/unit/proxy/management_endpoints/test_key_management_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_key_management_endpoints.py
@@ -9584,6 +9584,97 @@ async def test_rotate_master_key_reencrypts_model_params_in_place(
), "api_key must be stored re-encrypted under the new master key, not in plaintext"
+async def test_rotate_master_key_keeps_environment_variables_it_cannot_decrypt(monkeypatch):
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock, MagicMock
+
+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
+ from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_if_encrypted_with, encrypt_value_helper
+ from litellm.proxy.management_endpoints.key_management_endpoints import rotate_master_key
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ monkeypatch.setenv("LITELLM_SALT_KEY", "sk-old-master-key")
+ under_another_key = encrypt_value_helper("stored-under-another-key", new_encryption_key="sk-another-master-key")
+ for key in ("ROTATION_TEST_ENCRYPTED", "ROTATION_TEST_PLAINTEXT", "ROTATION_TEST_UNDER_ANOTHER_KEY"):
+ monkeypatch.setenv(key, "restored-by-monkeypatch")
+ monkeypatch.delenv(key)
+ prisma_client = AsyncMock()
+ prisma_client.db = MagicMock()
+ prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ prisma_client.db.litellm_credentialstable.find_many = AsyncMock(return_value=[])
+ prisma_client.db.litellm_config.update = AsyncMock()
+ prisma_client.writer_db.litellm_config.find_many = AsyncMock(
+ return_value=[
+ SimpleNamespace(
+ param_name="environment_variables",
+ param_value={
+ "ROTATION_TEST_ENCRYPTED": encrypt_value_helper("stored-encrypted"),
+ "ROTATION_TEST_PLAINTEXT": "stored-plaintext",
+ "ROTATION_TEST_UNDER_ANOTHER_KEY": under_another_key,
+ },
+ )
+ ]
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_config", ProxyConfig())
+
+ await rotate_master_key(
+ prisma_client=prisma_client,
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876"),
+ current_master_key="sk-old-master-key",
+ new_master_key="sk-new-master-key",
+ )
+
+ stored = prisma_client.db.litellm_config.update.call_args.kwargs["data"]["param_value"].data
+ rotated = decrypt_if_encrypted_with(stored["ROTATION_TEST_ENCRYPTED"], "sk-new-master-key")
+ assert {**stored, "ROTATION_TEST_ENCRYPTED": rotated} == {
+ "ROTATION_TEST_ENCRYPTED": "stored-encrypted",
+ "ROTATION_TEST_PLAINTEXT": "stored-plaintext",
+ "ROTATION_TEST_UNDER_ANOTHER_KEY": under_another_key,
+ }
+
+
+async def test_rotate_master_key_keeps_an_environment_variable_the_read_replica_has_not_caught_up_on(monkeypatch):
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock, MagicMock
+
+ from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
+ from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_if_encrypted_with, encrypt_value_helper
+ from litellm.proxy.management_endpoints.key_management_endpoints import rotate_master_key
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ monkeypatch.setenv("LITELLM_SALT_KEY", "sk-old-master-key")
+ monkeypatch.setenv("ROTATION_TEST_SAVED_A_MOMENT_AGO", "restored-by-monkeypatch")
+ monkeypatch.delenv("ROTATION_TEST_SAVED_A_MOMENT_AGO")
+
+ def rows(values: dict[str, str]) -> list[SimpleNamespace]:
+ return [SimpleNamespace(param_name="environment_variables", param_value=values)]
+
+ prisma_client = AsyncMock()
+ prisma_client.db = MagicMock()
+ prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
+ prisma_client.db.litellm_credentialstable.find_many = AsyncMock(return_value=[])
+ prisma_client.db.litellm_config.update = AsyncMock()
+ prisma_client.db.litellm_config.find_many = AsyncMock(return_value=rows({}))
+ prisma_client.writer_db.litellm_config.find_many = AsyncMock(
+ return_value=rows({"ROTATION_TEST_SAVED_A_MOMENT_AGO": encrypt_value_helper("saved-a-moment-ago")})
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.proxy_config", ProxyConfig())
+
+ await rotate_master_key(
+ prisma_client=prisma_client,
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876"),
+ current_master_key="sk-old-master-key",
+ new_master_key="sk-new-master-key",
+ )
+
+ stored = prisma_client.db.litellm_config.update.call_args.kwargs["data"]["param_value"].data
+ assert {key: decrypt_if_encrypted_with(value, "sk-new-master-key") for key, value in stored.items()} == {
+ "ROTATION_TEST_SAVED_A_MOMENT_AGO": "saved-a-moment-ago"
+ }
+
+
async def test_default_key_generate_params_duration(monkeypatch):
"""
Test that default_key_generate_params with 'duration' is applied
diff --git a/tests/unit/proxy/proxy_server/test_proxy_config.py b/tests/unit/proxy/proxy_server/test_proxy_config.py
index 5fd088acd01..51c84618a74 100644
--- a/tests/unit/proxy/proxy_server/test_proxy_config.py
+++ b/tests/unit/proxy/proxy_server/test_proxy_config.py
@@ -13,7 +13,7 @@ import json
import logging
import os
import re
-from collections.abc import Mapping
+from collections.abc import Awaitable, Callable, Mapping
from contextlib import nullcontext
from dataclasses import dataclass
from datetime import datetime, timedelta
@@ -22,7 +22,9 @@ from types import MappingProxyType, SimpleNamespace
from typing import Any, Dict, Final
from unittest.mock import AsyncMock, MagicMock
+import httpx
import pytest
+from prisma.errors import DataError
from pydantic import JsonValue, TypeAdapter, ValidationError
import litellm
@@ -41,6 +43,7 @@ from litellm.proxy.proxy_server import (
validate_deployment_complexity_router_placement,
validate_deployment_max_agentic_loops,
)
+from litellm.proxy.utils import evict_config_param
from litellm.tracing.config import is_lens_tracing_enabled
from .conftest import normalize
@@ -1483,7 +1486,7 @@ def _install_fake_config_repo(monkeypatch, existing_row):
captured["value"] = json.loads(data["update"]["param_value"])
class _FakeRepo:
- def __init__(self, client):
+ def __init__(self, client, *, use_writer=False):
self.table = _FakeTable()
monkeypatch.setattr("litellm.proxy.proxy_server.ConfigRepository", _FakeRepo)
@@ -1517,6 +1520,27 @@ async def test_ProxyConfig_save_environment_variables_merges_sets_and_deletes(mo
assert "LITELLM_FAVICON_URL" not in written
+async def test_ProxyConfig_save_environment_variables_keeps_a_key_the_read_replica_has_not_caught_up_on(monkeypatch):
+ def config_table(row):
+ return SimpleNamespace(find_first=AsyncMock(return_value=SimpleNamespace(param_value=row)), upsert=AsyncMock())
+
+ writer_table = config_table({"SAVED_A_MOMENT_AGO": "ciphertext-new"})
+ replica_table = config_table({})
+ database = SimpleNamespace(
+ writer_db=SimpleNamespace(litellm_config=writer_table), db=SimpleNamespace(litellm_config=replica_table)
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", database)
+ 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")
+
+ await ProxyConfig().save_environment_variables({"UI_LOGO_PATH": None})
+
+ written = replica_table.upsert.call_args.kwargs["data"]["update"]["param_value"]
+ assert json.loads(written) == {"SAVED_A_MOMENT_AGO": "ciphertext-new"}
+
+
@pytest.mark.asyncio
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
@@ -5078,6 +5102,418 @@ async def test_ProxyConfig_load_config_redacts_secret_litellm_setting_keeps_plai
)
+_REVISION_TEST_KEYS: Final = (
+ "REVISION_TEST_CONFIG_FILE",
+ "REVISION_TEST_DB_ONLY",
+ "REVISION_TEST_NULLED",
+ "REVISION_TEST_KEPT",
+ "revision_test_lower",
+ "REVISION_TEST_LOWER",
+ "GOOGLE_CLIENT_ID",
+ "PROXY_BASE_URL",
+)
+
+
+def _revision_test_environment() -> dict[str, str | None]:
+ return {key: os.environ.get(key) for key in _REVISION_TEST_KEYS}
+
+
+def revision_test_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("LITELLM_SALT_KEY", "sk-proxy-config-test-salt")
+ for key in _REVISION_TEST_KEYS:
+ monkeypatch.setenv(key, "restored-by-monkeypatch")
+ monkeypatch.delenv(key)
+
+
+def _environment_variables_row(
+ values: Mapping[str, str | None] | None, revision: int | None
+) -> SimpleNamespace | None:
+ if values is None:
+ return None
+ return SimpleNamespace(
+ param_name="environment_variables",
+ param_value={key: None if value is None else encrypt_value_helper(value) for key, value in values.items()},
+ reload_revision=revision,
+ )
+
+
+_CONFIG_SECTIONS: Final = ("general_settings", "router_settings", "litellm_settings", "environment_variables")
+
+
+async def _evict_config_rows() -> None:
+ for section in _CONFIG_SECTIONS:
+ await evict_config_param(section)
+
+
+def _config_database(
+ environment_variables_read: Callable[[], Awaitable[SimpleNamespace | None]],
+ writer_find_unique: AsyncMock,
+ other_section_read: Callable[[], Awaitable[None]] | None = None,
+) -> MagicMock:
+ async def get_generic_data(key: str, value: str, table_name: str) -> SimpleNamespace | None:
+ if value == "environment_variables":
+ return await environment_variables_read()
+ return None if other_section_read is None else await other_section_read()
+
+ prisma_client: Final = MagicMock()
+ prisma_client.get_generic_data = get_generic_data
+ prisma_client.writer_db.litellm_config.find_unique = writer_find_unique
+ return prisma_client
+
+
+def _rows_database(cached: SimpleNamespace | None, stored: SimpleNamespace | None) -> MagicMock:
+ async def read_cached() -> SimpleNamespace | None:
+ return cached
+
+ return _config_database(read_cached, AsyncMock(return_value=stored))
+
+
+async def _sync_from(pc: ProxyConfig, prisma_client: MagicMock) -> None:
+ await _evict_config_rows()
+ await pc._update_config_from_db(prisma_client, {}, store_model_in_db=True)
+ await _evict_config_rows()
+
+
+async def _sync_cached_and_stored_environment_variables_rows(
+ pc: ProxyConfig, cached: SimpleNamespace | None, stored: SimpleNamespace | None
+) -> None:
+ await _sync_from(pc, _rows_database(cached, stored))
+
+
+async def _sync_environment_variables_row(
+ pc: ProxyConfig, values: Mapping[str, str | None] | None, revision: int | None
+) -> None:
+ row: Final = _environment_variables_row(values, revision)
+ await _sync_cached_and_stored_environment_variables_rows(pc, cached=row, stored=row)
+
+
+async def _init_non_llm_objects_from_an_empty_database(pc: ProxyConfig) -> None:
+ await _evict_config_rows()
+ await pc._init_non_llm_objects_in_db(prisma_client=_rows_database(None, None))
+ await _evict_config_rows()
+
+
+async def _sync_sso_settings_row(pc: ProxyConfig, values: Mapping[str, str] | None) -> None:
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_ssoconfig.find_unique = AsyncMock(
+ return_value=None
+ if values is None
+ else SimpleNamespace(sso_settings={key: encrypt_value_helper(value) for key, value in values.items()})
+ )
+ await pc._init_sso_settings_in_db(prisma_client=prisma_client)
+
+
[email protected]("revision_test_environment")
+async def test_newer_environment_variables_row_restores_the_keys_it_no_longer_stores(monkeypatch):
+ pc: Final = ProxyConfig()
+ monkeypatch.setenv("REVISION_TEST_CONFIG_FILE", "from-config-file")
+
+ await _sync_environment_variables_row(
+ pc,
+ {
+ "REVISION_TEST_CONFIG_FILE": "from-db",
+ "REVISION_TEST_DB_ONLY": "db-only",
+ "REVISION_TEST_NULLED": "nulled-later",
+ "REVISION_TEST_KEPT": "kept-1",
+ "revision_test_lower": "lower",
+ },
+ revision=1,
+ )
+ assert _revision_test_environment() == {
+ "REVISION_TEST_CONFIG_FILE": "from-db",
+ "REVISION_TEST_DB_ONLY": "db-only",
+ "REVISION_TEST_NULLED": "nulled-later",
+ "REVISION_TEST_KEPT": "kept-1",
+ "revision_test_lower": "lower",
+ "REVISION_TEST_LOWER": "lower",
+ "GOOGLE_CLIENT_ID": None,
+ "PROXY_BASE_URL": None,
+ }
+
+ await _sync_environment_variables_row(
+ pc, {"REVISION_TEST_NULLED": None, "REVISION_TEST_KEPT": "kept-2"}, revision=2
+ )
+ assert _revision_test_environment() == {
+ "REVISION_TEST_CONFIG_FILE": "from-config-file",
+ "REVISION_TEST_DB_ONLY": None,
+ "REVISION_TEST_NULLED": None,
+ "REVISION_TEST_KEPT": "kept-2",
+ "revision_test_lower": None,
+ "REVISION_TEST_LOWER": None,
+ "GOOGLE_CLIENT_ID": None,
+ "PROXY_BASE_URL": None,
+ }
+
+
[email protected]("revision_test_environment")
+async def test_cached_environment_variables_row_older_than_the_stored_one_changes_nothing():
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_KEPT": "newer"}, revision=5)
+
+ await _sync_cached_and_stored_environment_variables_rows(
+ pc,
+ cached=_environment_variables_row(
+ {"REVISION_TEST_KEPT": "older", "REVISION_TEST_DB_ONLY": "older-only"}, revision=4
+ ),
+ stored=_environment_variables_row({"REVISION_TEST_KEPT": "newer"}, revision=5),
+ )
+
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_DB_ONLY")) == ("newer", None)
+
+
[email protected]("revision_test_environment")
[email protected]("cached_revision", [None, 4])
+ "writer_error",
+ [
+ httpx.ConnectError("Can't reach database server"),
+ DataError(
+ {"user_facing_error": {"message": "Error querying the database: FATAL: sorry, too many clients already"}}
+ ),
+ ],
+ ids=["unreachable", "out_of_connections"],
+)
+async def test_a_writer_that_cannot_answer_keeps_the_applied_environment_variables_when_the_cached_row_is_behind(
+ cached_revision, writer_error
+):
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_KEPT": "newer"}, revision=5)
+ cached: Final = _environment_variables_row(
+ {"REVISION_TEST_KEPT": "older", "REVISION_TEST_DB_ONLY": "older-only"}, revision=cached_revision
+ )
+
+ prisma_client: Final = _rows_database(cached, stored=None)
+ prisma_client.writer_db.litellm_config.find_unique = AsyncMock(side_effect=writer_error)
+ prisma_client.attempt_db_reconnect = AsyncMock(return_value=False)
+
+ await _sync_from(pc, prisma_client)
+
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_DB_ONLY")) == ("newer", None)
+
+
[email protected]("revision_test_environment")
+async def test_environment_variables_row_read_before_an_overlapping_newer_sync_is_not_applied_after_it():
+ pc: Final = ProxyConfig()
+ older_values: Final = {"REVISION_TEST_KEPT": "older", "REVISION_TEST_DB_ONLY": "removed-by-the-newer-row"}
+ await _sync_environment_variables_row(pc, older_values, revision=5)
+ older_row: Final = _environment_variables_row(older_values, revision=5)
+ newer_row: Final = _environment_variables_row({"REVISION_TEST_KEPT": "newer"}, revision=6)
+ older_environment_row_read: Final = asyncio.Event()
+ newer_sync_finished: Final = asyncio.Event()
+
+ async def read_older_row() -> SimpleNamespace | None:
+ older_environment_row_read.set()
+ return older_row
+
+ async def wait_for_the_newer_sync() -> None:
+ await newer_sync_finished.wait()
+
+ older_sync: Final = asyncio.create_task(
+ _sync_from(
+ pc, _config_database(read_older_row, AsyncMock(return_value=older_row), wait_for_the_newer_sync)
+ )
+ )
+ await older_environment_row_read.wait()
+ await _sync_from(pc, _rows_database(newer_row, newer_row))
+ newer_sync_finished.set()
+ await older_sync
+
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_DB_ONLY")) == ("newer", None)
+
+
[email protected]("revision_test_environment")
+async def test_older_row_a_later_sync_read_before_a_newer_row_applied_is_not_applied_after_it():
+ pc: Final = ProxyConfig()
+ older_values: Final = {"REVISION_TEST_KEPT": "older", "REVISION_TEST_DB_ONLY": "removed-by-the-newer-row"}
+ await _sync_environment_variables_row(pc, older_values, revision=5)
+ older_row: Final = _environment_variables_row(older_values, revision=5)
+ newer_row: Final = _environment_variables_row({"REVISION_TEST_KEPT": "newer"}, revision=6)
+ later_sync_read_the_older_row: Final = asyncio.Event()
+ earlier_sync_finished: Final = asyncio.Event()
+
+ async def read_newer_row_after_the_later_sync_read() -> SimpleNamespace | None:
+ await later_sync_read_the_older_row.wait()
+ return newer_row
+
+ async def read_older_row() -> SimpleNamespace | None:
+ later_sync_read_the_older_row.set()
+ return older_row
+
+ async def wait_for_the_earlier_sync() -> None:
+ await earlier_sync_finished.wait()
+
+ earlier_sync: Final = asyncio.create_task(
+ _sync_from(pc, _config_database(read_newer_row_after_the_later_sync_read, AsyncMock(return_value=newer_row)))
+ )
+ await asyncio.sleep(0)
+ later_sync: Final = asyncio.create_task(
+ _sync_from(pc, _config_database(read_older_row, AsyncMock(return_value=newer_row), wait_for_the_earlier_sync))
+ )
+ await earlier_sync
+ earlier_sync_finished.set()
+ await later_sync
+
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_DB_ONLY")) == ("newer", None)
+
+
[email protected]("revision_test_environment")
+async def test_writer_row_read_while_an_overlapping_sync_applies_a_newer_row_is_not_applied_after_it():
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_KEPT": "applied"}, revision=5)
+ writer_values: Final = {"REVISION_TEST_KEPT": "writer", "REVISION_TEST_DB_ONLY": "removed-by-the-newest-row"}
+ writer_row: Final = _environment_variables_row(writer_values, revision=6)
+ newest_row: Final = _environment_variables_row({"REVISION_TEST_KEPT": "newest"}, revision=7)
+ writer_read_started: Final = asyncio.Event()
+ earlier_sync_finished: Final = asyncio.Event()
+
+ async def read_newest_row_once_the_writer_read_started() -> SimpleNamespace | None:
+ await writer_read_started.wait()
+ return newest_row
+
+ async def read_cached_row_behind_the_applied_one() -> SimpleNamespace | None:
+ return _environment_variables_row(writer_values, revision=4)
+
+ async def read_writer_row_finished_after_the_earlier_sync(where: Mapping[str, str]) -> SimpleNamespace | None:
+ writer_read_started.set()
+ await earlier_sync_finished.wait()
+ return writer_row
+
+ earlier_sync: Final = asyncio.create_task(
+ _sync_from(
+ pc, _config_database(read_newest_row_once_the_writer_read_started, AsyncMock(return_value=newest_row))
+ )
+ )
+ await asyncio.sleep(0)
+ later_sync: Final = asyncio.create_task(
+ _sync_from(
+ pc,
+ _config_database(
+ read_cached_row_behind_the_applied_one,
+ AsyncMock(side_effect=read_writer_row_finished_after_the_earlier_sync),
+ ),
+ )
+ )
+ await earlier_sync
+ earlier_sync_finished.set()
+ await later_sync
+
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_DB_ONLY")) == ("newest", None)
+
+
[email protected]("revision_test_environment")
+async def test_environment_variables_row_whose_stored_revision_went_backwards_is_applied():
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(
+ pc,
+ {"REVISION_TEST_KEPT": "before-the-restore", "REVISION_TEST_DB_ONLY": "dropped-by-the-restore"},
+ revision=500,
+ )
+
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_KEPT": "restored"}, revision=1)
+
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_DB_ONLY")) == ("restored", None)
+
+
[email protected]("revision_test_environment")
+async def test_environment_variables_row_without_a_revision_only_sets_keys_a_later_revision_can_restore():
+ pc: Final = ProxyConfig()
+
+ await _sync_environment_variables_row(
+ pc, {"REVISION_TEST_KEPT": "kept", "REVISION_TEST_NULLED": "from-an-older-pod"}, revision=None
+ )
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_NULLED")) == (
+ "kept",
+ "from-an-older-pod",
+ )
+
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_KEPT": "kept"}, revision=3)
+ assert (os.environ.get("REVISION_TEST_KEPT"), os.environ.get("REVISION_TEST_NULLED")) == ("kept", None)
+
+
[email protected]("revision_test_environment")
+async def test_stale_environment_variables_row_without_a_revision_cannot_bring_back_a_removed_key():
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_DB_ONLY": "db-only"}, revision=1)
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_DB_ONLY": None}, revision=2)
+
+ await _sync_cached_and_stored_environment_variables_rows(
+ pc,
+ cached=_environment_variables_row({"REVISION_TEST_DB_ONLY": "db-only"}, revision=None),
+ stored=_environment_variables_row({"REVISION_TEST_DB_ONLY": None}, revision=2),
+ )
+
+ assert os.environ.get("REVISION_TEST_DB_ONLY") is None
+
+
[email protected]("revision_test_environment")
+async def test_removed_key_does_not_come_back_with_a_value_set_after_the_first_sync_without_a_row(monkeypatch):
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, None, revision=None)
+
+ monkeypatch.setenv("REVISION_TEST_DB_ONLY", "set-at-runtime")
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_DB_ONLY": "set-at-runtime"}, revision=1)
+ monkeypatch.delenv("REVISION_TEST_DB_ONLY")
+ await _sync_environment_variables_row(pc, {"REVISION_TEST_DB_ONLY": None}, revision=2)
+
+ assert os.environ.get("REVISION_TEST_DB_ONLY") is None
+
+
[email protected]("revision_test_environment")
+async def test_sso_key_only_the_environment_variables_row_stored_is_unset_by_the_next_sso_sync():
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, {"PROXY_BASE_URL": "https://from-the-row"}, revision=1)
+ await _sync_sso_settings_row(pc, None)
+
+ await _sync_environment_variables_row(pc, {"PROXY_BASE_URL": None}, revision=2)
+ await _sync_sso_settings_row(pc, None)
+
+ assert os.environ.get("PROXY_BASE_URL") is None
+
+
[email protected]("revision_test_environment")
+async def test_sso_key_the_sso_settings_table_holds_stays_set_while_the_environment_variables_row_drops_it():
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, {"GOOGLE_CLIENT_ID": "from-the-row"}, revision=1)
+ await _sync_sso_settings_row(pc, {"google_client_id": "from-the-row"})
+
+ await _sync_environment_variables_row(pc, {}, revision=2)
+ set_between_the_two_syncs: Final = os.environ.get("GOOGLE_CLIENT_ID")
+ await _sync_sso_settings_row(pc, {"google_client_id": "from-the-row"})
+
+ assert (set_between_the_two_syncs, os.environ.get("GOOGLE_CLIENT_ID")) == ("from-the-row", "from-the-row")
+
+
[email protected]("revision_test_environment")
+async def test_sso_key_the_environment_variables_row_drops_is_unset_when_sso_settings_are_not_loaded_from_the_db(
+ monkeypatch,
+):
+ from litellm.proxy import proxy_server
+
+ monkeypatch.setattr(proxy_server, "general_settings", {"supported_db_objects": ["models"]})
+ pc: Final = ProxyConfig()
+ await _sync_environment_variables_row(pc, {"GOOGLE_CLIENT_ID": "from-the-row"}, revision=1)
+ await _init_non_llm_objects_from_an_empty_database(pc)
+
+ await _sync_environment_variables_row(pc, {}, revision=2)
+ await _init_non_llm_objects_from_an_empty_database(pc)
+
+ assert os.environ.get("GOOGLE_CLIENT_ID") is None
+
+
# ---------------------------------------------------------------------------
# ProxyConfig agents from config.yaml
# ---------------------------------------------------------------------------
diff --git a/tests/unit/proxy/proxy_server/test_routes_config.py b/tests/unit/proxy/proxy_server/test_routes_config.py
index 2d86ff6a7c2..a92986392e9 100644
--- a/tests/unit/proxy/proxy_server/test_routes_config.py
+++ b/tests/unit/proxy/proxy_server/test_routes_config.py
@@ -51,6 +51,7 @@ def _install_litellm_config(mock_prisma: MagicMock) -> MagicMock:
table.upsert = AsyncMock(return_value=None)
table.delete = AsyncMock()
mock_prisma.db.litellm_config = table
+ mock_prisma.writer_db.litellm_config = table
return table
diff --git a/tests/unit/proxy/test_proxy_server.py b/tests/unit/proxy/test_proxy_server.py
index 80bc3ad1a34..2f2563b9ee4 100644
--- a/tests/unit/proxy/test_proxy_server.py
+++ b/tests/unit/proxy/test_proxy_server.py
@@ -3205,6 +3205,7 @@ async def test_update_config_success_callback_normalization(monkeypatch):
self.db.litellm_config = MagicMock()
self.db.litellm_config.find_first = AsyncMock(side_effect=fake_find_first)
self.db.litellm_config.upsert = AsyncMock(side_effect=fake_upsert)
+ self.writer_db = self.db
monkeypatch.setattr(proxy_server, "prisma_client", MockPrisma())
diff --git a/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py b/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
index e824c5017c6..fbdd8d4d7fb 100644
--- a/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
+++ b/tests/unit/proxy/test_proxy_server_endpoints_and_startup.py
@@ -6691,10 +6691,9 @@ def test_settings_store_uppercases_db_env_vars(monkeypatch):
monkeypatch.delenv(key, raising=False)
proxy_config = ProxyConfig()
- db_values = proxy_config._prepared_db_settings_values(
- "environment_variables", {"dd_api_key": "test-api-key", "dd_site": "us5.datadoghq.com"}
+ proxy_config._apply_db_environment_variables(
+ {"dd_api_key": "test-api-key", "dd_site": "us5.datadoghq.com"}, revision=None, environment_before_db={}, read=1
)
- proxy_config.environment_variables.apply_db_row("environment_variables", db_values)
env_vars = proxy_config.environment_variables.resolved()
assert env_vars["DD_API_KEY"] == "test-api-key"
@@ -9924,10 +9923,22 @@ class _FakeLitellmConfig:
self.upsert_calls.append((name, value))
+class _LaggingReplicaLitellmConfig(_FakeLitellmConfig):
+ def __init__(self, replica_rows, writer):
+ super().__init__(initial_rows=replica_rows)
+ self.upsert = writer.upsert
+
+
class _FakePrismaClient:
- def __init__(self, initial_rows=None):
+ def __init__(self, initial_rows=None, replica_rows=None):
+ self.writer_db = mock.MagicMock()
+ self.writer_db.litellm_config = _FakeLitellmConfig(initial_rows=initial_rows)
self.db = mock.MagicMock()
- self.db.litellm_config = _FakeLitellmConfig(initial_rows=initial_rows)
+ self.db.litellm_config = (
+ self.writer_db.litellm_config
+ if replica_rows is None
+ else _LaggingReplicaLitellmConfig(replica_rows, writer=self.writer_db.litellm_config)
+ )
self.jsonify_object = lambda obj: obj
@@ -9937,8 +9948,8 @@ def _update_config_setup(monkeypatch):
from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth as auth_dep
- def _install(initial_rows=None, store_model_in_db=True):
- prisma = _FakePrismaClient(initial_rows=initial_rows)
+ def _install(initial_rows=None, store_model_in_db=True, replica_rows=None):
+ prisma = _FakePrismaClient(initial_rows=initial_rows, replica_rows=replica_rows)
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma)
monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", store_model_in_db)
monkeypatch.setattr(
@@ -9992,6 +10003,22 @@ def test_update_config_writes_only_sent_section(_update_config_setup):
restore()
+def test_update_config_keeps_an_environment_variable_the_read_replica_has_not_caught_up_on(_update_config_setup):
+ client, prisma, restore = _update_config_setup(
+ initial_rows={"environment_variables": {"SAVED_A_MOMENT_AGO": "enc:new"}},
+ replica_rows={"environment_variables": {}},
+ )
+ try:
+ resp = client.post("/config/update", json={"environment_variables": {"ANOTHER_KEY": "value"}})
+ assert resp.status_code == 200
+ assert prisma.writer_db.litellm_config.rows["environment_variables"] == {
+ "SAVED_A_MOMENT_AGO": "enc:new",
+ "ANOTHER_KEY": "enc:value",
+ }
+ finally:
+ restore()
+
+
def test_update_config_rejects_overlapping_routing_groups_before_writing(_update_config_setup):
existing_groups = [{"group_name": "g1", "models": ["m1"], "routing_strategy": "least-busy"}]
client, prisma, restore = _update_config_setup(
diff --git a/tests/unit/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py b/tests/unit/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py
index da799a307a6..512f58380ea 100644
--- a/tests/unit/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py
+++ b/tests/unit/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py
@@ -646,7 +646,7 @@ class TestProxySettingEndpoints:
mock_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_ssoconfig.upsert = AsyncMock()
mock_prisma.db.litellm_config = MagicMock()
- mock_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_config.update = AsyncMock()
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
@@ -731,7 +731,7 @@ class TestProxySettingEndpoints:
mock_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_ssoconfig.upsert = AsyncMock()
mock_prisma.db.litellm_config = MagicMock()
- mock_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_config.update = AsyncMock()
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
@@ -863,7 +863,7 @@ class TestProxySettingEndpoints:
"PROXY_BASE_URL": "old_proxy_url",
}
)
- mock_prisma.db.litellm_config.find_unique = AsyncMock(
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(
return_value=env_var_entry
)
mock_prisma.db.litellm_config.update = AsyncMock()
@@ -942,7 +942,7 @@ class TestProxySettingEndpoints:
"PROXY_BASE_URL": "old_proxy_url",
}
)
- mock_prisma.db.litellm_config.find_unique = AsyncMock(
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(
return_value=env_var_entry
)
mock_prisma.db.litellm_config.update = AsyncMock()
@@ -1013,7 +1013,7 @@ class TestProxySettingEndpoints:
"MICROSOFT_CLIENT_SECRET": "test_existing_microsoft_secret",
}
)
- mock_prisma.db.litellm_config.find_unique = AsyncMock(
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(
return_value=env_var_entry
)
mock_prisma.db.litellm_config.update = AsyncMock()
@@ -1083,7 +1083,7 @@ class TestProxySettingEndpoints:
mock_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_ssoconfig.upsert = AsyncMock()
mock_prisma.db.litellm_config = MagicMock()
- mock_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_config.update = AsyncMock()
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
@@ -1944,7 +1944,7 @@ class TestProxySettingEndpoints:
mock_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_ssoconfig.upsert = upsert_mock
mock_prisma.db.litellm_config = MagicMock()
- mock_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_config.update = AsyncMock()
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
@@ -2033,7 +2033,7 @@ class TestProxySettingEndpoints:
}
)
mock_prisma.db.litellm_config = MagicMock()
- mock_prisma.db.litellm_config.find_unique = AsyncMock(
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(
return_value=env_var_entry
)
mock_prisma.db.litellm_config.update = AsyncMock()
@@ -2052,7 +2052,7 @@ class TestProxySettingEndpoints:
)
assert response.status_code == 200
- mock_prisma.db.litellm_config.find_unique.assert_called_once()
+ mock_prisma.writer_db.litellm_config.find_unique.assert_called_once()
mock_prisma.db.litellm_config.update.assert_called_once()
update_call = mock_prisma.db.litellm_config.update.call_args
updated_env_vars = json.loads(update_call.kwargs["data"]["param_value"])
@@ -2082,7 +2082,7 @@ class TestProxySettingEndpoints:
"ANOTHER_ENV": "also_keep",
}
mock_prisma.db.litellm_config = MagicMock()
- mock_prisma.db.litellm_config.find_unique = AsyncMock(
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(
return_value=env_var_entry
)
mock_prisma.db.litellm_config.update = AsyncMock()
@@ -2101,12 +2101,44 @@ class TestProxySettingEndpoints:
)
assert response.status_code == 200
- mock_prisma.db.litellm_config.find_unique.assert_called_once()
+ mock_prisma.writer_db.litellm_config.find_unique.assert_called_once()
mock_prisma.db.litellm_config.update.assert_called_once()
update_call = mock_prisma.db.litellm_config.update.call_args
updated_env_vars = json.loads(update_call.kwargs["data"]["param_value"])
assert updated_env_vars == env_var_entry.param_value
+ def test_update_sso_settings_keeps_an_env_var_the_read_replica_has_not_caught_up_on(
+ self, mock_proxy_config, mock_auth, monkeypatch
+ ):
+ import json
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock, MagicMock
+
+ monkeypatch.setenv("LITELLM_SALT_KEY", "test_salt_key")
+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)
+
+ mock_prisma = MagicMock()
+ mock_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=None)
+ mock_prisma.db.litellm_ssoconfig.upsert = AsyncMock()
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(
+ return_value=SimpleNamespace(
+ param_value={"SAVED_A_MOMENT_AGO": "new", "MICROSOFT_CLIENT_ID": "old_microsoft_id"}
+ )
+ )
+ mock_prisma.db.litellm_config.find_unique = AsyncMock(
+ return_value=SimpleNamespace(param_value={"MICROSOFT_CLIENT_ID": "old_microsoft_id"})
+ )
+ mock_prisma.db.litellm_config.update = AsyncMock()
+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
+
+ response = client.patch(
+ "/update/sso_settings", json={"microsoft_client_id": "new_microsoft_id"}
+ )
+
+ assert response.status_code == 200
+ update_call = mock_prisma.db.litellm_config.update.call_args
+ assert json.loads(update_call.kwargs["data"]["param_value"]) == {"SAVED_A_MOMENT_AGO": "new"}
+
def test_get_sso_settings_empty_database(
self, mock_proxy_config, mock_auth, monkeypatch
):
@@ -2248,7 +2280,7 @@ class TestProxySettingEndpoints:
mock_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_ssoconfig.upsert = AsyncMock()
mock_prisma.db.litellm_config = MagicMock()
- mock_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
+ mock_prisma.writer_db.litellm_config.find_unique = AsyncMock(return_value=None)
mock_prisma.db.litellm_config.update = AsyncMock()
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
@@ -2573,7 +2605,7 @@ def test_update_sso_settings_writes_redacted_audit_log(mock_proxy_config, monkey
fake_prisma.db.litellm_ssoconfig.upsert = AsyncMock()
# No prior SSO row, so before_value resolves to None.
fake_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=None)
- fake_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
+ fake_prisma.writer_db.litellm_config.find_unique = AsyncMock(return_value=None)
monkeypatch.setattr(proxy_server_module, "prisma_client", fake_prisma)
monkeypatch.setattr(proxy_server_module, "premium_user", True)
@@ -2645,7 +2677,7 @@ def test_update_sso_settings_audit_captures_redacted_before_snapshot(
"google_client_secret": "OLD-SUPER-SECRET",
}
fake_prisma.db.litellm_ssoconfig.find_unique = AsyncMock(return_value=existing_record)
- fake_prisma.db.litellm_config.find_unique = AsyncMock(return_value=None)
+ fake_prisma.writer_db.litellm_config.find_unique = AsyncMock(return_value=None)
monkeypatch.setattr(proxy_server_module, "prisma_client", fake_prisma)
monkeypatch.setattr(proxy_server_module, "premium_user", True)
diff --git a/tests/unit/proxy/utils/prisma_and_spend/test_config_param_cache.py b/tests/unit/proxy/utils/prisma_and_spend/test_config_param_cache.py
index cdaf5c1ee3b..69b54e5c520 100644
--- a/tests/unit/proxy/utils/prisma_and_spend/test_config_param_cache.py
+++ b/tests/unit/proxy/utils/prisma_and_spend/test_config_param_cache.py
@@ -72,7 +72,7 @@ def test_config_row_dataclass_shape() -> None:
} == {
"param_name": "alpha",
"param_value": {"k": 1},
- "slots": ("param_name", "param_value"),
+ "slots": ("param_name", "param_value", "reload_revision"),
}
@@ -83,12 +83,13 @@ def test_config_row_rejects_unknown_attribute() -> None:
def test_pack_config_row_returns_dict_for_caching() -> None:
- row = SimpleNamespace(param_name="zeta", param_value=[1, 2, 3])
+ row = SimpleNamespace(param_name="zeta", param_value=[1, 2, 3], reload_revision=7)
actual = _pack_config_row(row)
expanded = {**actual, "is_dict": isinstance(actual, dict)}
assert expanded == {
"param_name": "zeta",
"param_value": [1, 2, 3],
+ "reload_revision": 7,
"is_dict": True,
}
@@ -119,6 +120,21 @@ def test_unpack_config_row_round_trips_dict() -> None:
}
+def test_config_row_revision_survives_the_cache_round_trip() -> None:
+ unpacked = _unpack_config_row(
+ _pack_config_row(SimpleNamespace(param_name="environment_variables", param_value={}, reload_revision=42))
+ )
+ assert unpacked is not None and unpacked.reload_revision == 42
+
+
[email protected]("cached_revision", [None, True, "42"])
+def test_unpack_config_row_without_an_integer_revision_has_none(cached_revision: object) -> None:
+ unpacked = _unpack_config_row(
+ {"param_name": "environment_variables", "param_value": {}, "reload_revision": cached_revision}
+ )
+ assert unpacked is not None and unpacked.reload_revision is None
+
+
def test_unpack_config_row_error_on_malformed_dict() -> None:
with pytest.raises(KeyError):
_unpack_config_row({"only_name": "x"})
@@ -168,7 +184,7 @@ async def test_get_config_param_cache_miss_fetches_from_db_and_caches(
}
assert actual == {
"returned": db_row,
- "cached": {"param_name": "p2", "param_value": {"y": 2}},
+ "cached": {"param_name": "p2", "param_value": {"y": 2}, "reload_revision": None},
"db_called": 1,
"db_args": {"key": "param_name", "value": "p2", "table_name": "config"},
}
@@ -251,9 +267,9 @@ async def test_prefetch_config_params_populates_cache_for_each_name(
"c": _swap_config_cache._store[_config_cache_key("c")],
}
assert actual == {
- "a": {"param_name": "a", "param_value": {"av": 1}},
+ "a": {"param_name": "a", "param_value": {"av": 1}, "reload_revision": None},
"b": utils_mod._CONFIG_CACHE_MISS,
- "c": {"param_name": "c", "param_value": [3]},
+ "c": {"param_name": "c", "param_value": [3], "reload_revision": None},
}
diff --git a/tests/unit/test_router_retry_policy_update.py b/tests/unit/test_router_retry_policy_update.py
index 918d215c89f..6ab672d7b04 100644
--- a/tests/unit/test_router_retry_policy_update.py
+++ b/tests/unit/test_router_retry_policy_update.py
@@ -430,6 +430,7 @@ async def test_config_update_persists_and_reads_back_retry_policy(monkeypatch):
fake_table = _FakeConfigTable()
prisma_client = MagicMock()
prisma_client.db.litellm_config = fake_table
+ prisma_client.writer_db = prisma_client.db
async def _apply_router_settings(*args, **kwargs):
await proxy_server.proxy_config._add_router_settings_from_db_config(