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]

feat(proxy): authenticate to Azure Postgres with Microsoft Entra ID tokens

mateo-berri5c213127e8ff
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.json
index b4c324a2c4c..e4c0145cf1a 100644
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@ -105,13 +105,13 @@
"limit": 109
},
"reportUnknownMemberType": {
- "limit": 39017
+ "limit": 39013
},
"reportUnknownParameterType": {
"limit": 19885
},
"reportUnknownVariableType": {
- "limit": 30572
+ "limit": 30570
},
"reportUnnecessaryCast": {
"limit": 117
diff --git a/helm/litellm/templates/_helpers.tpl b/helm/litellm/templates/_helpers.tpl
index bffd627393a..72f7f74bcf6 100644
--- a/helm/litellm/templates/_helpers.tpl
+++ b/helm/litellm/templates/_helpers.tpl
@@ -213,18 +213,21 @@ whenever the password contains a URL-reserved character (@, /, ?, %, +,
When `database.writer.useIAMAuth: true`, the chart injects
IAM_TOKEN_DB_AUTH=true and omits DATABASE_PASSWORD — the entrypoint mints
-the URL from DATABASE_HOST/PORT/USER/NAME plus a short-lived IAM token
-instead of a static password.
+the URL from DATABASE_HOST/PORT/USER/NAME plus a short-lived AWS RDS IAM
+token instead of a static password. `database.writer.useAzureEntraAuth: true`
+does the same with AZURE_POSTGRESQL_AUTH=true and a Microsoft Entra ID token,
+for Azure Database for PostgreSQL. The two are mutually exclusive.
The read replica is opt-in via `database.reader.host`. The chart emits
DATABASE_HOST_READ_REPLICA / DATABASE_PORT_READ_REPLICA /
DATABASE_NAME_READ_REPLICA (+ DATABASE_SCHEMA_READ_REPLICA) for both auth
modes, plus DATABASE_USER_READ_REPLICA / DATABASE_PASSWORD_READ_REPLICA for
-password auth. When `database.reader.useIAMAuth: true` it omits
+password auth. When `database.reader.useIAMAuth: true` (or
+`database.reader.useAzureEntraAuth: true`) it omits
DATABASE_PASSWORD_READ_REPLICA and the entrypoint mints the reader URL the
-same way. Reader IAM only takes effect when the writer also uses IAM auth
-(the proxy gates URL minting on IAM_TOKEN_DB_AUTH, which only the writer
-sets).
+same way. Reader token auth only takes effect when the writer uses the same
+token source, since the proxy gates URL minting on the single global
+IAM_TOKEN_DB_AUTH / AZURE_POSTGRESQL_AUTH toggle that only the writer sets.
*/}}
{{- define "litellm.serverEnv" -}}
{{- $root := .root -}}
@@ -254,9 +257,15 @@ sets).
- name: DATABASE_SCHEMA
value: {{ .schema | quote }}
{{- end }}
+{{- if and .useIAMAuth .useAzureEntraAuth }}
+{{- fail "database.writer.useIAMAuth and database.writer.useAzureEntraAuth are mutually exclusive: the database password can only come from one token source" }}
+{{- end }}
{{- if .useIAMAuth }}
- name: IAM_TOKEN_DB_AUTH
value: "true"
+{{- else if .useAzureEntraAuth }}
+- name: AZURE_POSTGRESQL_AUTH
+ value: "true"
{{- else }}
- name: DATABASE_PASSWORD
valueFrom:
@@ -270,6 +279,9 @@ sets).
{{- if and .useIAMAuth (not $root.Values.database.writer.useIAMAuth) }}
{{- fail "database.reader.useIAMAuth requires database.writer.useIAMAuth: true (the proxy gates IAM URL minting on IAM_TOKEN_DB_AUTH, which is only set by the writer)" }}
{{- end }}
+{{- if and .useAzureEntraAuth (not $root.Values.database.writer.useAzureEntraAuth) }}
+{{- fail "database.reader.useAzureEntraAuth requires database.writer.useAzureEntraAuth: true (the proxy gates Entra URL minting on AZURE_POSTGRESQL_AUTH, which is only set by the writer)" }}
+{{- end }}
- name: DATABASE_HOST_READ_REPLICA
value: {{ .host | quote }}
- name: DATABASE_PORT_READ_REPLICA
@@ -280,7 +292,7 @@ sets).
- name: DATABASE_SCHEMA_READ_REPLICA
value: {{ .schema | quote }}
{{- end }}
-{{- if .useIAMAuth }}
+{{- if or .useIAMAuth .useAzureEntraAuth }}
{{- if .passwordSecret.name }}
- name: DATABASE_USER_READ_REPLICA
valueFrom:
diff --git a/helm/litellm/tests/database_auth_tests.yaml b/helm/litellm/tests/database_auth_tests.yaml
new file mode 100644
index 00000000000..adbe14c59c2
--- /dev/null
+++ b/helm/litellm/tests/database_auth_tests.yaml
@@ -0,0 +1,116 @@
+suite: test database token auth env vars
+templates:
+ - gateway/deployment.yaml
+ - gateway/configmap.yaml
+ - backend/deployment.yaml
+ - backend/configmap.yaml
+values:
+ - ./values/required.yaml
+tests:
+ - it: writer emits DATABASE_PASSWORD and no token toggle by default
+ template: gateway/deployment.yaml
+ asserts:
+ - contains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: DATABASE_PASSWORD
+ valueFrom:
+ secretKeyRef:
+ name: litellm-writer-secret
+ key: password
+ any: true
+ - notContains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: IAM_TOKEN_DB_AUTH
+ value: "true"
+ any: true
+ - notContains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: AZURE_POSTGRESQL_AUTH
+ value: "true"
+ any: true
+
+ - it: writer emits AZURE_POSTGRESQL_AUTH and omits DATABASE_PASSWORD under Entra auth
+ template: gateway/deployment.yaml
+ set:
+ database.writer.useAzureEntraAuth: true
+ asserts:
+ - contains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: AZURE_POSTGRESQL_AUTH
+ value: "true"
+ any: true
+ - notContains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: DATABASE_PASSWORD
+ any: true
+ - notContains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: IAM_TOKEN_DB_AUTH
+ value: "true"
+ any: true
+
+ - it: backend gets the same Entra toggle as the gateway
+ template: backend/deployment.yaml
+ set:
+ database.writer.useAzureEntraAuth: true
+ asserts:
+ - contains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: AZURE_POSTGRESQL_AUTH
+ value: "true"
+ any: true
+
+ - it: writer rejects both token sources at once
+ template: gateway/deployment.yaml
+ set:
+ database.writer.useIAMAuth: true
+ database.writer.useAzureEntraAuth: true
+ asserts:
+ - failedTemplate:
+ errorMessage: "database.writer.useIAMAuth and database.writer.useAzureEntraAuth are mutually exclusive: the database password can only come from one token source"
+
+ - it: reader Entra auth without writer Entra auth is rejected
+ template: gateway/deployment.yaml
+ set:
+ database.reader.host: reader.example.com
+ database.reader.dbname: litellm
+ database.reader.useAzureEntraAuth: true
+ asserts:
+ - failedTemplate:
+ errorMessage: "database.reader.useAzureEntraAuth requires database.writer.useAzureEntraAuth: true (the proxy gates Entra URL minting on AZURE_POSTGRESQL_AUTH, which is only set by the writer)"
+
+ - it: reader under Entra auth omits DATABASE_PASSWORD_READ_REPLICA
+ template: gateway/deployment.yaml
+ set:
+ database.writer.useAzureEntraAuth: true
+ database.reader.host: reader.example.com
+ database.reader.dbname: litellm
+ database.reader.useAzureEntraAuth: true
+ asserts:
+ - contains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: DATABASE_HOST_READ_REPLICA
+ value: reader.example.com
+ any: true
+ - contains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: DATABASE_USER_READ_REPLICA
+ valueFrom:
+ secretKeyRef:
+ name: litellm-reader-secret
+ key: username
+ any: true
+ - notContains:
+ path: spec.template.spec.containers[0].env
+ content:
+ name: DATABASE_PASSWORD_READ_REPLICA
+ any: true
diff --git a/helm/litellm/values.yaml b/helm/litellm/values.yaml
index 3f8aacfce17..998d225a317 100644
--- a/helm/litellm/values.yaml
+++ b/helm/litellm/values.yaml
@@ -145,6 +145,8 @@ database:
dbname: ""
schema: ""
useIAMAuth: false
+ # Azure Database for PostgreSQL with a Microsoft Entra ID token; mutually exclusive with useIAMAuth
+ useAzureEntraAuth: false
passwordSecret:
name: litellm-writer-secret
usernameKey: username
@@ -159,6 +161,8 @@ database:
dbname: ""
schema: ""
useIAMAuth: false
+ # Azure Database for PostgreSQL with a Microsoft Entra ID token; mutually exclusive with useIAMAuth
+ useAzureEntraAuth: false
passwordSecret:
name: litellm-reader-secret
usernameKey: username
diff --git a/litellm/proxy/db/db_url_settings.py b/litellm/proxy/db/db_url_settings.py
index 17e631995cd..37d965e40a0 100644
--- a/litellm/proxy/db/db_url_settings.py
+++ b/litellm/proxy/db/db_url_settings.py
@@ -11,10 +11,12 @@ The env var names this module reads are exactly the ones emitted by the
(``helm/litellm/templates/_helpers.tpl``). Both auth styles and both
endpoints are covered:
- * IAM auth (``IAM_TOKEN_DB_AUTH`` truthy): mint a short-lived RDS IAM
- token and embed it as the password. The writer URL is always
- (re)written because the token is freshly minted on every startup. The
- chart omits ``DATABASE_PASSWORD`` in this mode.
+ * Token auth (``IAM_TOKEN_DB_AUTH`` truthy for AWS RDS IAM, or
+ ``AZURE_POSTGRESQL_AUTH`` truthy for Azure Database for PostgreSQL with
+ Microsoft Entra ID): mint a short-lived token and embed it as the
+ password. The writer URL is always (re)written because the token is
+ freshly minted on every startup. The chart omits ``DATABASE_PASSWORD``
+ in this mode. Enabling both toggles is a startup error.
* Password auth: build a percent-encoded URL from ``DATABASE_PASSWORD``.
The chart emits the discrete ``DATABASE_*`` fields (never a
pre-assembled URL), so URL-reserved characters in the password survive
@@ -22,27 +24,33 @@ endpoints are covered:
one an operator pinned via ``extraEnv`` — is left untouched and wins.
The read replica is opt-in via ``DATABASE_HOST_READ_REPLICA`` and never
-clobbers a pre-existing ``DATABASE_URL_READ_REPLICA``, so an IAM writer can
-run alongside a password-auth reader (or a precomputed reader URL). Reader
-IAM is gated on the single global ``IAM_TOKEN_DB_AUTH`` flag — the chart
-only emits the reader IAM env vars when the writer also uses IAM auth.
+clobbers a pre-existing ``DATABASE_URL_READ_REPLICA``, so a token-auth writer
+can run alongside a password-auth reader (or a precomputed reader URL). Reader
+token auth is gated on the same global toggle as the writer: the chart only
+emits the reader token env vars when the writer also uses token auth.
Reader-side fields fall back to the writer's user / name / schema / port /
password when their ``*_READ_REPLICA`` counterpart is unset.
"""
import os
import urllib.parse
-from typing import Final, cast
+from typing import Annotated, Final, cast
-from pydantic import AliasChoices, Field
+from pydantic import AliasChoices, BeforeValidator, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
-# Imported as a module (not `from ... import generate_iam_auth_token`) so the
-# AWS-touching token mint stays patchable at its canonical location in tests.
-from litellm.proxy.auth import rds_iam_token
+from litellm.proxy.db.token_auth import (
+ AZURE_POSTGRESQL_AUTH_ENV_VAR,
+ DEFAULT_POSTGRES_PORT,
+ IAM_TOKEN_DB_AUTH_ENV_VAR,
+ DatabaseTokenAuth,
+ IAMEndpoint,
+ build_database_token_auth,
+ mint_database_token,
+ token_auth_flag_enabled,
+)
-_IAM_ENV_KEY: Final = "IAM_TOKEN_DB_AUTH"
-_DEFAULT_PG_PORT: Final = "5432"
+TokenAuthFlag = Annotated[bool, BeforeValidator(token_auth_flag_enabled)]
# schema.prisma pins `provider = "postgresql"`, so these are the only schemes
# Prisma can actually connect with.
@@ -90,13 +98,14 @@ class DatabaseURLSettings(BaseSettings):
model_config = SettingsConfigDict(case_sensitive=False, extra="ignore")
- iam_token_db_auth: bool = Field(default=False, validation_alias=_IAM_ENV_KEY)
+ iam_token_db_auth: TokenAuthFlag = Field(default=False, validation_alias=IAM_TOKEN_DB_AUTH_ENV_VAR)
+ azure_postgresql_auth: TokenAuthFlag = Field(default=False, validation_alias=AZURE_POSTGRESQL_AUTH_ENV_VAR)
# Writer
database_url: str | None = Field(default=None, validation_alias="DATABASE_URL")
direct_url: str | None = Field(default=None, validation_alias="DIRECT_URL")
database_host: str | None = Field(default=None, validation_alias="DATABASE_HOST")
- database_port: str = Field(default=_DEFAULT_PG_PORT, validation_alias="DATABASE_PORT")
+ database_port: str = Field(default=DEFAULT_POSTGRES_PORT, validation_alias="DATABASE_PORT")
database_user: str | None = Field(
default=None,
validation_alias=AliasChoices("DATABASE_USER", "DATABASE_USERNAME"),
@@ -122,15 +131,27 @@ class DatabaseURLSettings(BaseSettings):
"""Load the settings from ``os.environ`` (read at call time)."""
return cls()
+ def token_auth(self) -> DatabaseTokenAuth | None:
+ """The token strategy the toggles ask for, or ``None`` for password auth.
+
+ Raises ``RuntimeError`` when both toggles are on, since the password can only
+ come from one source.
+ """
+ return build_database_token_auth(
+ iam_token_db_auth=self.iam_token_db_auth,
+ azure_postgresql_auth=self.azure_postgresql_auth,
+ )
+
def build_writer_url(self) -> str | None:
"""Return the writer URL to set, or ``None`` to leave it as-is.
- Raises ``RuntimeError`` (naming the offending vars) when IAM auth is
+ Raises ``RuntimeError`` (naming the offending vars) when token auth is
enabled but a required field is missing — the proxy cannot recover
from this and a clear startup error beats a Prisma connect failure.
"""
- if self.iam_token_db_auth:
- missing: Final = [
+ auth: Final = self.token_auth()
+ if auth is not None:
+ missing: Final = tuple(
env
for env, val in (
("DATABASE_HOST", self.database_host),
@@ -138,23 +159,21 @@ class DatabaseURLSettings(BaseSettings):
("DATABASE_NAME", self.database_name),
)
if not val
- ]
+ )
if missing:
raise RuntimeError(
- "IAM_TOKEN_DB_AUTH is enabled but required DB env var(s) "
+ f"{auth.env_var} is enabled but required DB env var(s) "
f"are unset: {', '.join(missing)}. Set them so the writer "
- "DATABASE_URL can be assembled with a minted IAM token."
+ f"DATABASE_URL can be assembled with a minted {auth.label}."
)
- host: Final = cast(str, self.database_host)
- user: Final = cast(str, self.database_user)
- name: Final = cast(str, self.database_name)
- # IAM token is already URL-quoted by generate_iam_auth_token;
- # user/name embedded raw (parity with proxy_cli.py / IAMEndpoint).
- token: Final = rds_iam_token.generate_iam_auth_token(db_host=host, db_port=self.database_port, db_user=user)
- url = f"postgresql://{user}:{token}@{host}:{self.database_port}/{name}"
- if self.database_schema:
- url += f"?schema={self.database_schema}"
- return url
+ endpoint: Final = IAMEndpoint(
+ host=cast(str, self.database_host),
+ port=self.database_port,
+ user=cast(str, self.database_user),
+ name=cast(str, self.database_name),
+ schema=self.database_schema,
+ )
+ return endpoint.build_url(mint_database_token(auth, endpoint))
# Password auth: an operator-pinned DATABASE_URL always wins.
if self.database_url:
@@ -184,35 +203,37 @@ class DatabaseURLSettings(BaseSettings):
host: Final = self.database_host_read_replica
port: Final = self.database_port_read_replica or self.database_port
- user = self.database_user_read_replica or self.database_user
- name = self.database_name_read_replica or self.database_name
+ user: Final = self.database_user_read_replica or self.database_user
+ name: Final = self.database_name_read_replica or self.database_name
schema: Final = self.database_schema_read_replica or self.database_schema
password: Final = self.database_password_read_replica or self.database_password
- if self.iam_token_db_auth:
- missing: Final = [
+ auth: Final = self.token_auth()
+ if auth is not None:
+ missing: Final = tuple(
env
for env, val in (
("DATABASE_USER[_READ_REPLICA]", user),
("DATABASE_NAME[_READ_REPLICA]", name),
)
if not val
- ]
+ )
if missing:
raise RuntimeError(
- "IAM_TOKEN_DB_AUTH is enabled and DATABASE_HOST_READ_REPLICA "
+ f"{auth.env_var} is enabled and DATABASE_HOST_READ_REPLICA "
"is set, but the reader could not resolve: "
f"{', '.join(missing)} (no *_READ_REPLICA value and no "
"writer fallback). Set the reader fields or the writer "
"defaults."
)
- user = cast(str, user)
- name = cast(str, name)
- token: Final = rds_iam_token.generate_iam_auth_token(db_host=host, db_port=port, db_user=user)
- url = f"postgresql://{user}:{token}@{host}:{port}/{name}"
- if schema:
- url += f"?schema={schema}"
- return url
+ endpoint: Final = IAMEndpoint(
+ host=host,
+ port=port,
+ user=cast(str, user),
+ name=cast(str, name),
+ schema=schema,
+ )
+ return endpoint.build_url(mint_database_token(auth, endpoint))
if user and name:
return self._password_url(
@@ -271,23 +292,35 @@ class DatabaseURLSettings(BaseSettings):
if bad_scheme is not None:
raise RuntimeError(unsupported_db_scheme_message(env_var, bad_scheme))
+ def apply_writer_url_to_env(self) -> bool:
+ """Write just the assembled writer URL into ``os.environ``.
+
+ Split out because the CLI shares this minting path but resolves the read
+ replica separately, so it must not pick up reader behavior on the way. The
+ CLI runs its own scheme guard over the pinned URLs, so unlike
+ ``apply_to_env`` this does not repeat it.
+ """
+ writer_url: Final = self.build_writer_url()
+ if writer_url is None:
+ return False
+ os.environ["DATABASE_URL"] = writer_url
+ # Normalize the toggles so downstream readers (PrismaWrapper's token
+ # refresh) reliably see token auth on, regardless of spelling.
+ if self.iam_token_db_auth:
+ os.environ[IAM_TOKEN_DB_AUTH_ENV_VAR] = "True"
+ if self.azure_postgresql_auth:
+ os.environ[AZURE_POSTGRESQL_AUTH_ENV_VAR] = "True"
+ return True
+
def apply_to_env(self) -> bool:
"""Write the assembled URL(s) into ``os.environ``.
- Returns True iff this call set ``DATABASE_URL`` (IAM mint, or
+ Returns True iff this call set ``DATABASE_URL`` (token mint, or
password auth that assembled a fresh URL). False means there was
nothing to do — an operator-pinned URL, or no discrete fields.
"""
self._raise_for_unsupported_scheme()
- wrote_writer = False
- writer_url: Final = self.build_writer_url()
- if writer_url is not None:
- os.environ["DATABASE_URL"] = writer_url
- if self.iam_token_db_auth:
- # Normalize the toggle so downstream readers (PrismaWrapper's
- # IAM refresh) reliably see IAM on, regardless of spelling.
- os.environ[_IAM_ENV_KEY] = "True"
- wrote_writer = True
+ wrote_writer: Final = self.apply_writer_url_to_env()
reader_url: Final = self.build_reader_url()
if reader_url is not None:
diff --git a/litellm/proxy/db/prisma_client.py b/litellm/proxy/db/prisma_client.py
index 5f86490a474..757f7576047 100644
--- a/litellm/proxy/db/prisma_client.py
+++ b/litellm/proxy/db/prisma_client.py
@@ -1,5 +1,6 @@
"""
-This file contains the PrismaWrapper class, which is used to wrap the Prisma client and handle the RDS IAM token.
+This file contains the PrismaWrapper class, which wraps the Prisma client and keeps the
+database token (AWS RDS IAM or Microsoft Entra ID) fresh.
"""
import asyncio
@@ -11,34 +12,27 @@ import time
import urllib
import urllib.parse
from collections.abc import Callable
-from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, Final, Protocol
from litellm._logging import verbose_proxy_logger
+from litellm.proxy.db.token_auth import (
+ DEFAULT_POSTGRES_PORT,
+ DatabaseTokenAuth,
+ IAMEndpoint,
+ RdsIamTokenAuth,
+ mint_database_token,
+ parse_database_token_expiration,
+ parse_iam_endpoint_from_url,
+)
from litellm.secret_managers.main import str_to_bool
-
-@dataclass(frozen=True)
-class IAMEndpoint:
- """Static parts of an RDS IAM-authenticated Postgres connection.
-
- The IAM token rotates every ~15 minutes; everything else (host, port, user,
- database name, schema) stays fixed. We capture the static fields once so
- refresh just regenerates the token and reassembles the URL.
- """
-
- host: str
- port: str
- user: str
- name: str
- schema: str | None = None
-
- def build_url(self, token: str) -> str:
- url = f"postgresql://{self.user}:{token}@{self.host}:{self.port}/{self.name}"
- if self.schema:
- url += f"?schema={self.schema}"
- return url
+__all__ = (
+ "IAMEndpoint",
+ "PrismaManager",
+ "PrismaWrapper",
+ "parse_iam_endpoint_from_url",
+)
class _PrismaProcess(Protocol):
@@ -141,45 +135,17 @@ class _TrackedPrismaEngine:
self.tracker.transaction_finished(tx_id)
-def parse_iam_endpoint_from_url(url: str) -> IAMEndpoint:
- """Parse an IAMEndpoint from a Postgres URL.
-
- Used so a reader URL can drive its own IAM refresh without requiring
- callers to set parallel DATABASE_HOST_READ_REPLICA / etc. env vars.
- """
- parsed: Final = urllib.parse.urlparse(url)
- if not parsed.hostname or not parsed.username:
- raise ValueError("Cannot parse IAM endpoint from URL: missing host or username")
- name: Final = (parsed.path or "/").lstrip("/")
- if not name:
- raise ValueError("Cannot parse IAM endpoint from URL: missing database name")
- port: Final = str(parsed.port) if parsed.port else "5432"
- schema: str | None = None
- if parsed.query:
- qs: Final = urllib.parse.parse_qs(parsed.query)
- schema_vals: Final = qs.get("schema")
- if schema_vals:
- schema = schema_vals[0]
- return IAMEndpoint(
- host=parsed.hostname,
- port=port,
- user=parsed.username,
- name=name,
- schema=schema,
- )
-
-
class PrismaWrapper:
"""
- Wrapper around Prisma client that handles RDS IAM token authentication.
+ Wrapper around Prisma client that handles token-based database authentication.
- When iam_token_db_auth is enabled, this wrapper:
- 1. Proactively refreshes IAM tokens before they expire (background task)
+ When a token strategy is active (AWS RDS IAM or Microsoft Entra ID), this wrapper:
+ 1. Proactively refreshes the token before it expires (background task)
2. Falls back to synchronous refresh if a token is found expired
3. Uses proper locking to prevent race conditions during reconnection
- RDS IAM tokens are valid for 15 minutes. This wrapper refreshes them
- 3 minutes before expiration to ensure uninterrupted database connectivity.
+ RDS IAM tokens are valid for 15 minutes and Entra tokens for about an hour. This
+ wrapper refreshes 3 minutes before whatever expiry the live token carries.
"""
# Buffer time in seconds before token expiration to trigger refresh
@@ -194,15 +160,18 @@ class PrismaWrapper:
def __init__(
self,
original_prisma: Any,
- iam_token_db_auth: bool,
+ iam_token_db_auth: bool = False,
*,
+ token_auth: DatabaseTokenAuth | None = None,
db_url_env_var: str = "DATABASE_URL",
iam_endpoint: IAMEndpoint | None = None,
recreate_uses_datasource: bool = False,
log_prefix: str = "",
):
+ # Set before `_original_prisma` so the `iam_token_db_auth` property below can
+ # never send `__getattr__` looking for a half-built strategy on the raw client.
+ self._token_auth = token_auth if token_auth is not None else (RdsIamTokenAuth() if iam_token_db_auth else None)
self._original_prisma = original_prisma
- self.iam_token_db_auth = iam_token_db_auth
# Per-connection knobs so the same wrapper can be used for the writer
# (defaults: DATABASE_URL env, IAM endpoint from DATABASE_HOST/etc.,
@@ -241,6 +210,25 @@ class PrismaWrapper:
self._engine_generation: int = 0
self.on_engine_replaced: Callable[[], None] | None = None
+ @property
+ def token_auth(self) -> DatabaseTokenAuth | None:
+ """The active database token strategy, or None for password auth."""
+ return self._token_auth
+
+ @property
+ def token_label(self) -> str:
+ """Human name of the active token kind, for log lines."""
+ return self._token_auth.label if self._token_auth is not None else "database token"
+
+ @property
+ def iam_token_db_auth(self) -> bool:
+ """Whether any token strategy is active.
+
+ Read-only: the kind of token is chosen once, by injection, so there is no way
+ to flip this back on and silently get AWS RDS on an Azure deployment.
+ """
+ return self._token_auth is not None
+
@staticmethod
def _read_engine(prisma_client: _PrismaClient) -> _PrismaEngine:
return prisma_client._engine
@@ -376,30 +364,9 @@ class PrismaWrapper:
Returns the datetime when the token expires, or None if parsing fails.
"""
- if token is None:
- return None
-
- try:
- # Token format: ...?X-Amz-Date=YYYYMMDDTHHMMSSZ&X-Amz-Expires=900&...
- if "?" not in token:
- return None
-
- query_string: Final = token.split("?", 1)[1]
- params: Final = urllib.parse.parse_qs(query_string)
-
- expires_str: Final = params.get("X-Amz-Expires", [None])[0]
- date_str: Final = params.get("X-Amz-Date", [None])[0]
-
- if not expires_str or not date_str:
- return None
-
- token_created: Final = datetime.strptime(date_str, "%Y%m%dT%H%M%SZ")
- expires_in: Final = int(expires_str)
-
- return token_created + timedelta(seconds=expires_in)
- except Exception as e:
- verbose_proxy_logger.debug("Failed to parse token expiration: %s", e)
+ if token is None or self._token_auth is None:
return None
+ return parse_database_token_expiration(self._token_auth, token)
def _calculate_seconds_until_refresh(self) -> float:
"""
@@ -451,40 +418,47 @@ class PrismaWrapper:
return datetime.utcnow() > expiration_time
def get_rds_iam_token(self) -> str | None:
- """Generate a new RDS IAM token and update the configured DB URL env var.
+ """Mint a fresh database token and update the configured DB URL env var.
When the wrapper was constructed with an explicit `iam_endpoint`
(typical for a reader wrapper whose host/port/user came from a parsed
- URL), use that. Otherwise fall back to the legacy DATABASE_HOST/PORT/
- USER/NAME/SCHEMA env vars (writer behavior).
+ URL), use that. Otherwise fall back to the DATABASE_HOST/PORT/USER/
+ NAME/SCHEMA env vars (writer behavior).
"""
- if not self.iam_token_db_auth:
+ auth: Final = self._token_auth
+ if auth is None:
return None
- from litellm.proxy.auth.rds_iam_token import generate_iam_auth_token
+ endpoint: Final = self._iam_endpoint if self._iam_endpoint is not None else self._endpoint_from_env()
+ db_url: Final = endpoint.build_url(mint_database_token(auth, endpoint))
+ os.environ[self._db_url_env_var] = db_url
+ return db_url
- if self._iam_endpoint is not None:
- endpoint: Final = self._iam_endpoint
- token = generate_iam_auth_token(db_host=endpoint.host, db_port=endpoint.port, db_user=endpoint.user)
- _db_url = endpoint.build_url(token)
- else:
- db_host: Final = os.getenv("DATABASE_HOST")
+ @staticmethod
+ def _endpoint_from_env() -> IAMEndpoint:
+ host: Final = os.getenv("DATABASE_HOST")
+ user: Final = os.getenv("DATABASE_USER")
+ name: Final = os.getenv("DATABASE_NAME")
+ if not host or not user or not name:
+ missing: Final = tuple(
+ env
+ for env, value in (("DATABASE_HOST", host), ("DATABASE_USER", user), ("DATABASE_NAME", name))
+ if not value
+ )
+ raise RuntimeError(
+ f"Cannot mint a database token: {', '.join(missing)} unset. Set them so the "
+ "connection URL can be reassembled around a freshly minted token."
+ )
+ return IAMEndpoint(
+ host=host,
# Default to the Postgres standard port; passing None to
# `generate_iam_auth_token` makes botocore embed the literal
# string "None" in the presigned URL, which then fails to parse.
- db_port: Final = os.getenv("DATABASE_PORT", "5432")
- db_user: Final = os.getenv("DATABASE_USER")
- db_name: Final = os.getenv("DATABASE_NAME")
- db_schema: Final = os.getenv("DATABASE_SCHEMA")
-
- token = generate_iam_auth_token(db_host=db_host, db_port=db_port, db_user=db_user)
-
- _db_url = f"postgresql://{db_user}:{token}@{db_host}:{db_port}/{db_name}"
- if db_schema:
- _db_url += f"?schema={db_schema}"
-
- os.environ[self._db_url_env_var] = _db_url
- return _db_url
+ port=os.getenv("DATABASE_PORT", DEFAULT_POSTGRES_PORT),
+ user=user,
+ name=name,
+ schema=os.getenv("DATABASE_SCHEMA"),
+ )
@property
def engine_generation(self) -> int:
@@ -658,12 +632,12 @@ class PrismaWrapper:
"""
Start the background token refresh task.
- This task proactively refreshes RDS IAM tokens before they expire,
+ This task proactively refreshes the database token before it expires,
preventing connection failures. Should be called after the initial
Prisma client connection is established.
"""
if not self.iam_token_db_auth:
- verbose_proxy_logger.debug("IAM token auth not enabled, skipping token refresh task")
+ verbose_proxy_logger.debug("Database token auth not enabled, skipping token refresh task")
return
if self._token_refresh_task is not None:
@@ -672,8 +646,9 @@ class PrismaWrapper:
self._token_refresh_task = asyncio.create_task(self._token_refresh_loop())
verbose_proxy_logger.info(
- "%sStarted RDS IAM token proactive refresh background task",
+ "%sStarted %s proactive refresh background task",
self._log_prefix,
+ self.token_label,
)
async def stop_token_refresh_task(self) -> None:
@@ -691,19 +666,24 @@ class PrismaWrapper:
except asyncio.CancelledError:
pass
self._token_refresh_task = None
- verbose_proxy_logger.info("%sStopped RDS IAM token refresh background task", self._log_prefix)
+ verbose_proxy_logger.info(
+ "%sStopped %s refresh background task",
+ self._log_prefix,
+ self.token_label,
+ )
async def _token_refresh_loop(self) -> None:
"""
- Background loop that proactively refreshes RDS IAM tokens before expiration.
+ Background loop that proactively refreshes database tokens before expiration.
Uses precise timing: calculates the exact sleep duration until the token
needs to be refreshed (expiration - 3 minute buffer), then refreshes.
This is more efficient than polling, requiring only 1 wake-up per token cycle.
"""
verbose_proxy_logger.info(
- "%sRDS IAM token refresh loop started. Tokens will be refreshed %ss before expiration.",
+ "%s%s refresh loop started. Tokens will be refreshed %ss before expiration.",
self._log_prefix,
+ self.token_label,
self.TOKEN_REFRESH_BUFFER_SECONDS,
)
@@ -714,22 +694,31 @@ class PrismaWrapper:
if sleep_seconds > 0:
verbose_proxy_logger.info(
- f"{self._log_prefix}RDS IAM token refresh scheduled in "
+ f"{self._log_prefix}{self.token_label} refresh scheduled in "
f"{sleep_seconds:.0f} seconds ({sleep_seconds / 60:.1f} minutes)"
)
await asyncio.sleep(sleep_seconds)
# Refresh the token
- verbose_proxy_logger.info("%sProactively refreshing RDS IAM token...", self._log_prefix)
+ verbose_proxy_logger.info(
+ "%sProactively refreshing %s...",
+ self._log_prefix,
+ self.token_label,
+ )
await self._safe_refresh_token()
except asyncio.CancelledError:
- verbose_proxy_logger.info("%sRDS IAM token refresh loop cancelled", self._log_prefix)
+ verbose_proxy_logger.info(
+ "%s%s refresh loop cancelled",
+ self._log_prefix,
+ self.token_label,
+ )
break
except Exception as e:
verbose_proxy_logger.error(
- "%sError in RDS IAM token refresh loop: %s. Retrying in %ss...",
+ "%sError in %s refresh loop: %s. Retrying in %ss...",
self._log_prefix,
+ self.token_label,
e,
self.FALLBACK_REFRESH_INTERVAL_SECONDS,
)
@@ -741,7 +730,7 @@ class PrismaWrapper:
async def _safe_refresh_token(self) -> None:
"""
- Refresh the RDS IAM token with proper locking to prevent race conditions.
+ Refresh the database token with proper locking to prevent race conditions.
Uses an asyncio lock to ensure only one refresh operation happens at a time,
preventing multiple concurrent reconnection attempts.
@@ -754,8 +743,9 @@ class PrismaWrapper:
# by skipping when the current token still has comfortable runway.
if self._token_refresh_not_needed(os.getenv(self._db_url_env_var)):
verbose_proxy_logger.debug(
- "%sRDS IAM token still fresh; skipping redundant refresh.",
+ "%s%s still fresh; skipping redundant refresh.",
self._log_prefix,
+ self.token_label,
)
return
@@ -772,13 +762,15 @@ class PrismaWrapper:
raise
self._last_refresh_time = datetime.utcnow()
verbose_proxy_logger.info(
- "%sRDS IAM token refreshed successfully. New token valid for ~15 minutes.",
+ "%s%s refreshed successfully.",
self._log_prefix,
+ self.token_label,
)
else:
verbose_proxy_logger.error(
- "%sFailed to generate new RDS IAM token during proactive refresh",
+ "%sFailed to generate new %s during proactive refresh",
self._log_prefix,
+ self.token_label,
)
def _token_refresh_not_needed(self, token_url: str | None) -> bool:
@@ -832,10 +824,11 @@ class PrismaWrapper:
if running_loop is not None:
verbose_proxy_logger.warning(
- "%sRDS IAM token expired in __getattr__ — proactive refresh "
+ "%s%s expired in __getattr__ - proactive refresh "
"may have failed. Scheduling async refresh; the current "
"request may fail and be retried with the fresh token.",
self._log_prefix,
+ self.token_label,
)
# Non-blocking: schedule the locked refresh on the
# running loop. The reconnection lock inside
@@ -843,9 +836,10 @@ class PrismaWrapper:
running_loop.create_task(self._safe_refresh_token())
else:
verbose_proxy_logger.warning(
- "%sRDS IAM token expired in __getattr__ — proactive refresh "
+ "%s%s expired in __getattr__ - proactive refresh "
"may have failed. Triggering synchronous fallback refresh...",
self._log_prefix,
+ self.token_label,
)
new_db_url: Final = self.get_rds_iam_token()
if new_db_url:
@@ -857,7 +851,7 @@ class PrismaWrapper:
self._log_prefix,
)
else:
- raise ValueError("Failed to get RDS IAM token")
+ raise ValueError(f"Failed to get {self.token_label}")
return original_attr
diff --git a/litellm/proxy/db/routing_prisma_wrapper.py b/litellm/proxy/db/routing_prisma_wrapper.py
index 5aeb52be535..22fc32a898a 100644
--- a/litellm/proxy/db/routing_prisma_wrapper.py
+++ b/litellm/proxy/db/routing_prisma_wrapper.py
@@ -248,14 +248,14 @@ class RoutingPrismaWrapper:
async def _recreate_reader(self, http_client: Any | None = None) -> None:
"""Resolve the reader URL and recreate its Prisma client.
- IAM-enabled readers regenerate their token (host/port/user came from
- the parsed reader URL at construction time). Non-IAM readers reuse
- the URL stored in `DATABASE_URL_READ_REPLICA`.
+ Token-authenticated readers regenerate their token (host/port/user came
+ from the parsed reader URL at construction time). Password-authenticated
+ readers reuse the URL stored in `DATABASE_URL_READ_REPLICA`.
"""
if self._reader.iam_token_db_auth:
new_reader_url: Final = self._reader.get_rds_iam_token()
if not new_reader_url:
- raise RuntimeError("Failed to generate fresh IAM token for read replica")
+ raise RuntimeError(f"Failed to generate fresh {self._reader.token_label} for read replica")
await self._reader.recreate_prisma_client(new_reader_url, http_client=http_client)
return
reader_url: Final = os.getenv("DATABASE_URL_READ_REPLICA", "")
diff --git a/litellm/proxy/db/token_auth.py b/litellm/proxy/db/token_auth.py
new file mode 100644
index 00000000000..608a07a60d5
--- /dev/null
+++ b/litellm/proxy/db/token_auth.py
@@ -0,0 +1,239 @@
+"""Token-based authentication for the proxy's Postgres connection.
+
+Two managed Postgres offerings hand the client a short-lived credential that is used as
+the Postgres password: AWS RDS with IAM auth, and Azure Database for PostgreSQL Flexible
+Server with Microsoft Entra ID. Both need the same machinery (mint at startup, read the
+expiry back off the token, mint again before it lapses) and differ only in how the token
+is produced and how its expiry is encoded, so the difference lives in a tagged union that
+is resolved once from the environment and injected into whatever needs a token.
+"""
+
+import base64
+import functools
+import os
+import urllib.parse
+from collections.abc import Callable
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from typing import Final, TypeAlias
+
+from pydantic import BaseModel
+from typing_extensions import assert_never
+
+from litellm._logging import verbose_proxy_logger
+
+IAM_TOKEN_DB_AUTH_ENV_VAR: Final = "IAM_TOKEN_DB_AUTH"
+AZURE_POSTGRESQL_AUTH_ENV_VAR: Final = "AZURE_POSTGRESQL_AUTH"
+AZURE_POSTGRESQL_SCOPE: Final = "https://ossrdbms-aad.database.windows.net/.default"
+
+CONFLICTING_TOKEN_AUTH_MESSAGE: Final = (
+ f"{IAM_TOKEN_DB_AUTH_ENV_VAR} and {AZURE_POSTGRESQL_AUTH_ENV_VAR} are both enabled, but the "
+ "database password can only come from one token source. Keep "
+ f"{IAM_TOKEN_DB_AUTH_ENV_VAR} for AWS RDS IAM auth, or {AZURE_POSTGRESQL_AUTH_ENV_VAR} for "
+ "Azure Database for PostgreSQL with Microsoft Entra ID, and unset the other one."
+)
+
+DEFAULT_POSTGRES_PORT: Final = "5432"
+
+TRUTHY_TOKEN_AUTH_VALUES: Final[frozenset[str]] = frozenset({"1", "on", "t", "true", "y", "yes"})
+
+
+def token_auth_flag_enabled(value: str | bool | None) -> bool:
+ """Whether a token-auth toggle is on.
+
+ The single parser for both toggles. Every entry point (the settings model, the
+ CLI, and the refresh loop's own env lookup) routes through this, so a value like
+ ``"1"`` cannot enable minting in one place and leave the refresh loop convinced
+ token auth is off, which would strand a pod on a token it never renews.
+ """
+ if isinstance(value, bool):
+ return value
+ return value is not None and value.strip().lower() in TRUTHY_TOKEN_AUTH_VALUES
+
+
+def _quote(value: str) -> str:
+ return urllib.parse.quote(value, safe="")
+
+
+@dataclass(frozen=True, slots=True)
+class IAMEndpoint:
+ """Static parts of a token-authenticated Postgres connection.
+
+ The token rotates every few minutes to an hour depending on the provider;
+ everything else (host, port, user, database name, schema) stays fixed. Capturing
+ the static fields once means a refresh only regenerates the token and reassembles
+ the URL.
+ """
+
+ host: str
+ port: str
+ user: str
+ name: str
+ schema: str | None = None
+
+ def build_url(self, token: str) -> str:
+ """Assemble the connection URL, inserting ``token`` verbatim as the password.
+
+ User, database name, and schema are percent-encoded because an Entra principal
+ is a UPN containing ``@``. The token is not: both providers hand it back already
+ in wire form, and re-encoding it would double-escape the password.
+ """
+ base: Final = f"postgresql://{_quote(self.user)}:{token}@{self.host}:{self.port}/{_quote(self.name)}"
+ if not self.schema:
+ return base
+ return f"{base}?schema={_quote(self.schema)}"
+
+
+def parse_iam_endpoint_from_url(url: str) -> IAMEndpoint:
+ """Parse an :class:`IAMEndpoint` back out of a Postgres URL.
+
+ Used so a reader URL can drive its own token refresh without requiring callers to
+ set parallel ``DATABASE_HOST_READ_REPLICA`` / etc. env vars.
+ """
+ parsed: Final = urllib.parse.urlparse(url)
+ if not parsed.hostname or not parsed.username:
+ raise ValueError("Cannot parse IAM endpoint from URL: missing host or username")
+ name: Final = urllib.parse.unquote((parsed.path or "/").lstrip("/"))
+ if not name:
+ raise ValueError("Cannot parse IAM endpoint from URL: missing database name")
+ port: Final = str(parsed.port) if parsed.port else DEFAULT_POSTGRES_PORT
+ schema_values: Final = urllib.parse.parse_qs(parsed.query).get("schema") if parsed.query else None
+ return IAMEndpoint(
+ host=parsed.hostname,
+ port=port,
+ user=urllib.parse.unquote(parsed.username),
+ name=name,
+ schema=schema_values[0] if schema_values else None,
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class RdsIamTokenAuth:
+ """AWS RDS IAM auth: a SigV4-presigned token minted from the ambient AWS credentials."""
+
+ @property
+ def label(self) -> str:
+ return "RDS IAM token"
+
+ @property
+ def env_var(self) -> str:
+ return IAM_TOKEN_DB_AUTH_ENV_VAR
+
+
+@dataclass(frozen=True, slots=True)
+class AzureEntraTokenAuth:
+ """Azure Database for PostgreSQL auth: a Microsoft Entra ID access token as the password.
+
+ The provider is injected rather than resolved here so callers (and tests) decide which
+ Azure credential mints the token.
+ """
+
+ token_provider: Callable[[], str]
+
+ @property
+ def label(self) -> str:
+ return "Azure Entra token"
+
+ @property
+ def env_var(self) -> str:
+ return AZURE_POSTGRESQL_AUTH_ENV_VAR
+
+
+DatabaseTokenAuth: TypeAlias = RdsIamTokenAuth | AzureEntraTokenAuth
+
+
+def mint_database_token(auth: DatabaseTokenAuth, endpoint: IAMEndpoint) -> str:
+ """Mint a fresh database password for ``endpoint``, already percent-encoded."""
+ match auth:
+ case RdsIamTokenAuth():
+ from litellm.proxy.auth.rds_iam_token import generate_iam_auth_token
+
+ return generate_iam_auth_token(db_host=endpoint.host, db_port=endpoint.port, db_user=endpoint.user)
+ case AzureEntraTokenAuth():
+ return _quote(auth.token_provider())
+ case _:
+ assert_never(auth)
+
+
+def parse_database_token_expiration(auth: DatabaseTokenAuth, token: str) -> datetime | None:
+ """Return when ``token`` expires as a naive UTC datetime, or None when unreadable.
+
+ Callers fall back to a fixed refresh interval on None, so an unparseable token
+ degrades to periodic refresh instead of failing.
+ """
+ match auth:
+ case RdsIamTokenAuth():
+ return _parse_rds_token_expiration(token)
+ case AzureEntraTokenAuth():
+ return _parse_entra_token_expiration(token)
+ case _:
+ assert_never(auth)
+
+
+def _parse_rds_token_expiration(token: str) -> datetime | None:
+ if "?" not in token:
+ return None
+ try:
+ params: Final = urllib.parse.parse_qs(token.split("?", 1)[1])
+ expires_values: Final = params.get("X-Amz-Expires")
+ date_values: Final = params.get("X-Amz-Date")
+ if not expires_values or not date_values:
+ return None
+ created: Final = datetime.strptime(date_values[0], "%Y%m%dT%H%M%SZ")
+ return created + timedelta(seconds=int(expires_values[0]))
+ except (ValueError, OverflowError, OSError) as exc:
+ verbose_proxy_logger.debug("Failed to parse RDS IAM token expiration: %s", exc)
+ return None
+
+
+class _EntraAccessTokenClaims(BaseModel):
+ exp: int
+
+
+def _parse_entra_token_expiration(token: str) -> datetime | None:
+ segments: Final = token.split(".")
+ if len(segments) != 3:
+ return None
+ payload: Final = segments[1]
+ try:
+ claims: Final = _EntraAccessTokenClaims.model_validate_json(
+ base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))
+ )
+ except ValueError as exc:
+ verbose_proxy_logger.debug("Failed to parse Azure Entra token expiration: %s", exc)
+ return None
+ return datetime.fromtimestamp(claims.exp, tz=timezone.utc).replace(tzinfo=None)
+
+
+def build_azure_entra_token_provider() -> Callable[[], str]:
+ """The process-wide Entra token provider for the Azure Postgres OSS RDBMS scope.
+
+ Cached because the writer URL, the reader URL, and the refresh loop each ask for a
+ strategy, and every uncached call would build another Azure credential with its own
+ HTTP transport and its own token cache that nothing ever closes.
+ """
+ from litellm.secret_managers.get_azure_ad_token_provider import (
+ get_azure_ad_token_provider,
+ )
+
+ return get_azure_ad_token_provider(azure_scope=AZURE_POSTGRESQL_SCOPE)
+
+
+def build_database_token_auth(*, iam_token_db_auth: bool, azure_postgresql_auth: bool) -> DatabaseTokenAuth | None:
+ """Pick the token strategy the two toggles ask for, or None when neither is on."""
+ if iam_token_db_auth and azure_postgresql_auth:
+ raise RuntimeError(CONFLICTING_TOKEN_AUTH_MESSAGE)
+ if azure_postgresql_auth:
+ return AzureEntraTokenAuth(token_provider=build_azure_entra_token_provider())
+ if iam_token_db_auth:
+ return RdsIamTokenAuth()
+ return None
+
+
+def resolve_database_token_auth() -> DatabaseTokenAuth | None:
+ """Resolve the token strategy from the environment, raising when both toggles are set."""
+ return build_database_token_auth(
+ iam_token_db_auth=token_auth_flag_enabled(os.getenv(IAM_TOKEN_DB_AUTH_ENV_VAR)),
+ azure_postgresql_auth=token_auth_flag_enabled(os.getenv(AZURE_POSTGRESQL_AUTH_ENV_VAR)),
+ )
diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.py
index 6a0b3c6bfb2..8ad20cf1c5f 100644
--- a/litellm/proxy/proxy_cli.py
+++ b/litellm/proxy/proxy_cli.py
@@ -19,7 +19,6 @@ from pydantic import BaseModel, ConfigDict
import litellm
from litellm.constants import DEFAULT_NUM_WORKERS_LITELLM_PROXY
from litellm.proxy.db.query_engine_reaper import start_query_engine_reaper
-from litellm.secret_managers.main import get_secret_bool
if TYPE_CHECKING:
from fastapi import FastAPI
@@ -790,6 +789,12 @@ class ProxyInitializationHelpers:
is_flag=True,
help="Connects to RDS DB with IAM token",
)
+ "--azure_postgresql_auth",
+ default=False,
+ is_flag=True,
+ help="Connects to Azure Database for PostgreSQL with a Microsoft Entra ID token",
+)
@click.option(
"--num_requests",
default=10,
@@ -951,6 +956,7 @@ def run_server(
granian_threads,
test_async,
iam_token_db_auth,
+ azure_postgresql_auth: bool,
num_requests,
use_queue,
health,
@@ -1080,31 +1086,25 @@ def run_server(
db_statement_timeout: float | None = None
db_lock_timeout: float | None = None
general_settings = {}
- ### GET DB TOKEN FOR IAM AUTH ###
-
- if iam_token_db_auth or get_secret_bool("IAM_TOKEN_DB_AUTH"):
- from litellm.proxy.auth.rds_iam_token import generate_iam_auth_token
-
- db_host: Final = os.getenv("DATABASE_HOST")
- # Default to the Postgres standard port. Without a default,
- # `db_port=None` flows into `boto.generate_db_auth_token(Port=None)`
- # and botocore stringifies it to `"None"` while building the
- # presigned URL, which then blows up with `ValueError: Port could
- # not be cast to integer value as 'None'` during signing.
- db_port: Final = os.getenv("DATABASE_PORT", "5432")
- db_user: Final = os.getenv("DATABASE_USER")
- db_name: Final = os.getenv("DATABASE_NAME")
- db_schema: Final = os.getenv("DATABASE_SCHEMA")
-
- token: Final = generate_iam_auth_token(db_host=db_host, db_port=db_port, db_user=db_user)
-
- # print(f"token: {token}")
- _db_url = f"postgresql://{db_user}:{token}@{db_host}:{db_port}/{db_name}"
- if db_schema:
- _db_url += f"?schema={db_schema}"
-
- os.environ["DATABASE_URL"] = _db_url
- os.environ["IAM_TOKEN_DB_AUTH"] = "True"
+ ### GET DB TOKEN FOR RDS IAM / AZURE ENTRA AUTH ###
+
+ from litellm.proxy.db.db_url_settings import DatabaseURLSettings
+ from litellm.proxy.db.token_auth import (
+ AZURE_POSTGRESQL_AUTH_ENV_VAR,
+ IAM_TOKEN_DB_AUTH_ENV_VAR,
+ token_auth_flag_enabled,
+ )
+
+ wants_rds_iam: Final = iam_token_db_auth or token_auth_flag_enabled(os.getenv(IAM_TOKEN_DB_AUTH_ENV_VAR))
+ wants_azure_entra: Final = azure_postgresql_auth or token_auth_flag_enabled(
+ os.getenv(AZURE_POSTGRESQL_AUTH_ENV_VAR)
+ )
+ if wants_rds_iam:
+ os.environ[IAM_TOKEN_DB_AUTH_ENV_VAR] = "True"
+ if wants_azure_entra:
+ os.environ[AZURE_POSTGRESQL_AUTH_ENV_VAR] = "True"
+ if wants_rds_iam or wants_azure_entra:
+ DatabaseURLSettings.from_env().apply_writer_url_to_env()
### DECRYPT ENV VAR ###
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 1d042e2521b..eb04a862c5a 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -127,6 +127,11 @@ from litellm.proxy.db.spend_log_batching import (
spend_log_row_bytes,
spend_log_write_batches,
)
+from litellm.proxy.db.token_auth import (
+ DatabaseTokenAuth,
+ mint_database_token,
+ resolve_database_token_auth,
+)
from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (
UnifiedLLMGuardrails,
)
@@ -3277,7 +3282,7 @@ class PrismaClient:
):
## init logging object
self.proxy_logging_obj = proxy_logging_obj
- self.iam_token_db_auth: bool | None = str_to_bool(os.getenv("IAM_TOKEN_DB_AUTH"))
+ self.token_auth: DatabaseTokenAuth | None = resolve_database_token_auth()
verbose_proxy_logger.debug("Creating Prisma Client..")
try:
from prisma import Prisma
@@ -3286,22 +3291,22 @@ class PrismaClient:
verbose_proxy_logger.error("This usually means 'prisma generate' hasn't been run yet.")
verbose_proxy_logger.error("Please run 'prisma generate' to generate the Prisma client.")
raise Exception("Unable to find Prisma binaries. Please run 'prisma generate' first.")
- iam_flag: Final = self.iam_token_db_auth if self.iam_token_db_auth is not None else False
+ token_auth: Final = self.token_auth
# When read-replica routing is on, tag log lines with [writer]/[reader]
- # so the two wrappers' interleaved IAM refresh logs can be told apart.
+ # so the two wrappers' interleaved token refresh logs can be told apart.
# Single-DB deployments get an empty prefix (logs unchanged).
read_replica_url = os.getenv("DATABASE_URL_READ_REPLICA")
writer_log_prefix: Final = "[writer]" if read_replica_url else ""
if http_client is not None:
writer_wrapper = PrismaWrapper(
original_prisma=Prisma(http=http_client),
- iam_token_db_auth=iam_flag,
+ token_auth=token_auth,
log_prefix=writer_log_prefix,
)
else:
writer_wrapper = PrismaWrapper(
original_prisma=Prisma(),
- iam_token_db_auth=iam_flag,
+ token_auth=token_auth,
log_prefix=writer_log_prefix,
)
@@ -3313,29 +3318,22 @@ class PrismaClient:
self.db: PrismaWrapper | RoutingPrismaWrapper
if read_replica_url:
try:
- # If IAM auth is enabled, the reader refreshes its own token on
+ # If token auth is enabled, the reader refreshes its own token on
# the same cadence as the writer. We parse the static endpoint
# pieces (host/port/user/db) once from the reader URL — only
- # the IAM token rotates after that.
- reader_iam_endpoint: Final = parse_iam_endpoint_from_url(read_replica_url) if iam_flag else None
- # Mint a fresh IAM token for the reader BEFORE constructing the
+ # the token rotates after that.
+ reader_iam_endpoint: Final = (
+ parse_iam_endpoint_from_url(read_replica_url) if token_auth is not None else None
+ )
+ # Mint a fresh token for the reader BEFORE constructing the
# Prisma client. Mirrors what `proxy_cli.py` already does for
- # the writer (proxy_cli.py:812-832) — without this, the reader
- # Prisma is built with whatever placeholder URL the user
- # supplied (no real token), and the first query falls through
- # to the synchronous fallback path in
- # `PrismaWrapper.__getattr__`, which deadlocks the event loop
- # and times out after 30s.
- if iam_flag and reader_iam_endpoint is not None:
- from litellm.proxy.auth.rds_iam_token import (
- generate_iam_auth_token,
- )
-
- reader_token: Final = generate_iam_auth_token(
- db_host=reader_iam_endpoint.host,
- db_port=reader_iam_endpoint.port,
- db_user=reader_iam_endpoint.user,
- )
+ # the writer — without this, the reader Prisma is built with
+ # whatever placeholder URL the user supplied (no real token),
+ # and the first query falls through to the synchronous fallback
+ # path in `PrismaWrapper.__getattr__`, which deadlocks the event
+ # loop and times out after 30s.
+ if token_auth is not None and reader_iam_endpoint is not None:
+ reader_token: Final = mint_database_token(token_auth, reader_iam_endpoint)
read_replica_url = reader_iam_endpoint.build_url(reader_token)
os.environ["DATABASE_URL_READ_REPLICA"] = read_replica_url
reader_kwargs: Final[dict[str, Any]] = {"datasource": {"url": read_replica_url}}
@@ -3345,7 +3343,7 @@ class PrismaClient:
reader_prisma = Prisma(**reader_kwargs)
reader_wrapper: Final = PrismaWrapper(
original_prisma=reader_prisma,
- iam_token_db_auth=iam_flag,
+ token_auth=token_auth,
db_url_env_var="DATABASE_URL_READ_REPLICA",
iam_endpoint=reader_iam_endpoint,
recreate_uses_datasource=True,
@@ -3354,15 +3352,15 @@ class PrismaClient:
self.db = RoutingPrismaWrapper(writer=writer_wrapper, reader=reader_wrapper)
verbose_proxy_logger.info(
"PrismaClient: read-replica routing enabled via DATABASE_URL_READ_REPLICA"
- + (" (with IAM token auto-refresh)" if iam_flag else "")
+ + (f" (with {token_auth.label} auto-refresh)" if token_auth is not None else "")
)
except Exception as e:
# Reader is opt-in; never let its construction fail proxy
# startup. Mirrors the runtime contract from
# `RoutingPrismaWrapper.connect`: reader-side failures are
# logged and we keep serving traffic via the writer alone.
- # This recovers from transient AWS STS hiccups during the
- # reader IAM token mint, malformed DATABASE_URL_READ_REPLICA,
+ # This recovers from transient credential-provider hiccups
+ # during the reader token mint, malformed DATABASE_URL_READ_REPLICA,
# and Prisma construction errors. Operator restart is required
# to retry read-routing once the underlying issue is resolved.
verbose_proxy_logger.warning(
diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json
index 5c312dcf1c8..be08122d0e5 100644
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@ -57,7 +57,7 @@
"limit": 3
},
"BLE001": {
- "limit": 2923
+ "limit": 2921
},
"C401": {
"limit": 8
diff --git a/tests/test_litellm/proxy/db/conftest.py b/tests/test_litellm/proxy/db/conftest.py
index a0fb6bed4fa..6f67b91ac1d 100644
--- a/tests/test_litellm/proxy/db/conftest.py
+++ b/tests/test_litellm/proxy/db/conftest.py
@@ -6,6 +6,7 @@ import pytest
DB_ENV_KEYS = (
"IAM_TOKEN_DB_AUTH",
+ "AZURE_POSTGRESQL_AUTH",
"DATABASE_URL",
"DIRECT_URL",
"DATABASE_URL_READ_REPLICA",
@@ -59,6 +60,17 @@ def pytest_runtest_teardown(item: pytest.Item, nextitem: Optional[pytest.Item])
return result
[email protected](autouse=True)
+def reset_entra_token_provider_cache() -> Generator[None, None, None]:
+ """The Entra provider factory is cached process-wide so one Azure credential serves
+ the whole proxy; that cache would otherwise carry one test's stub into the next."""
+ from litellm.proxy.db.token_auth import build_azure_entra_token_provider
+
+ build_azure_entra_token_provider.cache_clear()
+ yield
+ build_azure_entra_token_provider.cache_clear()
+
+
@pytest.fixture
def unset_database_url(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DATABASE_URL", "about-to-be-unset")
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 e5aa09addab..35ee8349f90 100644
--- a/tests/test_litellm/proxy/db/test_db_url_settings.py
+++ b/tests/test_litellm/proxy/db/test_db_url_settings.py
@@ -3,8 +3,8 @@
The model assembles ``DATABASE_URL`` (and optionally
``DATABASE_URL_READ_REPLICA``) from the discrete ``DATABASE_*`` env vars
emitted by the ``helm/litellm`` chart, before Prisma initializes. It covers
-both IAM auth (mint a short-lived token) and password auth, for both the
-writer and the read replica.
+both token auth (mint a short-lived AWS RDS IAM or Microsoft Entra ID token)
+and password auth, for both the writer and the read replica.
The reader URL is opt-in via ``DATABASE_HOST_READ_REPLICA`` and must not
clobber a pre-existing ``DATABASE_URL_READ_REPLICA``. A pre-existing
@@ -21,6 +21,7 @@ from litellm.proxy.db.db_url_settings import (
unsupported_db_scheme,
unsupported_db_scheme_message,
)
+from litellm.proxy.db.token_auth import AzureEntraTokenAuth, RdsIamTokenAuth
def _apply() -> bool:
@@ -30,6 +31,7 @@ def _apply() -> bool:
_MANAGED_DB_ENV_VARS = (
"IAM_TOKEN_DB_AUTH",
+ "AZURE_POSTGRESQL_AUTH",
"DATABASE_URL",
"DIRECT_URL",
"DATABASE_URL_READ_REPLICA",
@@ -76,6 +78,14 @@ def _stub_iam_token(token: str = "FAKE_TOKEN"):
)
+def _stub_entra_token(token: str = "FAKE_TOKEN"):
+ """Patch the Azure-touching token provider so tests don't need azure-identity."""
+ return patch(
+ "litellm.secret_managers.get_azure_ad_token_provider.get_azure_ad_token_provider",
+ return_value=lambda: token,
+ )
+
+
# ---------------------------------------------------------------------------
# IAM auth
# ---------------------------------------------------------------------------
@@ -184,6 +194,123 @@ def test_reader_field_fallbacks_default_to_writer_values(monkeypatch):
)
+# ---------------------------------------------------------------------------
+# Azure Entra auth
+# ---------------------------------------------------------------------------
+
+
+def test_assembles_writer_url_when_azure_entra_enabled(monkeypatch):
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "true")
+ monkeypatch.setenv("DATABASE_HOST", "writer.postgres.database.azure.com")
+ monkeypatch.setenv("DATABASE_USER", "[email protected]")
+ monkeypatch.setenv("DATABASE_NAME", "litellm_db")
+
+ with _stub_entra_token("ENTRA_TOKEN"):
+ assert _apply() is True
+
+ assert os.environ["DATABASE_URL"] == (
+ "postgresql://litellm%40contoso.onmicrosoft.com:ENTRA_TOKEN"
+ "@writer.postgres.database.azure.com:5432/litellm_db"
+ )
+ assert os.environ["AZURE_POSTGRESQL_AUTH"] == "True"
+ assert "IAM_TOKEN_DB_AUTH" not in os.environ
+
+
+def test_azure_reader_url_assembled_from_writer_fallbacks(monkeypatch):
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "true")
+ monkeypatch.setenv("DATABASE_HOST", "writer.postgres.database.azure.com")
+ monkeypatch.setenv("DATABASE_USER", "[email protected]")
+ monkeypatch.setenv("DATABASE_NAME", "litellm_db")
+ monkeypatch.setenv("DATABASE_SCHEMA", "public")
+ monkeypatch.setenv("DATABASE_HOST_READ_REPLICA", "reader.postgres.database.azure.com")
+
+ with _stub_entra_token("ENTRA_TOKEN"):
+ _apply()
+
+ assert os.environ["DATABASE_URL_READ_REPLICA"] == (
+ "postgresql://litellm%40contoso.onmicrosoft.com:ENTRA_TOKEN"
+ "@reader.postgres.database.azure.com:5432/litellm_db?schema=public"
+ )
+
+
+def test_azure_missing_writer_envs_names_the_azure_toggle(monkeypatch):
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "true")
+ # DATABASE_HOST intentionally unset.
+ monkeypatch.setenv("DATABASE_USER", "[email protected]")
+ monkeypatch.setenv("DATABASE_NAME", "litellm_db")
+
+ with pytest.raises(RuntimeError, match="AZURE_POSTGRESQL_AUTH is enabled but"):
+ _apply()
+
+
+def test_both_token_toggles_is_a_startup_error(monkeypatch):
+ monkeypatch.setenv("IAM_TOKEN_DB_AUTH", "true")
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "true")
+ monkeypatch.setenv("DATABASE_HOST", "writer.example.com")
+ monkeypatch.setenv("DATABASE_USER", "litellm")
+ monkeypatch.setenv("DATABASE_NAME", "litellm_db")
+
+ with pytest.raises(RuntimeError, match="can only come from one token source"):
+ _apply()
+
+ assert "DATABASE_URL" not in os.environ
+
+
+ "env_var, expected_type",
+ [("IAM_TOKEN_DB_AUTH", RdsIamTokenAuth), ("AZURE_POSTGRESQL_AUTH", AzureEntraTokenAuth)],
+)
+def test_token_auth_reflects_the_enabled_toggle(monkeypatch, env_var, expected_type):
+ monkeypatch.setenv(env_var, "true")
+
+ with _stub_entra_token():
+ assert isinstance(DatabaseURLSettings.from_env().token_auth(), expected_type)
+
+
+def test_the_toggle_agrees_with_the_refresh_loop_on_every_spelling(monkeypatch):
+ """This model and `resolve_database_token_auth` (which arms the refresh loop) both
+ read the same env var. When they disagreed, `AZURE_POSTGRESQL_AUTH=1` minted a token
+ here and left the refresh loop convinced token auth was off."""
+ from litellm.proxy.db.token_auth import resolve_database_token_auth
+
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "1")
+
+ with _stub_entra_token():
+ settings_says = DatabaseURLSettings.from_env().azure_postgresql_auth
+ refresh_loop_says = resolve_database_token_auth() is not None
+
+ assert settings_says is True
+ assert refresh_loop_says is True
+
+
+def test_an_empty_toggle_is_off_rather_than_a_validation_error(monkeypatch):
+ """`value: ""` is how a Kubernetes manifest spells 'off', and the componentized
+ entrypoints build this model at import time, so a raise there is a crash loop."""
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "")
+ monkeypatch.setenv("IAM_TOKEN_DB_AUTH", "")
+
+ settings = DatabaseURLSettings.from_env()
+
+ assert (settings.azure_postgresql_auth, settings.iam_token_db_auth) == (False, False)
+ assert settings.token_auth() is None
+
+
+def test_apply_writer_url_to_env_leaves_the_reader_alone(monkeypatch):
+ """The CLI shares the writer minting path but resolves the read replica itself, so
+ it must not start writing DATABASE_URL_READ_REPLICA as a side effect."""
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "true")
+ monkeypatch.setenv("DATABASE_HOST", "writer.postgres.database.azure.com")
+ monkeypatch.setenv("DATABASE_USER", "litellm")
+ monkeypatch.setenv("DATABASE_NAME", "litellm_db")
+ monkeypatch.setenv("DATABASE_HOST_READ_REPLICA", "reader.postgres.database.azure.com")
+
+ with _stub_entra_token("ENTRA_TOKEN"):
+ assert DatabaseURLSettings.from_env().apply_writer_url_to_env() is True
+
+ assert "DATABASE_URL" in os.environ
+ assert "DATABASE_URL_READ_REPLICA" not in os.environ
+
+
# ---------------------------------------------------------------------------
# Password auth
# ---------------------------------------------------------------------------
diff --git a/tests/test_litellm/proxy/db/test_prisma_client.py b/tests/test_litellm/proxy/db/test_prisma_client.py
index 08b873dfc44..a67f48f1a74 100644
--- a/tests/test_litellm/proxy/db/test_prisma_client.py
+++ b/tests/test_litellm/proxy/db/test_prisma_client.py
@@ -2,6 +2,7 @@ import json
import os
import signal
import sys
+import urllib.parse
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
@@ -215,3 +216,113 @@ def test_db_push_applies_replica_identity_full_when_requested(monkeypatch):
assert mock_run.call_args[0][0][:3] == ["prisma", "db", "push"]
assert applied == [True]
+
+
+def _entra_jwt(expires_in_seconds: int) -> str:
+ """A JWT shaped like a real Entra access token, expiring ``expires_in_seconds`` from now."""
+ import base64
+ from datetime import datetime, timedelta, timezone
+
+ exp = int((datetime.now(tz=timezone.utc) + timedelta(seconds=expires_in_seconds)).timestamp())
+ payload = base64.urlsafe_b64encode(json.dumps({"exp": exp}).encode()).rstrip(b"=").decode()
+ return f"aGVhZGVy.{payload}.c2ln"
+
+
+def azure_env(monkeypatch, unset_database_url):
+ monkeypatch.setenv("DATABASE_HOST", "pg.postgres.database.azure.com")
+ monkeypatch.setenv("DATABASE_PORT", "5432")
+ monkeypatch.setenv("DATABASE_USER", "[email protected]")
+ monkeypatch.setenv("DATABASE_NAME", "litellm_db")
+
+
+def _azure_wrapper(token: str, **kwargs):
+ from litellm.proxy.db.token_auth import AzureEntraTokenAuth
+
+ return PrismaWrapper(
+ original_prisma=MagicMock(),
+ token_auth=AzureEntraTokenAuth(token_provider=lambda: token),
+ **kwargs,
+ )
+
+
+def test_azure_entra_mint_writes_an_encoded_url_into_the_db_url_env_var(azure_env):
+ """The UPN user and the JWT both have to survive being embedded in a URL."""
+ token = _entra_jwt(3600)
+ wrapper = _azure_wrapper(token)
+
+ db_url = wrapper.get_rds_iam_token()
+
+ assert db_url == (
+ f"postgresql://litellm%40contoso.onmicrosoft.com:{urllib.parse.quote(token, safe='')}"
+ "@pg.postgres.database.azure.com:5432/litellm_db"
+ )
+ assert os.environ["DATABASE_URL"] == db_url
+
+
+def test_azure_entra_refresh_is_scheduled_off_the_jwt_expiry(azure_env):
+ """Without reading `exp` this falls back to a fixed 600s interval, which silently
+ outlives a token and breaks every reconnect after it lapses (issue #29661)."""
+ wrapper = _azure_wrapper(_entra_jwt(3600))
+ wrapper.get_rds_iam_token()
+
+ seconds = wrapper._calculate_seconds_until_refresh()
+
+ expected = 3600 - PrismaWrapper.TOKEN_REFRESH_BUFFER_SECONDS
+ assert seconds != PrismaWrapper.FALLBACK_REFRESH_INTERVAL_SECONDS
+ assert expected - 5 <= seconds <= expected
+
+
+def test_azure_entra_token_expiry_is_detected(azure_env):
+ wrapper = _azure_wrapper(_entra_jwt(3600))
+ fresh_url = wrapper.get_rds_iam_token()
+ expired_url = _azure_wrapper(_entra_jwt(-1)).get_rds_iam_token()
+
+ assert wrapper.is_token_expired(fresh_url) is False
+ assert wrapper.is_token_expired(expired_url) is True
+
+
+async def test_azure_entra_strategy_starts_the_refresh_task(azure_env):
+ """The refresh loop is gated on the legacy boolean, so an Azure strategy has to
+ get past that gate; a password-auth wrapper still must not start a task."""
+ wrapper = _azure_wrapper(_entra_jwt(3600))
+ wrapper.get_rds_iam_token()
+ password_wrapper = PrismaWrapper(original_prisma=MagicMock())
+
+ await wrapper.start_token_refresh_task()
+ await password_wrapper.start_token_refresh_task()
+ try:
+ assert wrapper._token_refresh_task is not None
+ assert not wrapper._token_refresh_task.done()
+ assert password_wrapper._token_refresh_task is None
+ finally:
+ await wrapper.stop_token_refresh_task()
+
+
+def test_azure_entra_strategy_reads_as_token_auth_enabled(azure_env):
+ """`routing_prisma_wrapper` gates the reader's refresh on this flag, so an Azure
+ reader has to answer True to it."""
+ wrapper = _azure_wrapper(_entra_jwt(3600))
+
+ assert wrapper.iam_token_db_auth is True
+ assert wrapper.token_label == "Azure Entra token"
+
+
+def test_the_token_strategy_cannot_be_swapped_after_construction(azure_env):
+ """Assigning the legacy boolean used to replace a configured Entra strategy with the
+ RDS one, which points boto at an Azure host."""
+ wrapper = _azure_wrapper(_entra_jwt(3600))
+
+ with pytest.raises(AttributeError):
+ wrapper.iam_token_db_auth = True
+
+
+def test_minting_without_the_database_env_vars_names_them(azure_env, monkeypatch):
+ """A blank host used to produce `postgresql://:<token>@:5432/`, which fails deep
+ inside Prisma instead of at the misconfiguration."""
+ monkeypatch.delenv("DATABASE_HOST")
+ wrapper = _azure_wrapper(_entra_jwt(3600))
+
+ with pytest.raises(RuntimeError, match="DATABASE_HOST"):
+ wrapper.get_rds_iam_token()
diff --git a/tests/test_litellm/proxy/db/test_routing_prisma_wrapper.py b/tests/test_litellm/proxy/db/test_routing_prisma_wrapper.py
index e5bb8b99507..11ed63cf8f0 100644
--- a/tests/test_litellm/proxy/db/test_routing_prisma_wrapper.py
+++ b/tests/test_litellm/proxy/db/test_routing_prisma_wrapper.py
@@ -991,3 +991,52 @@ async def test_recreate_keeps_writer_unavailable_when_writer_recreate_fails():
await routing.recreate_prisma_client("writer-url")
assert routing.writer_unavailable is True
+
+
+def test_prisma_client_premints_an_entra_token_for_the_reader(monkeypatch):
+ """Under Azure Entra auth the reader has to be pre-minted the same way the RDS
+ reader already is: Prisma is constructed with a `datasource` URL, so a reader built
+ from the operator's placeholder URL would never carry a real token."""
+ from litellm.proxy.db.prisma_client import PrismaWrapper
+ from litellm.proxy.db.routing_prisma_wrapper import RoutingPrismaWrapper
+ from litellm.proxy.db.token_auth import AzureEntraTokenAuth
+
+ monkeypatch.setenv("AZURE_POSTGRESQL_AUTH", "true")
+ monkeypatch.delenv("IAM_TOKEN_DB_AUTH", raising=False)
+ monkeypatch.setenv(
+ "DATABASE_URL_READ_REPLICA",
+ "postgresql://litellm%[email protected]:5432/litellm",
+ )
+
+ captured_kwargs: Dict[str, Any] = {}
+
+ class FakePrisma:
+ def __init__(self, **kwargs):
+ captured_kwargs.update(kwargs)
+
+ async def connect(self):
+ return None
+
+ fake_prisma_module = MagicMock()
+ fake_prisma_module.Prisma = FakePrisma
+ monkeypatch.setitem(sys.modules, "prisma", fake_prisma_module)
+
+ with patch(
+ "litellm.secret_managers.get_azure_ad_token_provider.get_azure_ad_token_provider",
+ return_value=lambda: "ENTRA-TOKEN",
+ ):
+ from litellm.proxy.utils import PrismaClient
+
+ client = PrismaClient(
+ database_url="postgresql://[email protected]:5432/litellm",
+ proxy_logging_obj=MagicMock(),
+ )
+
+ assert isinstance(client.db, RoutingPrismaWrapper)
+ assert captured_kwargs["datasource"] == {
+ "url": "postgresql://litellm%40contoso.com:[email protected]:5432/litellm"
+ }
+ assert os.environ["DATABASE_URL_READ_REPLICA"] == captured_kwargs["datasource"]["url"]
+ assert isinstance(client.db._reader.token_auth, AzureEntraTokenAuth)
+ assert isinstance(client.db._writer.token_auth, AzureEntraTokenAuth)
+ assert isinstance(client.db._writer, PrismaWrapper)
diff --git a/tests/test_litellm/proxy/db/test_token_auth.py b/tests/test_litellm/proxy/db/test_token_auth.py
new file mode 100644
index 00000000000..493daf5ac23
--- /dev/null
+++ b/tests/test_litellm/proxy/db/test_token_auth.py
@@ -0,0 +1,292 @@
+"""Tests for the database token auth strategies.
+
+``litellm/proxy/db/token_auth.py`` decides where the proxy's Postgres password
+comes from: an AWS RDS IAM token, a Microsoft Entra ID access token for Azure
+Database for PostgreSQL, or neither. Minting and expiry parsing dispatch over
+that union, so both variants are exercised here, together with the URL encoding
+that lets an Entra principal (a UPN containing ``@``) survive being embedded in
+a connection URL.
+"""
+
+import base64
+import json
+from datetime import datetime, timezone
+from unittest.mock import patch
+
+import pytest
+
+from litellm.proxy.db.token_auth import (
+ AZURE_POSTGRESQL_AUTH_ENV_VAR,
+ AZURE_POSTGRESQL_SCOPE,
+ IAM_TOKEN_DB_AUTH_ENV_VAR,
+ AzureEntraTokenAuth,
+ IAMEndpoint,
+ RdsIamTokenAuth,
+ build_azure_entra_token_provider,
+ mint_database_token,
+ parse_database_token_expiration,
+ parse_iam_endpoint_from_url,
+ resolve_database_token_auth,
+)
+
+
+def _entra_token(exp: int, *, header: str = "eyJhbGciOiJSUzI1NiJ9") -> str:
+ """A JWT shaped like a real Entra access token, carrying ``exp``."""
+ payload = base64.urlsafe_b64encode(
+ json.dumps({"aud": "https://ossrdbms-aad.database.windows.net", "exp": exp}).encode()
+ ).rstrip(b"=")
+ return f"{header}.{payload.decode()}.c2lnbmF0dXJl"
+
+
+def _endpoint(**overrides) -> IAMEndpoint:
+ fields = {
+ "host": "pg.postgres.database.azure.com",
+ "port": "5432",
+ "user": "litellm",
+ "name": "litellm_db",
+ }
+ fields.update(overrides)
+ return IAMEndpoint(**fields)
+
+
+# ---------------------------------------------------------------------------
+# Minting
+# ---------------------------------------------------------------------------
+
+
+def test_rds_mint_delegates_to_the_sigv4_token_generator():
+ endpoint = _endpoint(host="writer.aurora.local", user="litellm_rds")
+
+ with patch(
+ "litellm.proxy.auth.rds_iam_token.generate_iam_auth_token",
+ return_value="SIGV4_TOKEN",
+ ) as generate:
+ token = mint_database_token(RdsIamTokenAuth(), endpoint)
+
+ assert token == "SIGV4_TOKEN"
+ generate.assert_called_once_with(
+ db_host="writer.aurora.local",
+ db_port="5432",
+ db_user="litellm_rds",
+ )
+
+
+def test_entra_mint_calls_the_injected_provider_and_encodes_the_token():
+ """A real compact JWT is already URL-safe, but the provider is an Azure SDK call
+ whose output we do not control, and an unencoded ``/`` or ``=`` in a password
+ silently truncates the connection URL."""
+ auth = AzureEntraTokenAuth(token_provider=lambda: "head.pay/load+x=.sig")
+
+ assert mint_database_token(auth, _endpoint()) == "head.pay%2Fload%2Bx%3D.sig"
+
+
+def test_entra_mint_asks_the_provider_every_time():
+ """A refresh must get a new token, not a cached one from construction time."""
+ tokens = iter(["first", "second"])
+ auth = AzureEntraTokenAuth(token_provider=lambda: next(tokens))
+
+ assert mint_database_token(auth, _endpoint()) == "first"
+ assert mint_database_token(auth, _endpoint()) == "second"
+
+
+# ---------------------------------------------------------------------------
+# Expiry parsing
+# ---------------------------------------------------------------------------
+
+
+def test_rds_expiry_reads_the_sigv4_query_params():
+ token = "writer.aurora.local:5432/?Action=connect&X-Amz-Date=20260820T101500Z&X-Amz-Expires=900"
+
+ assert parse_database_token_expiration(RdsIamTokenAuth(), token) == datetime(2026, 8, 20, 10, 30, 0)
+
+
+ "token",
+ [
+ "no-query-params",
+ "host/?X-Amz-Date=20260820T101500Z",
+ "host/?X-Amz-Expires=900",
+ "host/?X-Amz-Date=not-a-date&X-Amz-Expires=900",
+ ],
+)
+def test_rds_expiry_returns_none_when_unreadable(token):
+ assert parse_database_token_expiration(RdsIamTokenAuth(), token) is None
+
+
[email protected]("exp", [1787000000, 1787000001, 1787000012, 1787000123])
+def test_entra_expiry_decodes_the_jwt_exp_claim(exp):
+ """Parametrized over several ``exp`` values so the payload length lands on every
+ base64 padding remainder: the JWT payload is stripped of its ``=`` padding and has
+ to be re-padded before it can be decoded."""
+ auth = AzureEntraTokenAuth(token_provider=lambda: "unused")
+
+ parsed = parse_database_token_expiration(auth, _entra_token(exp))
+
+ assert parsed is not None
+ assert parsed.tzinfo is None
+ assert parsed == datetime.fromtimestamp(exp, tz=timezone.utc).replace(tzinfo=None)
+
+
+ "token",
+ [
+ "not-a-jwt",
+ "only.two",
+ "head.{}.sig",
+ "head.bm90LWpzb24.sig",
+ f"head.{base64.urlsafe_b64encode(b'{}').decode()}.sig",
+ f"head.{base64.urlsafe_b64encode(json.dumps({'exp': 'soon'}).encode()).decode()}.sig",
+ ],
+)
+def test_entra_expiry_returns_none_when_unreadable(token):
+ """An unreadable expiry must degrade to the caller's fallback refresh interval
+ rather than blowing up the refresh loop."""
+ auth = AzureEntraTokenAuth(token_provider=lambda: "unused")
+
+ assert parse_database_token_expiration(auth, token) is None
+
+
+# ---------------------------------------------------------------------------
+# URL building and parsing
+# ---------------------------------------------------------------------------
+
+
+def test_build_url_encodes_a_upn_user_and_the_schema():
+ endpoint = _endpoint(user="[email protected]", name="litellm db", schema="app/schema")
+
+ assert endpoint.build_url("TOKEN") == (
+ "postgresql://litellm%40contoso.onmicrosoft.com:TOKEN"
+ "@pg.postgres.database.azure.com:5432/litellm%20db?schema=app%2Fschema"
+ )
+
+
+def test_build_url_inserts_the_token_verbatim():
+ """Both providers hand the token back already in wire form, so re-encoding it here
+ would double-escape the password."""
+ rds_token = "writer.aurora.local%3A5432%2F%3FAction%3Dconnect%26X-Amz-Date%3D20260820T101500Z"
+
+ assert _endpoint().build_url(rds_token) == (
+ f"postgresql://litellm:{rds_token}@pg.postgres.database.azure.com:5432/litellm_db"
+ )
+
+
+ "endpoint",
+ [
+ IAMEndpoint(host="h.example.com", port="5432", user="litellm", name="litellm_db"),
+ IAMEndpoint(host="h.example.com", port="6543", user="[email protected]", name="db", schema="public"),
+ IAMEndpoint(host="h.example.com", port="5432", user="u", name="litellm db", schema="app schema"),
+ ],
+)
+def test_build_url_and_parse_round_trip(endpoint):
+ assert parse_iam_endpoint_from_url(endpoint.build_url("TOKEN")) == endpoint
+
+
+def test_parse_leaves_an_already_escaped_schema_alone():
+ """``parse_qs`` unquotes query values itself, so unquoting again here would turn a
+ schema that legitimately contains ``%40`` into one containing ``@``."""
+ url = "postgresql://u:[email protected]:5432/db?schema=raw%2540schema"
+
+ assert parse_iam_endpoint_from_url(url).schema == "raw%40schema"
+
+
+# ---------------------------------------------------------------------------
+# Strategy resolution from the environment
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_none_when_neither_toggle_is_set(monkeypatch):
+ monkeypatch.delenv(IAM_TOKEN_DB_AUTH_ENV_VAR, raising=False)
+ monkeypatch.delenv(AZURE_POSTGRESQL_AUTH_ENV_VAR, raising=False)
+
+ assert resolve_database_token_auth() is None
+
+
+def test_resolve_returns_the_rds_strategy(monkeypatch):
+ monkeypatch.setenv(IAM_TOKEN_DB_AUTH_ENV_VAR, "true")
+ monkeypatch.delenv(AZURE_POSTGRESQL_AUTH_ENV_VAR, raising=False)
+
+ assert resolve_database_token_auth() == RdsIamTokenAuth()
+
+
+def test_resolve_returns_the_entra_strategy(monkeypatch):
+ monkeypatch.delenv(IAM_TOKEN_DB_AUTH_ENV_VAR, raising=False)
+ monkeypatch.setenv(AZURE_POSTGRESQL_AUTH_ENV_VAR, "true")
+
+ with patch(
+ "litellm.secret_managers.get_azure_ad_token_provider.get_azure_ad_token_provider",
+ return_value=lambda: "ENTRA_TOKEN",
+ ):
+ auth = resolve_database_token_auth()
+
+ assert isinstance(auth, AzureEntraTokenAuth)
+ assert auth.token_provider() == "ENTRA_TOKEN"
+
+
+def test_resolve_raises_when_both_toggles_are_set(monkeypatch):
+ monkeypatch.setenv(IAM_TOKEN_DB_AUTH_ENV_VAR, "true")
+ monkeypatch.setenv(AZURE_POSTGRESQL_AUTH_ENV_VAR, "true")
+
+ with pytest.raises(RuntimeError, match="can only come from one token source"):
+ resolve_database_token_auth()
+
+
+def test_entra_provider_uses_the_ossrdbms_scope():
+ """The wrong scope mints a token Azure Postgres rejects, so the scope is pinned."""
+ with patch(
+ "litellm.secret_managers.get_azure_ad_token_provider.get_azure_ad_token_provider",
+ return_value=lambda: "ENTRA_TOKEN",
+ ) as get_provider:
+ build_azure_entra_token_provider()
+
+ get_provider.assert_called_once_with(azure_scope="https://ossrdbms-aad.database.windows.net/.default")
+ assert AZURE_POSTGRESQL_SCOPE == "https://ossrdbms-aad.database.windows.net/.default"
+
+
+# ---------------------------------------------------------------------------
+# Toggle parsing
+# ---------------------------------------------------------------------------
+
+
[email protected]("value", ["true", "TRUE", " True ", "1", "yes", "y", "on", "t"])
+def test_every_truthy_spelling_enables_token_auth(monkeypatch, value):
+ """The settings model reads these toggles with pydantic (which accepts all of these)
+ while the refresh loop reads them here. When the two disagreed, `AZURE_POSTGRESQL_AUTH=1`
+ minted a token at startup and then never refreshed it, so the proxy died an hour in."""
+ monkeypatch.setenv(AZURE_POSTGRESQL_AUTH_ENV_VAR, value)
+ monkeypatch.delenv(IAM_TOKEN_DB_AUTH_ENV_VAR, raising=False)
+
+ with patch(
+ "litellm.secret_managers.get_azure_ad_token_provider.get_azure_ad_token_provider",
+ return_value=lambda: "ENTRA_TOKEN",
+ ):
+ assert isinstance(resolve_database_token_auth(), AzureEntraTokenAuth)
+
+
[email protected]("value", ["", " ", "false", "False", "0", "no", "off", "maybe"])
+def test_falsy_and_unrecognized_spellings_leave_token_auth_off(monkeypatch, value):
+ """An empty string is how a Kubernetes manifest spells 'off'."""
+ monkeypatch.setenv(AZURE_POSTGRESQL_AUTH_ENV_VAR, value)
+ monkeypatch.setenv(IAM_TOKEN_DB_AUTH_ENV_VAR, value)
+
+ assert resolve_database_token_auth() is None
+
+
+def test_the_entra_provider_is_built_once_per_process():
+ """Each build is another Azure credential with its own transport and token cache
+ that nothing closes, and the writer, the reader, and the refresh loop each ask."""
+ with patch(
+ "litellm.secret_managers.get_azure_ad_token_provider.get_azure_ad_token_provider",
+ return_value=lambda: "ENTRA_TOKEN",
+ ) as get_provider:
+ assert build_azure_entra_token_provider() is build_azure_entra_token_provider()
+
+ get_provider.assert_called_once()
+
+
+def test_an_unparseable_rds_expiry_degrades_instead_of_raising():
+ """This runs inside `PrismaWrapper.__getattr__`, so anything it raises turns every
+ database call into that error."""
+ absurd = "https://host/?X-Amz-Date=20260820T101500Z&X-Amz-Expires=99999999999999999999"
+
+ assert parse_database_token_expiration(RdsIamTokenAuth(), absurd) is None
diff --git a/tests/test_litellm/proxy/test_component_allowlists.py b/tests/test_litellm/proxy/test_component_allowlists.py
index 3dd8d8b28cd..0fdb43d60da 100644
--- a/tests/test_litellm/proxy/test_component_allowlists.py
+++ b/tests/test_litellm/proxy/test_component_allowlists.py
@@ -75,6 +75,7 @@ _DB_ENV_KEYS = (
"DATABASE_HOST_READ_REPLICA",
"DATABASE_PASSWORD",
"IAM_TOKEN_DB_AUTH",
+ "AZURE_POSTGRESQL_AUTH",
)
_PRE_DB_ENV = {_key: os.environ.pop(_key, None) for _key in _DB_ENV_KEYS}
_PRE_COMPONENT_LIFESPAN = app.router.lifespan_context
diff --git a/tests/test_litellm/proxy/test_proxy_cli.py b/tests/test_litellm/proxy/test_proxy_cli.py
index 20d17b5a510..28f43345350 100644
--- a/tests/test_litellm/proxy/test_proxy_cli.py
+++ b/tests/test_litellm/proxy/test_proxy_cli.py
@@ -1585,6 +1585,7 @@ class TestProxyInitializationHelpers:
"DATABASE_URL": "",
"DIRECT_URL": "",
"IAM_TOKEN_DB_AUTH": "",
+ "AZURE_POSTGRESQL_AUTH": "",
"USE_AWS_KMS": "",
}
with patch.dict(os.environ, env_overrides):
@@ -2335,3 +2336,85 @@ class TestPostgresStatementTimeoutOptions:
standalone_mode=False,
)
return {k: os.environ[k] for k in ("DATABASE_URL", "DIRECT_URL") if k in os.environ}
+
+
+class TestTokenAuthCliFlags:
+ """`--azure_postgresql_auth` has to reach the URL assembly the same way the env var does."""
+
+ def _invoke_with_azure_host(self, args):
+ from click.testing import CliRunner
+
+ from litellm.proxy.db.token_auth import build_azure_entra_token_provider
+ from litellm.proxy.proxy_cli import run_server
+
+ build_azure_entra_token_provider.cache_clear()
+ clean_env = {
+ k: v
+ for k, v in os.environ.items()
+ if k
+ not in (
+ "DATABASE_URL",
+ "DIRECT_URL",
+ "IAM_TOKEN_DB_AUTH",
+ "AZURE_POSTGRESQL_AUTH",
+ "DATABASE_URL_READ_REPLICA",
+ )
+ }
+ clean_env["DATABASE_HOST"] = "writer.postgres.database.azure.com"
+ clean_env["DATABASE_USER"] = "[email protected]"
+ clean_env["DATABASE_NAME"] = "litellm_db"
+
+ mock_proxy_module = MagicMock(
+ app=MagicMock(),
+ ProxyConfig=MagicMock(),
+ KeyManagementSettings=MagicMock(),
+ save_worker_config=MagicMock(),
+ )
+ with (
+ patch.dict(os.environ, clean_env, clear=True),
+ patch.dict(
+ "sys.modules",
+ {
+ "proxy_server": mock_proxy_module,
+ "litellm.proxy.proxy_server": mock_proxy_module,
+ },
+ ),
+ patch(
+ "litellm.secret_managers.get_azure_ad_token_provider.get_azure_ad_token_provider",
+ return_value=lambda: "ENTRA_TOKEN",
+ ),
+ patch("litellm.proxy.db.prisma_client.should_update_prisma_schema", return_value=False),
+ patch("litellm.proxy.db.prisma_client.PrismaManager.setup_database"),
+ patch("uvicorn.run"),
+ patch(
+ "litellm.proxy.proxy_cli.ProxyInitializationHelpers._get_default_unvicorn_init_args"
+ ) as mock_get_args,
+ ):
+ mock_get_args.return_value = {
+ "app": "litellm.proxy.proxy_server:app",
+ "host": "localhost",
+ "port": 8000,
+ }
+ result = CliRunner().invoke(run_server, args)
+ database_url = os.getenv("DATABASE_URL")
+ toggle = os.getenv("AZURE_POSTGRESQL_AUTH")
+ build_azure_entra_token_provider.cache_clear()
+ return result, database_url, toggle
+
+ def test_azure_flag_assembles_a_token_bearing_database_url(self):
+ result, database_url, toggle = self._invoke_with_azure_host(
+ ["--local", "--azure_postgresql_auth"]
+ )
+
+ assert result.exit_code == 0, f"exit_code={result.exit_code}, output={result.output}"
+ assert database_url is not None
+ assert "ENTRA_TOKEN" in database_url
+ assert "writer.postgres.database.azure.com" in database_url
+ assert toggle == "True"
+
+ def test_without_the_flag_no_token_is_minted(self):
+ result, database_url, toggle = self._invoke_with_azure_host(["--local"])
+
+ 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
diff --git a/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_lifecycle.py b/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_lifecycle.py
index 30fd4a74bb0..18b02ac7772 100644
--- a/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_lifecycle.py
+++ b/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_lifecycle.py
@@ -36,7 +36,7 @@ async def test_prismaclient_init_wires_default_config(
proxy_logging_obj=proxy_logging,
)
pinned = {
- "iam_token_db_auth": pc.iam_token_db_auth,
+ "token_auth": pc.token_auth,
"db_reconnect_cooldown_seconds": pc._db_reconnect_cooldown_seconds,
"db_health_watchdog_interval_seconds": pc._db_health_watchdog_interval_seconds,
"db_health_watchdog_enabled": pc._db_health_watchdog_enabled,
@@ -48,7 +48,7 @@ async def test_prismaclient_init_wires_default_config(
"db_reconnect_lock_is_lock": isinstance(pc._db_reconnect_lock, asyncio.Lock),
}
assert pinned == {
- "iam_token_db_auth": None,
+ "token_auth": None,
"db_reconnect_cooldown_seconds": 15,
"db_health_watchdog_interval_seconds": 30,
"db_health_watchdog_enabled": True,
diff --git a/type-discipline-budget.json b/type-discipline-budget.json
index 20cd1165577..3293d94c536 100644
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@ -3,7 +3,7 @@
"limit": 22805
},
"LIT002": {
- "limit": 26878
+ "limit": 26870
},
"LIT003": {
"limit": 269
@@ -27,7 +27,7 @@
"limit": 0
},
"LIT010": {
- "limit": 16695
+ "limit": 16654
},
"LIT011": {
"limit": 5588