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): chain RDS IAM DB auth through the IRSA role when the DB role trusts only the pod role (#46540)

Yassin Kortam40187731b712
diff --git a/litellm/proxy/auth/rds_iam_token.py b/litellm/proxy/auth/rds_iam_token.py
index f0475c1959f..194e461bf76 100644
--- a/litellm/proxy/auth/rds_iam_token.py
+++ b/litellm/proxy/auth/rds_iam_token.py
@@ -1,9 +1,14 @@
import os
import re
+from collections.abc import Mapping
+from dataclasses import dataclass
+from types import MappingProxyType
from typing import Any, Final
import httpx
+from litellm._logging import verbose_proxy_logger
+
_RDS_HOSTNAME_REGION_PATTERN: Final = re.compile(
r"(?:[^.]+\.)+(?P<region>[a-z]{2}(?:-[a-z]+)+-\d+)\.rds\.amazonaws\.com(?:\.cn)?\.?",
re.IGNORECASE,
@@ -67,12 +72,7 @@ def init_rds_client(
import boto3
- if isinstance(timeout, float):
- config = boto3.session.Config(connect_timeout=timeout, read_timeout=timeout)
- elif isinstance(timeout, httpx.Timeout):
- config = boto3.session.Config(connect_timeout=timeout.connect, read_timeout=timeout.read)
- else:
- config = boto3.session.Config()
+ config: Final = boto3.session.Config(**_boto_timeouts(timeout))
### CHECK STS ###
if aws_web_identity_token is not None and aws_role_name is not None and aws_session_name is not None:
@@ -86,22 +86,18 @@ def init_rds_client(
"OIDC token could not be retrieved from secret manager.",
)
- sts_client = boto3.client("sts")
-
- # https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html
- # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts/client/assume_role_with_web_identity.html
- sts_response = sts_client.assume_role_with_web_identity(
- RoleArn=aws_role_name,
- RoleSessionName=aws_session_name,
- WebIdentityToken=oidc_token,
- DurationSeconds=3600,
+ web_identity_credentials: Final = _assume_role_with_web_identity(
+ oidc_token=oidc_token,
+ aws_role_name=aws_role_name,
+ aws_session_name=aws_session_name,
+ irsa_role_arn=os.getenv("AWS_ROLE_ARN"),
)
client = boto3.client(
service_name="rds",
- aws_access_key_id=sts_response["Credentials"]["AccessKeyId"],
- aws_secret_access_key=sts_response["Credentials"]["SecretAccessKey"],
- aws_session_token=sts_response["Credentials"]["SessionToken"],
+ aws_access_key_id=web_identity_credentials.access_key_id,
+ aws_secret_access_key=web_identity_credentials.secret_access_key,
+ aws_session_token=web_identity_credentials.session_token,
region_name=region_name,
config=config,
)
@@ -157,6 +153,66 @@ def init_rds_client(
return client
+def _boto_timeouts(timeout: float | httpx.Timeout | None) -> Mapping[str, float | None]:
+ if timeout is None:
+ return MappingProxyType({})
+ if isinstance(timeout, httpx.Timeout):
+ return MappingProxyType({"connect_timeout": timeout.connect, "read_timeout": timeout.read})
+ return MappingProxyType({"connect_timeout": timeout, "read_timeout": timeout})
+
+
+@dataclass(frozen=True, slots=True)
+class _StsCredentials:
+ access_key_id: str
+ secret_access_key: str
+ session_token: str
+
+
+def _assume_role_with_web_identity(
+ *, oidc_token: str, aws_role_name: str, aws_session_name: str, irsa_role_arn: str | None
+) -> _StsCredentials:
+ """Trade the web identity token for credentials on ``aws_role_name``.
+
+ First tries the direct exchange (the role trusts the OIDC provider). When that is refused and the
+ pod runs under IRSA as a different role, chains instead: web identity into the pod role, then
+ ``sts:AssumeRole`` into ``aws_role_name`` (the role trusts the pod role, typically cross-account).
+ """
+ import boto3
+ from botocore.exceptions import ClientError
+
+ sts_client: Final = boto3.client("sts")
+ try:
+ direct: Final = sts_client.assume_role_with_web_identity(
+ RoleArn=aws_role_name,
+ RoleSessionName=aws_session_name,
+ WebIdentityToken=oidc_token,
+ DurationSeconds=3600,
+ )["Credentials"]
+ return _StsCredentials(direct["AccessKeyId"], direct["SecretAccessKey"], direct["SessionToken"])
+ except ClientError as direct_error:
+ if not irsa_role_arn or irsa_role_arn == aws_role_name:
+ raise
+ verbose_proxy_logger.info(
+ "RDS IAM auth: AssumeRoleWithWebIdentity on %s was refused (%s), chaining through IRSA role %s",
+ aws_role_name,
+ direct_error.response.get("Error", {}).get("Code", "unknown"),
+ irsa_role_arn,
+ )
+
+ pod_role: Final = sts_client.assume_role_with_web_identity(
+ RoleArn=irsa_role_arn,
+ RoleSessionName=aws_session_name,
+ WebIdentityToken=oidc_token,
+ )["Credentials"]
+ chained: Final = boto3.client(
+ "sts",
+ aws_access_key_id=pod_role["AccessKeyId"],
+ aws_secret_access_key=pod_role["SecretAccessKey"],
+ aws_session_token=pod_role["SessionToken"],
+ ).assume_role(RoleArn=aws_role_name, RoleSessionName=aws_session_name)["Credentials"]
+ return _StsCredentials(chained["AccessKeyId"], chained["SecretAccessKey"], chained["SessionToken"])
+
+
def rds_region_from_hostname(db_host: str) -> str | None:
match: Final = _RDS_HOSTNAME_REGION_PATTERN.fullmatch(db_host)
if match is None:
diff --git a/tests/unit/proxy/auth/test_rds_iam_token.py b/tests/unit/proxy/auth/test_rds_iam_token.py
index b8dca804ad2..c38d782ed49 100644
--- a/tests/unit/proxy/auth/test_rds_iam_token.py
+++ b/tests/unit/proxy/auth/test_rds_iam_token.py
@@ -1,10 +1,12 @@
+from pathlib import Path
from typing import Final
from urllib.parse import parse_qs, unquote, urlsplit
import boto3
import pytest
+from botocore.exceptions import ClientError
-from litellm.proxy.auth.rds_iam_token import generate_iam_auth_token
+from litellm.proxy.auth.rds_iam_token import generate_iam_auth_token, init_rds_client
@pytest.mark.parametrize(
@@ -51,3 +53,118 @@ def test_generate_iam_auth_token_signs_for_the_database_hostname_region(
assert token.split("?", maxsplit=1)[0] == f"{db_host}:5432/"
assert credential.split("/")[2] == expected_region
+
+
+POD_ROLE: Final = "arn:aws:iam::111111111111:role/litellm-pod-irsa"
+DB_ROLE: Final = "arn:aws:iam::222222222222:role/litellm-db-connect"
+
+
+def _creds(tag: str) -> dict[str, dict[str, str]]:
+ return {
+ "Credentials": {"AccessKeyId": f"ASIA{tag}", "SecretAccessKey": f"secret-{tag}", "SessionToken": f"token-{tag}"}
+ }
+
+
+def _refused(operation: str) -> ClientError:
+ return ClientError({"Error": {"Code": "AccessDenied", "Message": "Not authorized"}}, operation)
+
+
+class _FakeSts:
+ def __init__(
+ self, calls: list[tuple[str, str, str | None]], roles_trusting_oidc: frozenset[str], caller: str | None
+ ) -> None:
+ self._calls: Final = calls
+ self._roles_trusting_oidc: Final = roles_trusting_oidc
+ self._caller: Final = caller
+
+ def assume_role_with_web_identity(
+ self, *, RoleArn: str, RoleSessionName: str, WebIdentityToken: str, **_: int
+ ) -> dict[str, dict[str, str]]:
+ self._calls.append(("web_identity", RoleArn, WebIdentityToken))
+ if RoleArn not in self._roles_trusting_oidc:
+ raise _refused("AssumeRoleWithWebIdentity")
+ return _creds(RoleArn.rsplit("/", maxsplit=1)[1])
+
+ def assume_role(self, *, RoleArn: str, RoleSessionName: str) -> dict[str, dict[str, str]]:
+ self._calls.append(("assume_role", RoleArn, self._caller))
+ if self._caller != f"ASIA{POD_ROLE.rsplit('/', maxsplit=1)[1]}":
+ raise _refused("AssumeRole")
+ return _creds("chained")
+
+
+def _boto3_client_factory(calls: list[tuple[str, str, str | None]], roles_trusting_oidc: frozenset[str]):
+ rds_clients: Final[list[dict[str, str]]] = []
+
+ def client(service_name: str, **kwargs: str) -> object:
+ if service_name == "sts":
+ return _FakeSts(calls, roles_trusting_oidc, kwargs.get("aws_access_key_id"))
+ rds_clients.append({k: v for k, v in kwargs.items() if k.startswith("aws_")})
+ return rds_clients[-1]
+
+ return client, rds_clients
+
+
+def web_identity_token_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> str:
+ token_file: Final = tmp_path / "token"
+ token_file.write_text("eyJ.oidc.token")
+ monkeypatch.setenv("AWS_ROLE_ARN", POD_ROLE)
+ monkeypatch.setenv("AWS_WEB_IDENTITY_TOKEN_FILE", str(token_file))
+ return str(token_file)
+
+
+def _init(
+ monkeypatch: pytest.MonkeyPatch, token_file: str, roles_trusting_oidc: frozenset[str]
+) -> tuple[list[tuple[str, str, str | None]], list[dict[str, str]]]:
+ calls: Final[list[tuple[str, str, str | None]]] = []
+ client, rds_clients = _boto3_client_factory(calls, roles_trusting_oidc)
+ monkeypatch.setattr(boto3, "client", client)
+ init_rds_client(
+ aws_role_name=DB_ROLE,
+ aws_session_name="litellm",
+ aws_web_identity_token=token_file,
+ aws_region_name="us-east-1",
+ )
+ return calls, rds_clients
+
+
+def test_init_rds_client_chains_through_the_irsa_role_when_the_db_role_only_trusts_the_pod_role(
+ web_identity_token_file: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls, rds_clients = _init(monkeypatch, web_identity_token_file, roles_trusting_oidc=frozenset({POD_ROLE}))
+
+ assert rds_clients == [
+ {
+ "aws_access_key_id": "ASIAchained",
+ "aws_secret_access_key": "secret-chained",
+ "aws_session_token": "token-chained",
+ }
+ ]
+ assert calls[-2:] == [
+ ("web_identity", POD_ROLE, "eyJ.oidc.token"),
+ ("assume_role", DB_ROLE, "ASIAlitellm-pod-irsa"),
+ ]
+
+
+def test_init_rds_client_keeps_the_direct_web_identity_exchange_when_the_db_role_trusts_the_oidc_provider(
+ web_identity_token_file: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls, rds_clients = _init(monkeypatch, web_identity_token_file, roles_trusting_oidc=frozenset({POD_ROLE, DB_ROLE}))
+
+ assert rds_clients == [
+ {
+ "aws_access_key_id": "ASIAlitellm-db-connect",
+ "aws_secret_access_key": "secret-litellm-db-connect",
+ "aws_session_token": "token-litellm-db-connect",
+ }
+ ]
+ assert calls == [("web_identity", DB_ROLE, "eyJ.oidc.token")]
+
+
+def test_init_rds_client_surfaces_the_sts_refusal_when_there_is_no_distinct_irsa_role_to_chain_through(
+ web_identity_token_file: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("AWS_ROLE_ARN", DB_ROLE)
+
+ with pytest.raises(ClientError, match="AssumeRoleWithWebIdentity"):
+ _init(monkeypatch, web_identity_token_file, roles_trusting_oidc=frozenset())