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(bedrock): stop replaying expired Google OIDC tokens to STS on guardrail auth (#34637)

yucheng-berri1776daa267e3
diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.py
index df811f8d262..6b89fb69739 100644
--- a/litellm/llms/bedrock/base_aws_llm.py
+++ b/litellm/llms/bedrock/base_aws_llm.py
@@ -78,8 +78,10 @@ class BaseAWSLLM:
# Storage is in-process memory only: default ``DualCache()`` has no Redis backend unless attached
# elsewhere. Entry TTL: static access-key + secret + region use ``_get_default_ttl_for_boto3_credentials``
# (~59 minutes); ambient env (``_auth_with_env_vars`` returns ``ttl=None``) uses ``InMemoryCache``'s
- # ``default_ttl`` (600 seconds / 10 minutes). AssumeRole, web identity, profiles, and explicit
- # session-token tuples are not cached — see ``get_credentials`` and ``_get_or_set_cached_credentials``.
+ # ``default_ttl`` (600 seconds / 10 minutes); web identity STS credentials use
+ # ``_get_default_ttl_for_boto3_credentials`` (~59 minutes), keyed on all aws_* credential args
+ # plus ssl_verify. AssumeRole, profiles, and explicit session-token tuples are not cached — see
+ # ``get_credentials`` and ``_get_or_set_cached_credentials``.
_shared_iam_cache: ClassVar[DualCache] = DualCache()
def __init__(self) -> None:
@@ -136,11 +138,12 @@ class BaseAWSLLM:
which ``InMemoryCache.set_cache`` resolves to ``default_ttl`` (600 seconds / 10 minutes by
default).
- Used only for static access-key credentials and ambient credentials from
+ Used for static access-key credentials, ambient credentials from
``_auth_with_env_vars`` (including when skipping AssumeRole because the runtime identity
- already matches ``aws_role_name``).
+ already matches ``aws_role_name``), and web identity STS credentials (plain
+ non-refreshable ``Credentials`` cached ~59 min, inside the 3600s STS session).
- AssumeRole, web identity exchange, profiles, and explicit session-token tuples are not
+ AssumeRole, profiles, and explicit session-token tuples are not
cached here — shared ``Credentials`` / refresh state must not span logical sessions.
"""
cache_key = self.get_cache_key(credential_args)
@@ -266,23 +269,26 @@ class BaseAWSLLM:
# Credentials - boto3.Credentials
# cache ttl - Optional[int]. If None, the credentials are not cached. Some auth flows have no expiry time.
#
- # iam_cache: static keys and ambient env only (including skip-AssumeRole path).
- # Do not cache AssumeRole / web identity / profile / explicit session-token paths here.
+ # iam_cache: static keys, ambient env (including skip-AssumeRole path), and web identity.
+ # Do not cache AssumeRole / profile / explicit session-token paths here.
#########################################################
if self._is_auth_with_web_identity_token(
aws_web_identity_token,
aws_role_name,
aws_session_name,
):
- credentials, _cache_ttl = self._auth_with_web_identity_token(
- aws_web_identity_token=cast(str, aws_web_identity_token),
- aws_role_name=cast(str, aws_role_name),
- aws_session_name=cast(str, aws_session_name),
- aws_region_name=aws_region_name,
- aws_sts_endpoint=aws_sts_endpoint,
- aws_external_id=aws_external_id,
+ return self._get_or_set_cached_credentials(
+ args,
+ lambda: self._auth_with_web_identity_token(
+ aws_web_identity_token=cast(str, aws_web_identity_token),
+ aws_role_name=cast(str, aws_role_name),
+ aws_session_name=cast(str, aws_session_name),
+ aws_region_name=aws_region_name,
+ aws_sts_endpoint=aws_sts_endpoint,
+ aws_external_id=aws_external_id,
+ ssl_verify=ssl_verify,
+ ),
)
- return credentials
elif self._is_auth_with_aws_role(aws_role_name):
# Same role (IRSA/ECS/EC2): ambient creds via _get_or_set_cached_credentials like the
# default env branch; never pre-read cache (must run _is_already_running_as_role first).
diff --git a/litellm/secret_managers/main.py b/litellm/secret_managers/main.py
index fa55828a249..88e3ad16cc3 100644
--- a/litellm/secret_managers/main.py
+++ b/litellm/secret_managers/main.py
@@ -1,9 +1,12 @@
import ast
+import base64
import os
+import time
import traceback
from typing import Optional, Union
import httpx
+from pydantic import BaseModel, ValidationError
import litellm
from litellm._logging import verbose_logger
@@ -16,6 +19,33 @@ from litellm.secret_managers.secret_manager_handler import get_secret_from_manag
oidc_cache = DualCache()
+
+_OIDC_TOKEN_EXPIRY_MARGIN_SECONDS = 60
+
+
+class _OidcTokenClaims(BaseModel):
+ exp: float | None = None
+
+
+def _oidc_token_cache_ttl(oidc_token: str, max_ttl: int) -> int:
+ """Cache TTL for a fetched OIDC token: ``max_ttl``, capped so the cache entry
+ never outlives the token's own ``exp`` claim (minus a safety margin).
+ Falls back to ``max_ttl`` when the token carries no readable ``exp``."""
+ segments = oidc_token.split(".")
+ if len(segments) != 3:
+ return max_ttl
+ payload = segments[1]
+ try:
+ decoded = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))
+ claims = _OidcTokenClaims.model_validate_json(decoded)
+ if claims.exp is None:
+ return max_ttl
+ exp = int(claims.exp)
+ except (ValueError, OverflowError, ValidationError):
+ return max_ttl
+ return min(max_ttl, exp - int(time.time()) - _OIDC_TOKEN_EXPIRY_MARGIN_SECONDS)
+
+
_DEFAULT_OIDC_ALLOWED_CREDENTIAL_DIRS = ("/var/run/secrets", "/run/secrets")
@@ -187,7 +217,15 @@ def get_secret(
)
if response.status_code == 200:
oidc_token = response.text
- oidc_cache.set_cache(key=secret_name, value=oidc_token, ttl=3600 - 60)
+ ttl = _oidc_token_cache_ttl(oidc_token, 3600 - 60)
+ if ttl > 0:
+ oidc_cache.set_cache(key=secret_name, value=oidc_token, ttl=ttl)
+ else:
+ verbose_logger.warning(
+ "Google OIDC token for %s is already expired or expires within %ss; not caching it",
+ secret_name,
+ _OIDC_TOKEN_EXPIRY_MARGIN_SECONDS,
+ )
return oidc_token
else:
raise ValueError("Google OIDC provider failed")
diff --git a/tests/test_litellm/llms/bedrock/test_base_aws_llm.py b/tests/test_litellm/llms/bedrock/test_base_aws_llm.py
index aaf523eacd5..200645daee5 100644
--- a/tests/test_litellm/llms/bedrock/test_base_aws_llm.py
+++ b/tests/test_litellm/llms/bedrock/test_base_aws_llm.py
@@ -292,21 +292,55 @@ def test_web_identity_token_oidc_reference_still_resolved():
assert exc.value.status_code == 401
-def test_web_identity_path_not_cached_in_iam_cache():
+def test_web_identity_credentials_cached_in_iam_cache():
+ """
+ Web identity STS credentials are cached for their STS lifetime, so repeated
+ get_credentials calls (e.g. per-request guardrail auth) reuse the assumed-role
+ credentials instead of replaying the OIDC token to STS on every request.
+ """
base = BaseAWSLLM()
with patch.object(
base,
"_auth_with_web_identity_token",
- return_value=(Credentials("wi-ak", "wi-sk", "wi-tok"), None),
+ return_value=(Credentials("wi-ak", "wi-sk", "wi-tok"), 3540),
) as mock_wi:
kwargs = dict(
- aws_web_identity_token="jwt-token",
+ aws_web_identity_token="oidc/google/https://example.com/",
aws_role_name="arn:aws:iam::123456789012:role/WebIdentity",
aws_session_name="web-id-session",
)
- base.get_credentials(**kwargs)
- base.get_credentials(**kwargs)
+ first = base.get_credentials(**kwargs)
+ second = base.get_credentials(**kwargs)
+ assert mock_wi.call_count == 1
+ assert first is second
+
+
+def test_web_identity_cache_is_keyed_on_credential_args():
+ """
+ Two web identity configs that differ in any credential arg (here the role)
+ must not share cached credentials.
+ """
+ base = BaseAWSLLM()
+ with patch.object(
+ base,
+ "_auth_with_web_identity_token",
+ side_effect=[
+ (Credentials("wi-ak-a", "wi-sk-a", "wi-tok-a"), 3540),
+ (Credentials("wi-ak-b", "wi-sk-b", "wi-tok-b"), 3540),
+ ],
+ ) as mock_wi:
+ first = base.get_credentials(
+ aws_web_identity_token="oidc/google/https://example.com/",
+ aws_role_name="arn:aws:iam::123456789012:role/RoleA",
+ aws_session_name="web-id-session",
+ )
+ second = base.get_credentials(
+ aws_web_identity_token="oidc/google/https://example.com/",
+ aws_role_name="arn:aws:iam::123456789012:role/RoleB",
+ aws_session_name="web-id-session",
+ )
assert mock_wi.call_count == 2
+ assert first.access_key != second.access_key
def test_boto3_init_tracer_wrapping():
diff --git a/tests/test_litellm/secret_managers/test_secret_managers_main.py b/tests/test_litellm/secret_managers/test_secret_managers_main.py
index b406231804b..3631f640136 100644
--- a/tests/test_litellm/secret_managers/test_secret_managers_main.py
+++ b/tests/test_litellm/secret_managers/test_secret_managers_main.py
@@ -1,5 +1,8 @@
+import base64
+import json
import logging
import os
+import time
from unittest.mock import Mock, patch
import pytest
@@ -95,6 +98,100 @@ def test_oidc_google_cached():
mock_get_http_handler.assert_not_called()
+def _jwt_with_exp(exp: int) -> str:
+ header = base64.urlsafe_b64encode(json.dumps({"alg": "RS256"}).encode()).rstrip(b"=").decode()
+ payload = base64.urlsafe_b64encode(json.dumps({"exp": exp}).encode()).rstrip(b"=").decode()
+ return f"{header}.{payload}.signature"
+
+
+def test_oidc_google_cache_ttl_capped_by_token_exp():
+ """A token the metadata server returns near its expiry must not be cached past
+ its exp claim; the cached-entry TTL is exp - now - 60s, not the 59m default."""
+ secret_name = "oidc/google/https://example.com/api"
+ mock_handler = MockHTTPHandler(timeout=600.0)
+ mock_handler.text = _jwt_with_exp(int(time.time()) + 300)
+ mock_get_http_handler = Mock(return_value=mock_handler)
+ mock_oidc_cache = Mock()
+ mock_oidc_cache.get_cache.return_value = None
+
+ with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
+ with patch(
+ "litellm.secret_managers.main._get_oidc_http_handler",
+ mock_get_http_handler,
+ ):
+ result = get_secret(secret_name)
+
+ assert result == mock_handler.text
+ mock_oidc_cache.set_cache.assert_called_once()
+ ttl = mock_oidc_cache.set_cache.call_args.kwargs["ttl"]
+ assert 0 < ttl <= 240
+
+
+def test_oidc_google_expired_token_not_cached():
+ """An already-expired token is returned (STS gives the authoritative error) but
+ never cached, so the next call fetches a fresh token instead of replaying it."""
+ secret_name = "oidc/google/https://example.com/api"
+ mock_handler = MockHTTPHandler(timeout=600.0)
+ mock_handler.text = _jwt_with_exp(int(time.time()) - 10)
+ mock_get_http_handler = Mock(return_value=mock_handler)
+ mock_oidc_cache = Mock()
+ mock_oidc_cache.get_cache.return_value = None
+
+ with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
+ with patch(
+ "litellm.secret_managers.main._get_oidc_http_handler",
+ mock_get_http_handler,
+ ):
+ result = get_secret(secret_name)
+
+ assert result == mock_handler.text
+ mock_oidc_cache.set_cache.assert_not_called()
+
+
+def test_oidc_google_long_lived_token_still_capped_at_default_ttl():
+ """A token expiring far in the future must not extend the cache past the
+ 59m policy ceiling; exp only ever shortens the TTL."""
+ secret_name = "oidc/google/https://example.com/api"
+ mock_handler = MockHTTPHandler(timeout=600.0)
+ mock_handler.text = _jwt_with_exp(int(time.time()) + 7200)
+ mock_get_http_handler = Mock(return_value=mock_handler)
+ mock_oidc_cache = Mock()
+ mock_oidc_cache.get_cache.return_value = None
+
+ with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
+ with patch(
+ "litellm.secret_managers.main._get_oidc_http_handler",
+ mock_get_http_handler,
+ ):
+ result = get_secret(secret_name)
+
+ assert result == mock_handler.text
+ mock_oidc_cache.set_cache.assert_called_once_with(
+ key=secret_name, value=mock_handler.text, ttl=3540
+ )
+
+
+def test_oidc_google_non_jwt_token_keeps_default_ttl():
+ """A token without a readable exp claim falls back to the 59m default TTL."""
+ secret_name = "oidc/google/https://example.com/api"
+ mock_handler = MockHTTPHandler(timeout=600.0)
+ mock_get_http_handler = Mock(return_value=mock_handler)
+ mock_oidc_cache = Mock()
+ mock_oidc_cache.get_cache.return_value = None
+
+ with patch("litellm.secret_managers.main.oidc_cache", mock_oidc_cache):
+ with patch(
+ "litellm.secret_managers.main._get_oidc_http_handler",
+ mock_get_http_handler,
+ ):
+ result = get_secret(secret_name)
+
+ assert result == "mocked_token"
+ mock_oidc_cache.set_cache.assert_called_once_with(
+ key=secret_name, value="mocked_token", ttl=3540
+ )
+
+
def test_oidc_google_failure():
"""Test Google OIDC raises when provider returns error (no real network calls)."""
secret_name = "oidc/google/https://example.com/api"