The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): stop leaking master_key and database_url in startup DEBUG logs
yucheng-berriai680f15f1e3f9
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex a29acf3b06f..eda7a1b507a 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -63,6 +63,7 @@ from litellm.litellm_core_utils.litellm_logging import (_init_custom_logger_compatible_class,)from litellm.litellm_core_utils.safe_json_dumps import safe_dumps+from litellm.litellm_core_utils.safe_json_loads import safe_json_loadsfrom litellm.proxy._types import (UI_TEAM_ID,CallbackDelete,@@ -637,6 +638,65 @@ premium_user_data: Optional["EnterpriseLicenseData"] = _license_check.airgapped_global_max_parallel_request_retries_env: Optional[str] = os.getenv("LITELLM_GLOBAL_MAX_PARALLEL_REQUEST_RETRIES")proxy_state = ProxyState()SENSITIVE_DATA_MASKER = SensitiveDataMasker()+++# Secret-bearing general_settings fields the segment masker does not match by+# name: database_url and database_extra_connection_params embed DB credentials,+# pass_through_endpoints carry upstream Authorization headers, and+# alert_to_webhook_url is itself a webhook secret+_EXTRA_SECRET_GENERAL_SETTINGS_FIELDS = frozenset(+ {+ "database_url",+ "database_extra_connection_params",+ "pass_through_endpoints",+ "alert_to_webhook_url",+ }+)+++_EXTRA_SECRET_MASK = "REDACTED"+++def _redact_config_dict_for_logging(data: dict[str, object]) -> dict[str, object]:+ """Mask secret-bearing entries in a proxy config-shaped dict.++ Combines the segment-matching masker (catches `master_key`, `api_key`,+ `*_token`, etc.) with an explicit whole-value replacement for the+ URL/webhook fields that embed credentials but do not contain any+ sensitive-pattern segment (e.g. `database_url` splits into+ `['database', 'url']`, so segment matching misses it). The whole-value+ replacement covers non-string shapes (`alert_to_webhook_url` is a dict,+ `pass_through_endpoints` is a list), which the string-only+ `mask_sensitive_keys` helper would otherwise pass through unchanged.+ """+ segment_masked = SENSITIVE_DATA_MASKER.mask_dict(data)+ return {+ key: _EXTRA_SECRET_MASK if key in _EXTRA_SECRET_GENERAL_SETTINGS_FIELDS and value is not None else value+ for key, value in segment_masked.items()+ }+++def _redact_worker_config_for_logging(worker_config: str | dict[str, object] | None) -> str | dict[str, object] | None:+ """Mask sensitive fields in the worker config before it enters a log record.++ `worker_config` reaches `proxy_startup_event` as either the JSON blob+ persisted by `save_worker_config` (a string) or the dict passed directly+ to `initialize`. Both shapes can carry `master_key`, `database_url`,+ provider API keys, etc.; passing the raw value to `verbose_proxy_logger`+ leaks them whenever the last-line-of-defense regex filter is bypassed+ (`LITELLM_DISABLE_REDACT_SECRETS=true`, an older log sink, a downstream+ handler that captures records pre-filter). Redact at the source.+ """+ if worker_config is None:+ return None+ if isinstance(worker_config, dict):+ return _redact_config_dict_for_logging(worker_config)+ parsed = safe_json_loads(worker_config, default=None)+ if isinstance(parsed, dict):+ return safe_dumps(_redact_config_dict_for_logging(parsed))+ return worker_config++if global_max_parallel_request_retries_env is None:global_max_parallel_request_retries: int = 3else:@@ -833,7 +893,7 @@ async def proxy_startup_event(app: FastAPI):### LOAD CONFIG ###worker_config: Optional[Union[str, dict]] = get_secret("WORKER_CONFIG") # type: ignoreenv_config_yaml: Optional[str] = get_secret_str("CONFIG_FILE_PATH")- verbose_proxy_logger.debug("worker_config: %s", worker_config)+ verbose_proxy_logger.debug("worker_config: %s", _redact_worker_config_for_logging(worker_config))# check if it's a valid file pathif env_config_yaml is not None:if os.path.isfile(env_config_yaml) and proxy_config.is_yaml(config_file_path=env_config_yaml):@@ -4336,9 +4396,9 @@ class ProxyConfig:### CONNECT TO DATABASE ###database_url = general_settings.get("database_url", None)if database_url and database_url.startswith("os.environ/"):- verbose_proxy_logger.debug("GOING INTO LITELLM.GET_SECRET!")+ verbose_proxy_logger.debug("Resolving database_url via secret manager")database_url = get_secret(database_url)- verbose_proxy_logger.debug("RETRIEVED DB URL: %s", database_url)+ verbose_proxy_logger.debug("Resolved database_url from secret manager")### MASTER KEY ###master_key = general_settings.get("master_key", get_secret("LITELLM_MASTER_KEY", None))@@ -4738,7 +4798,7 @@ class ProxyConfig:"""_alerting_callbacks = general_settings.get("alerting", None)- verbose_proxy_logger.debug(f"_alerting_callbacks: {general_settings}")+ verbose_proxy_logger.debug("_alerting_callbacks: %s", _alerting_callbacks)if _alerting_callbacks is None:return@@ -14218,20 +14278,6 @@ async def update_config_general_settings(return response-# Secret-bearing general_settings fields the segment masker does not match by-# name: database_url and database_extra_connection_params embed DB credentials,-# pass_through_endpoints carry upstream Authorization headers, and-# alert_to_webhook_url is itself a webhook secret-_EXTRA_SECRET_GENERAL_SETTINGS_FIELDS = frozenset(- {- "database_url",- "database_extra_connection_params",- "pass_through_endpoints",- "alert_to_webhook_url",- }-)--def _is_secret_general_setting_field(field_name: str) -> bool:return field_name in _EXTRA_SECRET_GENERAL_SETTINGS_FIELDS or SENSITIVE_DATA_MASKER.is_sensitive_key(field_name)diff --git a/tests/test_litellm/proxy/proxy_server/test_lifecycle.py b/tests/test_litellm/proxy/proxy_server/test_lifecycle.pyindex 9343dcbc29f..842b372ba83 100644--- a/tests/test_litellm/proxy/proxy_server/test_lifecycle.py+++ b/tests/test_litellm/proxy/proxy_server/test_lifecycle.py@@ -212,6 +212,108 @@ def test_save_worker_config_invalid_no_kwargs_yields_empty(monkeypatch):assert os.environ["WORKER_CONFIG"] == "{}"+# ---------------------------------------------------------------------------+# _redact_worker_config_for_logging (LIT-4152)+# ---------------------------------------------------------------------------+++_LIT4152_SECRETS = (+ "sk-lit4152-regression-master-key-abcdef1234567890",+ "leak_password_9090",+ "sk-lit4152-provider-api-key-abcdef",+ "postgresql://leak_user:[email protected]:5432/leak_db",+)+++def _lit4152_worker_config_dict():+ return {+ "model": "openai/gpt-4o-mini",+ "config": "/tmp/c.yaml",+ "master_key": _LIT4152_SECRETS[0],+ "database_url": _LIT4152_SECRETS[3],+ "api_key": _LIT4152_SECRETS[2],+ "telemetry": True,+ }+++def test__redact_worker_config_for_logging_dict_masks_all_secret_shapes():+ """LIT-4152 regression: dict-form worker_config must not embed any raw+ secret. Covers the segment-matched fields (`master_key`, `api_key`) and the+ URL-with-credentials field (`database_url`), which the segment masker+ misses because neither segment matches its sensitive-pattern set.+ """+ from litellm.proxy.proxy_server import _redact_worker_config_for_logging++ redacted = _redact_worker_config_for_logging(_lit4152_worker_config_dict())+ rendered = repr(redacted)+ for secret in _LIT4152_SECRETS:+ assert secret not in rendered, f"leak: {secret} in {rendered!r}"+ assert isinstance(redacted, dict)+ assert redacted["model"] == "openai/gpt-4o-mini"+ assert redacted["telemetry"] is True+++def test__redact_worker_config_for_logging_json_string_round_trips_masked():+ """Docker/K8s deployments hand the proxy a JSON string via ``WORKER_CONFIG``.+ Confirm the string path also masks and that the returned value re-parses+ into a dict with the sensitive fields masked.+ """+ from litellm.proxy.proxy_server import _redact_worker_config_for_logging++ payload = json.dumps(_lit4152_worker_config_dict())+ redacted = _redact_worker_config_for_logging(payload)+ assert isinstance(redacted, str)+ for secret in _LIT4152_SECRETS:+ assert secret not in redacted, f"leak: {secret} in {redacted!r}"+ parsed = json.loads(redacted)+ assert parsed["model"] == "openai/gpt-4o-mini"+++def test__redact_worker_config_for_logging_passthrough_for_none_and_non_json_string():+ """Non-dict, non-JSON-parseable string is passed through verbatim (nothing+ to mask) and ``None`` returns ``None``.+ """+ from litellm.proxy.proxy_server import _redact_worker_config_for_logging++ assert _redact_worker_config_for_logging(None) is None+ assert _redact_worker_config_for_logging("/tmp/some_config.yaml") == "/tmp/some_config.yaml"+++def test__redact_config_dict_for_logging_masks_non_string_url_webhook_values():+ """The URL/webhook fields the segment masker cannot catch by key name+ (``alert_to_webhook_url``, ``pass_through_endpoints``,+ ``database_extra_connection_params``) can hold non-string shapes:+ ``alert_to_webhook_url`` is typed as ``Optional[Dict]`` and can nest+ secret query params under keys the segment masker also misses. Confirm+ the whole value is replaced regardless of shape so a nested webhook or+ Bearer token under a non-segment-matched key does not slip through.+ """+ from litellm.proxy.proxy_server import _redact_config_dict_for_logging++ nested_webhook_secret = "https://hooks.slack.com/services/T0/B0/nested-webhook-secret-xyz"+ data = {+ "master_key": "sk-should-be-masked",+ "alert_to_webhook_url": {"budget_alerts": nested_webhook_secret},+ "pass_through_endpoints": [+ {+ "path": "/upstream",+ "target": "https://api.provider.com",+ "headers": {"Authorization": "Bearer nested-token-should-be-gone"},+ }+ ],+ "database_extra_connection_params": {"password": "extra-db-password-abc"},+ }+ redacted = _redact_config_dict_for_logging(data)+ rendered = repr(redacted)+ for secret in (+ "sk-should-be-masked",+ nested_webhook_secret,+ "nested-token-should-be-gone",+ "extra-db-password-abc",+ ):+ assert secret not in rendered, f"leak: {secret} in {rendered!r}"++# ---------------------------------------------------------------------------# initialize# ---------------------------------------------------------------------------diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.pyindex 196ff045208..78ec2813c61 100644--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py@@ -784,6 +784,70 @@ def test_ProxyConfig__load_alerting_settings_invalid_alerting_raises():pc._load_alerting_settings({"alerting": 12345})+def test_ProxyConfig__load_alerting_settings_does_not_log_general_settings_dict(monkeypatch):+ """Regression for LIT-4152.++ ``_load_alerting_settings`` used to log ``general_settings`` verbatim in a+ line labelled ``_alerting_callbacks:``, leaking ``master_key``,+ ``database_url``, and any other secret sitting in ``general_settings`` in+ cleartext at DEBUG. The fix logs only the alerting callback list.++ The regression check runs with the last-line-of-defense regex scrubber+ (``SecretRedactionFilter``) DISABLED, since defense in depth is the point.+ The caller must not construct the leaky string, so consumers of the log+ stream that bypass the module filter (versions before it existed,+ ``LITELLM_DISABLE_REDACT_SECRETS=true`` operators, downstream handlers+ that snapshot the record pre-filter) still do not see the secret. Uses a+ dedicated handler rather than caplog because caplog is unreliable under+ pytest-xdist.+ """+ import logging++ import litellm._logging as _logging_module+ from litellm._logging import verbose_proxy_logger++ monkeypatch.setattr(_logging_module, "_ENABLE_SECRET_REDACTION", False)++ class LogRecordHandler(logging.Handler):+ def __init__(self) -> None:+ super().__init__()+ self.records: list[logging.LogRecord] = []++ def emit(self, record: logging.LogRecord) -> None:+ self.records.append(record)++ master_key_secret = "sk-lit4152-regression-master-key-abcdef1234567890"+ db_url_secret = "postgresql://leak_user:[email protected]:5432/leak_db"+ settings = {+ "alerting": ["slack"],+ "alerting_threshold": 300,+ "master_key": master_key_secret,+ "database_url": db_url_secret,+ }++ handler = LogRecordHandler()+ handler.setLevel(logging.DEBUG)+ original_level = verbose_proxy_logger.level+ verbose_proxy_logger.setLevel(logging.DEBUG)+ verbose_proxy_logger.addHandler(handler)+ try:+ try:+ ProxyConfig()._load_alerting_settings(settings)+ except Exception:+ pass # downstream init may fail without full env; the debug log fires first+ rendered = " ".join(record.getMessage() for record in handler.records)+ finally:+ verbose_proxy_logger.removeHandler(handler)+ verbose_proxy_logger.setLevel(original_level)++ assert master_key_secret not in rendered, f"master_key leaked in logs: {rendered!r}"+ assert db_url_secret not in rendered, f"database_url leaked in logs: {rendered!r}"+ assert "leak_password_9090" not in rendered+ assert any("['slack']" in r.getMessage() for r in handler.records), (+ f"expected the alerting callback list to appear in a debug record; got {[r.getMessage() for r in handler.records]!r}"+ )++# ---------------------------------------------------------------------------# ProxyConfig.initialize_secret_manager# ---------------------------------------------------------------------------