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/db): translate libpq sslrootcert and verify-* into Prisma's strict TLS params (#39563)

devin-ai-integration[bot]a0f44af838bb
diff --git a/litellm/proxy/db/db_url_settings.py b/litellm/proxy/db/db_url_settings.py
index 01f66e4f3c5..f28e505246a 100644
--- a/litellm/proxy/db/db_url_settings.py
+++ b/litellm/proxy/db/db_url_settings.py
@@ -124,6 +124,42 @@ def add_missing_query_params(url: str, params: Mapping[str, str | int | float])
return urllib.parse.urlunsplit(parsed._replace(query=query))
+LIBPQ_VERIFY_SSLMODES: Final[frozenset[str]] = frozenset({"verify-ca", "verify-full"})
+
+
+def translate_libpq_ssl_params(url: str) -> str:
+ """Rewrite libpq's certificate-verification params into Prisma's dialect.
+
+ Prisma's engine only knows ``sslmode=disable|prefer|require``, ``sslcert``
+ (the CA bundle) and ``sslaccept=strict``. It silently discards
+ ``sslrootcert`` and downgrades ``sslmode=verify-ca`` / ``verify-full`` to
+ ``prefer``, so a URL copied from libpq / RDS docs connects over TLS with no
+ certificate check at all. ``verify-ca`` and ``verify-full`` both become
+ ``require`` (Prisma has no CA-only mode), ``sslrootcert`` becomes
+ ``sslcert``, and either one turns on ``sslaccept=strict`` (chain and
+ hostname), matching libpq where a root cert makes ``require`` verify.
+ Prisma params the operator pinned themselves win; anything else is left
+ untouched.
+ """
+ parsed: Final = urllib.parse.urlsplit(url)
+ pairs: Final = tuple(urllib.parse.parse_qsl(parsed.query, keep_blank_values=True))
+ keys: Final = frozenset(key for key, _ in pairs)
+ wants_verify: Final = any(key == "sslmode" and value in LIBPQ_VERIFY_SSLMODES for key, value in pairs)
+ if not wants_verify and "sslrootcert" not in keys:
+ return url
+ translated: Final = tuple(
+ ("sslmode", "require") if key == "sslmode" and value in LIBPQ_VERIFY_SSLMODES else (key, value)
+ for key, value in pairs
+ if key != "sslrootcert"
+ )
+ root_cert: Final = tuple(
+ ("sslcert", value) for key, value in pairs if key == "sslrootcert" and "sslcert" not in keys
+ )
+ strict: Final = () if "sslaccept" in keys else (("sslaccept", "strict"),)
+ query: Final = urllib.parse.urlencode(translated + root_cert + strict)
+ return urllib.parse.urlunsplit(parsed._replace(query=query))
+
+
def reader_shareable_params(params: Mapping[str, str | int | float]) -> Mapping[str, str | int | float]:
"""Return the subset of ``params`` the read replica is allowed to inherit."""
return MappingProxyType({key: value for key, value in params.items() if key in CONNECTION_PARAM_KEYS})
@@ -403,6 +439,11 @@ class DatabaseURLSettings(BaseSettings):
self._raise_for_unsupported_scheme()
wrote_writer: Final = self.apply_writer_url_to_env()
+ for env_var in ("DATABASE_URL", "DIRECT_URL"):
+ url = os.environ.get(env_var)
+ if url:
+ os.environ[env_var] = translate_libpq_ssl_params(url)
+
# DATABASE_DISABLE_PREPARED_STATEMENTS maps to Prisma's `pgbouncer=true`
# URL param, same as the CLI's `database_disable_prepared_statements`
# config key. An explicit `pgbouncer` value already on the URL wins.
@@ -418,7 +459,7 @@ class DatabaseURLSettings(BaseSettings):
reader_url: Final = self.build_reader_url() or self.database_url_read_replica
if reader_url is not None:
os.environ["DATABASE_URL_READ_REPLICA"] = add_missing_query_params(
- reader_url,
+ translate_libpq_ssl_params(reader_url),
connection_params_from_url(os.environ.get("DATABASE_URL", "")),
)
diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.py
index ed247d52ce2..e780beb4410 100644
--- a/litellm/proxy/proxy_cli.py
+++ b/litellm/proxy/proxy_cli.py
@@ -1228,6 +1228,7 @@ def run_server(
add_missing_query_params,
idle_lifetime_params,
reader_shareable_params,
+ translate_libpq_ssl_params,
unsupported_db_scheme,
unsupported_db_scheme_message,
)
@@ -1275,11 +1276,15 @@ def run_server(
writer_url,
connection_url_params,
)
- os.environ["DATABASE_URL"] = add_missing_query_params(modified_url, lifetime_params)
+ os.environ["DATABASE_URL"] = translate_libpq_ssl_params(
+ add_missing_query_params(modified_url, lifetime_params)
+ )
if os.getenv("DIRECT_URL", None) is not None:
database_url = os.getenv("DIRECT_URL")
modified_url = append_query_params(database_url, connection_url_params)
- os.environ["DIRECT_URL"] = add_missing_query_params(modified_url, lifetime_params)
+ os.environ["DIRECT_URL"] = translate_libpq_ssl_params(
+ add_missing_query_params(modified_url, lifetime_params)
+ )
# The reader pool is a real pool against the same configured cap, so it
# gets the allowlisted pool params. Schema-affecting ones, including any
# the operator smuggled in through database_extra_connection_params, stay
@@ -1292,14 +1297,16 @@ def run_server(
db_statement_timeout,
db_lock_timeout,
)
- os.environ["DATABASE_URL_READ_REPLICA"] = add_missing_query_params(
+ os.environ["DATABASE_URL_READ_REPLICA"] = translate_libpq_ssl_params(
add_missing_query_params(
- _with_query_value(read_replica_url, "options", reader_options)
- if reader_options
- else read_replica_url,
- reader_shareable_params(connection_url_params),
- ),
- lifetime_params,
+ add_missing_query_params(
+ _with_query_value(read_replica_url, "options", reader_options)
+ if reader_options
+ else read_replica_url,
+ reader_shareable_params(connection_url_params),
+ ),
+ lifetime_params,
+ )
)
subprocess.run(["prisma"], capture_output=True)
is_prisma_runnable = True
diff --git a/tests/test_litellm/proxy/db/test_db_url_settings.py b/tests/test_litellm/proxy/db/test_db_url_settings.py
index 2552e52fb77..db524625a93 100644
--- a/tests/test_litellm/proxy/db/test_db_url_settings.py
+++ b/tests/test_litellm/proxy/db/test_db_url_settings.py
@@ -739,3 +739,85 @@ def test_unsupported_db_scheme_message_names_var_and_scheme():
assert "DIRECT_URL" in msg
assert "sqlite" in msg
assert "postgresql://" in msg
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return urllib.parse.parse_qs(urllib.parse.urlsplit(url).query, keep_blank_values=True)
+
+
+def test_libpq_verify_full_and_sslrootcert_become_prisma_strict_sslcert(monkeypatch):
+ """Prisma drops ``sslrootcert`` and treats ``verify-full`` as ``prefer``, so a
+ libpq-style URL (the form the RDS docs give) connects with no certificate
+ check. The URL Prisma actually receives must carry its own strict dialect."""
+ monkeypatch.setenv(
+ "DATABASE_URL",
+ "postgresql://u:[email protected]:5432/litellm_db?sslmode=verify-full&sslrootcert=/certs/rds-bundle.pem",
+ )
+
+ assert _apply() is False
+
+ assert _query(os.environ["DATABASE_URL"]) == {
+ "sslmode": ["require"],
+ "sslcert": ["/certs/rds-bundle.pem"],
+ "sslaccept": ["strict"],
+ }
+
+
+def test_libpq_verify_ca_becomes_prisma_strict(monkeypatch):
+ monkeypatch.setenv("DATABASE_URL", "postgresql://u:[email protected]:5432/litellm_db?sslmode=verify-ca")
+
+ _apply()
+
+ assert _query(os.environ["DATABASE_URL"]) == {"sslmode": ["require"], "sslaccept": ["strict"]}
+
+
+def test_sslrootcert_alone_turns_on_strict_verification(monkeypatch):
+ """libpq verifies the chain whenever a root cert is supplied under
+ ``sslmode=require``; Prisma needs ``sslaccept=strict`` to do the same."""
+ monkeypatch.setenv(
+ "DATABASE_URL", "postgresql://u:[email protected]:5432/litellm_db?sslmode=require&sslrootcert=/certs/ca.pem"
+ )
+
+ _apply()
+
+ assert _query(os.environ["DATABASE_URL"]) == {
+ "sslmode": ["require"],
+ "sslcert": ["/certs/ca.pem"],
+ "sslaccept": ["strict"],
+ }
+
+
+def test_pinned_prisma_ssl_params_win_over_libpq_translation(monkeypatch):
+ monkeypatch.setenv(
+ "DATABASE_URL",
+ "postgresql://u:[email protected]:5432/litellm_db"
+ "?sslmode=verify-full&sslrootcert=/ignored.pem&sslcert=/pinned.pem&sslaccept=accept_invalid_certs",
+ )
+
+ _apply()
+
+ assert _query(os.environ["DATABASE_URL"]) == {
+ "sslmode": ["require"],
+ "sslcert": ["/pinned.pem"],
+ "sslaccept": ["accept_invalid_certs"],
+ }
+
+
+def test_prisma_native_ssl_url_is_left_untouched(monkeypatch):
+ url = "postgresql://u:[email protected]:5432/litellm_db?sslmode=require&sslcert=/certs/ca.pem&sslaccept=strict"
+ monkeypatch.setenv("DATABASE_URL", url)
+
+ _apply()
+
+ assert os.environ["DATABASE_URL"] == url
+
+
+def test_libpq_ssl_translation_covers_direct_url_and_read_replica(monkeypatch):
+ monkeypatch.setenv("DATABASE_URL", "postgresql://u:[email protected]:5432/db?sslmode=verify-full")
+ monkeypatch.setenv("DIRECT_URL", "postgresql://u:[email protected]:5432/db?sslmode=verify-full")
+ monkeypatch.setenv("DATABASE_URL_READ_REPLICA", "postgresql://u:[email protected]:5432/db?sslmode=verify-full")
+
+ _apply()
+
+ for env_var in ("DATABASE_URL", "DIRECT_URL", "DATABASE_URL_READ_REPLICA"):
+ assert _query(os.environ[env_var]) == {"sslmode": ["require"], "sslaccept": ["strict"]}, env_var
diff --git a/tests/test_litellm/proxy/test_proxy_cli.py b/tests/test_litellm/proxy/test_proxy_cli.py
index 7b3528f3a68..ff2bd1114de 100644
--- a/tests/test_litellm/proxy/test_proxy_cli.py
+++ b/tests/test_litellm/proxy/test_proxy_cli.py
@@ -2623,3 +2623,49 @@ class TestTokenAuthCliFlags:
assert result.exit_code == 0, f"exit_code={result.exit_code}, output={result.output}"
assert "ENTRA_TOKEN" not in (database_url or "")
assert toggle is None
+
+
+class TestLibpqSslParamTranslation:
+ """Prisma ignores ``sslrootcert`` and treats ``sslmode=verify-full`` as
+ ``prefer``, so the URL handed to it must carry Prisma's own strict dialect."""
+
+ @staticmethod
+ def _config(tmp_path, general_settings):
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(yaml.dump({"model_list": [], "general_settings": general_settings}))
+ return str(config_path)
+
+ def test_libpq_url_is_translated_on_every_prisma_url(self, tmp_path):
+ libpq = "?sslmode=verify-full&sslrootcert=/certs/rds-bundle.pem"
+ captured = _run_server_and_capture_urls(
+ self._config(tmp_path, {}),
+ database_url=f"postgresql://t:t@localhost:5432/t{libpq}",
+ direct_url=f"postgresql://t:t@direct:5432/t{libpq}",
+ read_replica_url=f"postgresql://t:t@reader:5432/t{libpq}",
+ )
+
+ for env_var in ("DATABASE_URL", "DIRECT_URL", "DATABASE_URL_READ_REPLICA"):
+ query = urlparse.parse_qs(urlparse.urlparse(captured[env_var]).query)
+ assert "sslrootcert" not in query, env_var
+ assert query["sslmode"] == ["require"], env_var
+ assert query["sslcert"] == ["/certs/rds-bundle.pem"], env_var
+ assert query["sslaccept"] == ["strict"], env_var
+
+ def test_libpq_params_from_extra_connection_params_are_translated(self, tmp_path):
+ captured = _run_server_and_capture_urls(
+ self._config(
+ tmp_path,
+ {
+ "database_extra_connection_params": {
+ "sslmode": "verify-full",
+ "sslrootcert": "/certs/rds-bundle.pem",
+ }
+ },
+ ),
+ )
+
+ query = urlparse.parse_qs(urlparse.urlparse(captured["DATABASE_URL"]).query)
+ assert "sslrootcert" not in query
+ assert query["sslmode"] == ["require"]
+ assert query["sslcert"] == ["/certs/rds-bundle.pem"]
+ assert query["sslaccept"] == ["strict"]