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
feat(proxy): audit default user settings updates (#31753)
yucheng-berri2860dad51457
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 5fe17d79ab5..a6ef7de07ae 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -189,6 +189,7 @@ class LitellmTableNames(str, enum.Enum):TOOL_TABLE_NAME = "LiteLLM_ToolTable"CACHE_CONFIG_TABLE_NAME = "LiteLLM_CacheConfig"CONFIG_OVERRIDES_TABLE_NAME = "LiteLLM_ConfigOverrides"+ CONFIG_TABLE_NAME = "LiteLLM_Config"class Litellm_EntityType(enum.Enum):diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 57814de6e3f..0158f601d32 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -425,7 +425,10 @@ from litellm.proxy.management_endpoints.user_agent_analytics_endpoints import (from litellm.proxy.management_endpoints.workflow_management_endpoints import (router as workflow_management_router,)-from litellm.proxy.management_helpers.audit_logs import create_audit_log_for_update+from litellm.proxy.management_helpers.audit_logs import (+ create_audit_log_for_update,+ create_object_audit_log,+)from litellm.proxy.memory.memory_endpoints import router as memory_routerfrom litellm.proxy.plugin_routes import (router as plugin_router,@@ -14228,6 +14231,47 @@ def _redact_general_setting_value(field_name: str, value: JsonValue, is_full_admreturn value+def _dump_redacted_config(value: Optional[JsonValue], *, redact_all_values: bool = False) -> Optional[str]:+ # `default=str` matches the sibling audit-log serializers in+ # team_endpoints.py and the LiteLLM_AuditLogs validator, so a YAML-loaded+ # value with a non-JSON-native leaf (datetime, custom object) cannot turn+ # an audit write into a 500.+ if value is None:+ return None+ if redact_all_values and isinstance(value, dict):+ return json.dumps({key: "REDACTED" for key in value}, default=str)+ return json.dumps(_redact_secret_values_in_obj(value), default=str)+++async def create_config_audit_log(+ param_name: str,+ action: AUDIT_ACTIONS,+ before_value: Optional[JsonValue],+ after_value: Optional[JsonValue],+ user_api_key_dict: UserAPIKeyAuth,+ table_name: LitellmTableNames = LitellmTableNames.CONFIG_TABLE_NAME,+) -> None:+ """Record a system-wide settings change in LiteLLM_AuditLog.++ Secret leaves are redacted before the row is written. environment_variables+ hold arbitrary credentials under non-secret-looking uppercase keys (e.g.+ DATABASE_URL), so every value in that section is redacted rather than+ relying on key-name matching; other sections reuse the same matcher+ /config/field/info applies for non-admins.+ """+ redact_all_values = param_name == "environment_variables"+ await create_object_audit_log(+ object_id=param_name,+ action=action,+ table_name=table_name,+ before_value=_dump_redacted_config(before_value, redact_all_values=redact_all_values),+ after_value=_dump_redacted_config(after_value, redact_all_values=redact_all_values),+ user_api_key_dict=user_api_key_dict,+ litellm_changed_by=None,+ litellm_proxy_admin_name=LITELLM_PROXY_ADMIN_NAME,+ )++@router.get("/config/field/info",tags=["config.yaml"],diff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.pyindex e4f68a1e9db..1be17c86123 100644--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py@@ -1,4 +1,5 @@#### CRUD ENDPOINTS for UI Settings #####+import asyncioimport jsonfrom typing import Any, Dict, List, Optional, Set, Tuple, Type, Unionfrom urllib.parse import urlparse@@ -553,6 +554,7 @@ async def _update_litellm_setting(settings: Union[DefaultInternalUserParams, DefaultTeamSSOParams, MCPSemanticFilterSettings],settings_key: str,success_message: str,+ user_api_key_dict: Optional[UserAPIKeyAuth] = None,):"""Common utility function to update `litellm_settings` in both memory and config.@@ -561,8 +563,15 @@ async def _update_litellm_setting(settings: The settings object to updatesettings_key: The key in litellm_settings to updatesuccess_message: Message to return on success+ user_api_key_dict: The acting admin, recorded as the audit-log actor.+ Optional today so callers that have not been wired for auditing+ keep working; the audit row is only written when an actor is passed."""- from litellm.proxy.proxy_server import proxy_config, store_model_in_db+ from litellm.proxy.proxy_server import (+ create_config_audit_log,+ proxy_config,+ store_model_in_db,+ )if store_model_in_db is not True:raise HTTPException(@@ -576,6 +585,7 @@ async def _update_litellm_setting(# because get_config() may overwrite litellm.<key> with stale DB values# via LITELLM_SETTINGS_SAFE_DB_OVERRIDES.config = await proxy_config.get_config()+ before_value = config.get("litellm_settings", {}).get(settings_key)# Update the in-memory settings (after get_config to avoid stale override)setattr(litellm, settings_key, in_memory_var)@@ -589,6 +599,21 @@ async def _update_litellm_setting(# Save the updated configawait proxy_config.save_config(new_config=config)+ if user_api_key_dict is not None:+ # Fire-and-forget so an audit-log failure (transient DB blip, etc.)+ # never surfaces as a 500 after save_config has already committed,+ # matching the create_object_audit_log pattern used elsewhere+ # (e.g. model_management_endpoints).+ asyncio.create_task(+ create_config_audit_log(+ param_name=settings_key,+ action="updated",+ before_value=before_value,+ after_value=in_memory_var,+ user_api_key_dict=user_api_key_dict,+ )+ )+return {"message": success_message,"status": "success",@@ -619,6 +644,7 @@ async def update_internal_user_settings(settings=settings,settings_key="default_internal_user_params",success_message="Internal user settings updated successfully",+ user_api_key_dict=user_api_key_dict,)diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex 019a7dc90d2..dc35d71ccbd 100644--- a/tests/test_litellm/proxy/test_proxy_server.py+++ b/tests/test_litellm/proxy/test_proxy_server.py@@ -8658,3 +8658,109 @@ def test_config_field_info_returns_raw_secrets_for_full_admin(monkeypatch):)finally:app.dependency_overrides.clear()+++def _fake_prisma_with_config(existing_param_value):+ """MagicMock prisma whose litellm_config row returns existing_param_value and+ whose litellm_auditlog.create records the written audit row."""+ fake = MagicMock()+ config_row = MagicMock()+ config_row.param_value = existing_param_value+ fake.db.litellm_config.find_first = AsyncMock(return_value=config_row)+ fake.db.litellm_config.upsert = AsyncMock(return_value=config_row)+ fake.db.litellm_auditlog.create = AsyncMock()+ return fake+++def test_dump_redacted_config_redacts_secret_leaves():+ from litellm.proxy.proxy_server import _dump_redacted_config++ assert _dump_redacted_config(None) is None++ restored = json.loads(+ _dump_redacted_config(+ {+ "api_key": "sk-leak",+ "model": "gpt-4",+ "nested": {"aws_secret_access_key": "abc", "region": "us-east-1"},+ }+ )+ )+ assert restored["api_key"] == "REDACTED"+ assert restored["model"] == "gpt-4"+ assert restored["nested"]["aws_secret_access_key"] == "REDACTED"+ assert restored["nested"]["region"] == "us-east-1"+++async def test_create_config_audit_log_writes_redacted_entry(monkeypatch):+ import litellm.proxy.proxy_server as proxy_server_module+ from litellm.proxy._types import LitellmTableNames+ from litellm.proxy.proxy_server import create_config_audit_log++ fake = _fake_prisma_with_config({})+ monkeypatch.setattr(proxy_server_module, "prisma_client", fake)+ monkeypatch.setattr(proxy_server_module, "premium_user", True)+ monkeypatch.setattr(litellm, "store_audit_logs", True)++ caller = UserAPIKeyAuth(api_key="hashed-key-abc", user_id="admin-7")+ await create_config_audit_log(+ "router_settings",+ "updated",+ {"routing_strategy": "simple-shuffle", "api_key": "sk-old"},+ {"routing_strategy": "latency-based", "api_key": "sk-new"},+ caller,+ )++ fake.db.litellm_auditlog.create.assert_awaited_once()+ written = fake.db.litellm_auditlog.create.call_args.kwargs["data"]+ assert written["table_name"] == LitellmTableNames.CONFIG_TABLE_NAME.value+ assert written["object_id"] == "router_settings"+ assert written["action"] == "updated"+ assert written["changed_by"] == "admin-7"+ assert written["changed_by_api_key"] == "hashed-key-abc"++ before = json.loads(written["before_value"])+ after = json.loads(written["updated_values"])+ assert before["routing_strategy"] == "simple-shuffle"+ assert after["routing_strategy"] == "latency-based"+ assert "sk-old" not in written["before_value"]+ assert "sk-new" not in written["updated_values"]+ assert before["api_key"] != "sk-old"+ assert after["api_key"] != "sk-new"+++async def test_create_config_audit_log_noop_when_store_audit_logs_disabled(monkeypatch):+ import litellm.proxy.proxy_server as proxy_server_module+ from litellm.proxy.proxy_server import create_config_audit_log++ fake = _fake_prisma_with_config({})+ monkeypatch.setattr(proxy_server_module, "prisma_client", fake)+ monkeypatch.setattr(proxy_server_module, "premium_user", True)+ monkeypatch.setattr(litellm, "store_audit_logs", False)++ await create_config_audit_log(+ "router_settings",+ "updated",+ {},+ {"a": 1},+ UserAPIKeyAuth(api_key="k", user_id="u"),+ )+ fake.db.litellm_auditlog.create.assert_not_called()+++def test_dump_redacted_config_serializes_non_json_native_values():+ """YAML-loaded config can contain datetime/date/custom values that plain+ json.dumps refuses. Without default=str the audit write turns into a 500+ after the config change has already committed; the sibling audit-log+ serializers in team_endpoints.py use default=str for the same reason."""+ from datetime import datetime, timezone++ from litellm.proxy.proxy_server import _dump_redacted_config++ out = _dump_redacted_config({"updated_at": datetime(2026, 6, 30, tzinfo=timezone.utc)})+ assert out is not None+ restored = json.loads(out)+ assert "2026-06-30" in restored["updated_at"]+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 ae217aca16e..7a586f758f4 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@@ -1869,3 +1869,94 @@ class TestProxySettingEndpoints:assert "field_schema" in dataassert "properties" in data["field_schema"]assert "role_mappings" in data["field_schema"]["properties"]+++def test_update_internal_user_settings_writes_audit_log(mock_proxy_config, monkeypatch):+ """Regression for the reported scenario: an admin changes Default User+ Settings from the dashboard, which issues PATCH /update/internal_user_settings+ (NOT /config/update). An audit row must record who changed it and what+ changed."""+ from unittest.mock import AsyncMock, MagicMock++ import litellm+ import litellm.proxy.proxy_server as proxy_server_module+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth++ audit_create = AsyncMock()+ fake_prisma = MagicMock()+ fake_prisma.db.litellm_auditlog.create = audit_create++ monkeypatch.setattr(proxy_server_module, "prisma_client", fake_prisma)+ monkeypatch.setattr(proxy_server_module, "premium_user", True)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)+ monkeypatch.setattr(litellm, "store_audit_logs", True)+ monkeypatch.setattr(litellm, "default_internal_user_params", {})++ async def _admin_auth():+ return UserAPIKeyAuth(+ user_id="audit-admin",+ api_key="hashed-admin-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ )++ app.dependency_overrides[user_api_key_auth] = _admin_auth+ try:+ resp = client.patch(+ "/update/internal_user_settings",+ json={"max_budget": 999.0, "models": ["gpt-4"]},+ )+ assert resp.status_code == 200, resp.text++ audit_create.assert_awaited_once()+ written = audit_create.await_args.kwargs["data"]+ assert written["object_id"] == "default_internal_user_params"+ assert written["action"] == "updated"+ assert written["table_name"] == "LiteLLM_Config"+ assert written["changed_by"] == "audit-admin"+ assert written["changed_by_api_key"] == "hashed-admin-key"++ before = json.loads(written["before_value"])+ after = json.loads(written["updated_values"])+ assert before["max_budget"] == 100.0+ assert after["max_budget"] == 999.0+ finally:+ app.dependency_overrides.pop(user_api_key_auth, None)+++def test_update_internal_user_settings_returns_200_when_audit_write_raises(+ mock_proxy_config, monkeypatch+):+ """The settings change is already committed by save_config, so an+ audit-log failure must never surface as a 500. Scheduling via+ asyncio.create_task keeps the audit call off the request path; this+ test asserts that contract by making the audit helper raise."""+ import litellm+ import litellm.proxy.proxy_server as proxy_server_module+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.proxy.auth.user_api_key_auth import user_api_key_auth++ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)+ monkeypatch.setattr(litellm, "default_internal_user_params", {})++ async def _raise(**_kwargs):+ raise RuntimeError("audit prisma blip")++ monkeypatch.setattr(proxy_server_module, "create_config_audit_log", _raise)++ async def _admin_auth():+ return UserAPIKeyAuth(+ user_id="audit-admin",+ api_key="hashed-admin-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ )++ app.dependency_overrides[user_api_key_auth] = _admin_auth+ try:+ resp = client.patch(+ "/update/internal_user_settings", json={"max_budget": 42.0}+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["status"] == "success"+ finally:+ app.dependency_overrides.pop(user_api_key_auth, None)