The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
refactor(BaseAWSLLM): implement shared IAM cache and static credentia… (#27125)
harish-berri4fec69dd1e30
diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.pyindex dae60948a58..0885775932c 100644--- a/litellm/llms/bedrock/base_aws_llm.py+++ b/litellm/llms/bedrock/base_aws_llm.py@@ -7,6 +7,8 @@ from datetime import datetimefrom typing import (TYPE_CHECKING,Any,+ Callable,+ ClassVar,Dict,List,Literal,@@ -63,8 +65,16 @@ class AwsAuthError(Exception):class BaseAWSLLM:+ # Process-wide IAM credential cache (shared across instances — Bedrock passthrough is per-request).+ # 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``.+ _shared_iam_cache: ClassVar[DualCache] = DualCache()+def __init__(self) -> None:- self.iam_cache = DualCache()+ self.iam_cache = BaseAWSLLM._shared_iam_cachesuper().__init__()self.aws_authentication_params = ["aws_access_key_id",@@ -103,6 +113,79 @@ class BaseAWSLLM:credential_str = json.dumps(credential_args, sort_keys=True)return hashlib.sha256(credential_str.encode()).hexdigest()+ def _get_or_set_cached_credentials(+ self,+ credential_args: Dict[str, Optional[str]],+ credential_fetcher: Callable[[], Tuple[Any, Optional[int]]],+ ) -> Any:+ """+ Read-through IAM cache on the process-wide ``DualCache``.++ Only the in-memory layer is used by default (no Redis on ``_shared_iam_cache`` unless+ configured globally). TTL on write: static access-key fetches pass+ ``_get_default_ttl_for_boto3_credentials()`` (~59 minutes); ambient env passes ``ttl=None``,+ 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+ ``_auth_with_env_vars`` (including when skipping AssumeRole because the runtime identity+ already matches ``aws_role_name``).++ AssumeRole, web identity exchange, 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)+ _cached = self.iam_cache.get_cache(cache_key)+ if _cached:+ return _cached+ credentials, ttl = credential_fetcher()+ self.iam_cache.set_cache(cache_key, credentials, ttl=ttl)+ return credentials++ @staticmethod+ def _is_auth_with_web_identity_token(+ aws_web_identity_token: Optional[str],+ aws_role_name: Optional[str],+ aws_session_name: Optional[str],+ ) -> bool:+ return (+ aws_web_identity_token is not None+ and aws_role_name is not None+ and aws_session_name is not None+ )++ @staticmethod+ def _is_auth_with_aws_role(aws_role_name: Optional[str]) -> bool:+ return aws_role_name is not None++ @staticmethod+ def _is_auth_with_aws_profile(aws_profile_name: Optional[str]) -> bool:+ return aws_profile_name is not None++ @staticmethod+ def _is_auth_with_aws_session_token_tuple(+ aws_access_key_id: Optional[str],+ aws_secret_access_key: Optional[str],+ aws_session_token: Optional[str],+ ) -> bool:+ return (+ aws_access_key_id is not None+ and aws_secret_access_key is not None+ and aws_session_token is not None+ )++ @staticmethod+ def _is_auth_with_access_key_and_secret_key(+ aws_access_key_id: Optional[str],+ aws_secret_access_key: Optional[str],+ aws_region_name: Optional[str],+ ) -> bool:+ return (+ aws_access_key_id is not None+ and aws_secret_access_key is not None+ and aws_region_name is not None+ )+@tracer.wrap()def get_credentials(self,@@ -184,95 +267,97 @@ class BaseAWSLLM:aws_external_id,)- # create cache key for non-expiring auth flowsargs = {k: vfor k, v in locals().items()if k.startswith("aws_") or k == "ssl_verify"}- cache_key = self.get_cache_key(args)- _cached_credentials = self.iam_cache.get_cache(cache_key)- if _cached_credentials:- return _cached_credentials-########################################################## Handle diff boto3 auth flows# for each helper# Return:# 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.#########################################################- if (- aws_web_identity_token is not None- and aws_role_name is not None- and aws_session_name is not None+ 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=aws_web_identity_token,- aws_role_name=aws_role_name,- aws_session_name=aws_session_name,+ 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,)- elif aws_role_name is not None:- # Check if we're already running as the target role and can skip assumption- # This handles IRSA (EKS), ECS task roles, and EC2 instance profiles- if self._is_already_running_as_role(aws_role_name, 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).+ if self._is_already_running_as_role(+ cast(str, aws_role_name), ssl_verify=ssl_verify+ ):verbose_logger.debug("Already running as target role %s, using ambient credentials",aws_role_name,)- credentials, _cache_ttl = self._auth_with_env_vars()- else:- verbose_logger.debug(- "Using role assumption: calling _auth_with_aws_role"- )- # If aws_session_name is not provided, generate a default one- if aws_session_name is None:- aws_session_name = (- f"litellm-session-{int(datetime.now().timestamp())}"- )- credentials, _cache_ttl = self._auth_with_aws_role(- aws_access_key_id=aws_access_key_id,- aws_secret_access_key=aws_secret_access_key,- aws_session_token=aws_session_token,- aws_role_name=aws_role_name,- aws_session_name=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 self._get_or_set_cached_credentials(+ args, self._auth_with_env_vars)-- elif aws_profile_name is not None: ### CHECK SESSION ###- credentials, _cache_ttl = self._auth_with_aws_profile(aws_profile_name)- elif (- aws_access_key_id is not None- and aws_secret_access_key is not None- and aws_session_token is not None- ):- credentials, _cache_ttl = self._auth_with_aws_session_token(+ verbose_logger.debug("Using role assumption: calling _auth_with_aws_role")+ # If aws_session_name is not provided, generate a default one+ if aws_session_name is None:+ aws_session_name = f"litellm-session-{int(datetime.now().timestamp())}"+ credentials, _assume_ttl = self._auth_with_aws_role(aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key,aws_session_token=aws_session_token,+ aws_role_name=cast(str, aws_role_name),+ aws_session_name=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,)- elif (- aws_access_key_id is not None- and aws_secret_access_key is not None- and aws_region_name is not None+ return credentials++ elif self._is_auth_with_aws_profile(aws_profile_name):+ credentials, _cache_ttl = self._auth_with_aws_profile(+ cast(str, aws_profile_name)+ )+ return credentials+ elif self._is_auth_with_aws_session_token_tuple(+ aws_access_key_id,+ aws_secret_access_key,+ aws_session_token,):- credentials, _cache_ttl = self._auth_with_access_key_and_secret_key(- aws_access_key_id=aws_access_key_id,- aws_secret_access_key=aws_secret_access_key,- aws_region_name=aws_region_name,+ credentials, _cache_ttl = self._auth_with_aws_session_token(+ aws_access_key_id=cast(str, aws_access_key_id),+ aws_secret_access_key=cast(str, aws_secret_access_key),+ aws_session_token=cast(str, aws_session_token),+ )+ return credentials+ elif self._is_auth_with_access_key_and_secret_key(+ aws_access_key_id,+ aws_secret_access_key,+ aws_region_name,+ ):+ return self._get_or_set_cached_credentials(+ args,+ lambda: self._auth_with_access_key_and_secret_key(+ aws_access_key_id=cast(str, aws_access_key_id),+ aws_secret_access_key=cast(str, aws_secret_access_key),+ aws_region_name=cast(str, aws_region_name),+ ),)else:- credentials, _cache_ttl = self._auth_with_env_vars()-- self.iam_cache.set_cache(cache_key, credentials, ttl=_cache_ttl)- return credentials+ return self._get_or_set_cached_credentials(args, self._auth_with_env_vars)def _get_aws_region_from_model_arn(self, model: Optional[str]) -> Optional[str]:try:diff --git a/litellm/llms/bedrock/passthrough/transformation.py b/litellm/llms/bedrock/passthrough/transformation.pyindex 274b0282acc..846af65c0f9 100644--- a/litellm/llms/bedrock/passthrough/transformation.py+++ b/litellm/llms/bedrock/passthrough/transformation.py@@ -10,14 +10,12 @@ from ..base_aws_llm import BaseAWSLLMfrom ..common_utils import BedrockEventStreamDecoderBase, BedrockModelInfoif TYPE_CHECKING:+ from httpx import URL+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.types.utils import CostResponseTypes-if TYPE_CHECKING:- from httpx import URL--class BedrockPassthroughConfig(BaseAWSLLM, BedrockModelInfo, BedrockEventStreamDecoderBase, BasePassthroughConfig):diff --git a/tests/test_litellm/llms/bedrock/test_base_aws_llm.py b/tests/test_litellm/llms/bedrock/test_base_aws_llm.pyindex 55f810380b4..a4969e5dacc 100644--- a/tests/test_litellm/llms/bedrock/test_base_aws_llm.py+++ b/tests/test_litellm/llms/bedrock/test_base_aws_llm.py@@ -18,7 +18,6 @@ from botocore.awsrequest import AWSPreparedRequest, AWSRequestfrom botocore.credentials import Credentialsimport litellm-from litellm.caching.caching import DualCachefrom litellm.llms.bedrock.base_aws_llm import (AwsAuthError,BaseAWSLLM,@@ -32,6 +31,155 @@ BASE_AWS_LLM_PATH = os.path.join()[email protected](autouse=True)+def flush_shared_bedrock_iam_cache():+ """Process-wide IAM cache must not leak static/env credential entries across tests."""+ BaseAWSLLM._shared_iam_cache.flush_cache()+ yield+++def test_base_aws_llm_instances_share_process_wide_iam_cache():+ """Regression LIT-2662: new instances must reuse iam_cache (Bedrock passthrough is per-request)."""+ first = BaseAWSLLM()+ second = BaseAWSLLM()+ assert first.iam_cache is second.iam_cache+ assert first.iam_cache is BaseAWSLLM._shared_iam_cache+++def test_static_access_key_credentials_use_iam_cache_across_calls():+ """Static access-key path hits shared iam_cache; second identical call does not refetch."""+ base = BaseAWSLLM()+ fake_creds = MagicMock()++ with patch.object(+ base,+ "_auth_with_access_key_and_secret_key",+ return_value=(fake_creds, 3600),+ ) as mock_static_auth:+ base.get_credentials(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ aws_region_name="us-east-1",+ )+ base.get_credentials(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret",+ aws_region_name="us-east-1",+ )+ mock_static_auth.assert_called_once()+++def _os_environ_without_aws_keys() -> Dict[str, str]:+ """Strip AWS_* so get_credentials hits the ambient-env branch when no explicit keys are passed."""+ return {k: v for k, v in os.environ.items() if not k.startswith("AWS_")}+++def test_ambient_env_credentials_use_iam_cache_across_instances():+ """Else-branch env path uses shared iam_cache; second call on another instance does not refetch."""+ base_a = BaseAWSLLM()+ base_b = BaseAWSLLM()+ fake_creds = MagicMock()+ with patch.dict(os.environ, _os_environ_without_aws_keys(), clear=True):+ with patch.object(+ BaseAWSLLM,+ "_auth_with_env_vars",+ return_value=(fake_creds, None),+ ) as mock_env:+ base_a.get_credentials()+ base_b.get_credentials()+ mock_env.assert_called_once()+++def test_static_access_key_path_boto3_session_constructed_once_when_cached():+ """With real _auth_with_access_key_and_secret_key, boto3.Session is only built once per cache key."""+ base_a = BaseAWSLLM()+ base_b = BaseAWSLLM()+ real_creds = Credentials("AKIAEXAMPLE", "secret-key-val", None)+ mock_session_instance = MagicMock()+ mock_session_instance.get_credentials.return_value = real_creds+ with patch("boto3.Session", return_value=mock_session_instance) as mock_session_cls:+ base_a.get_credentials(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret-key-val",+ aws_region_name="us-east-1",+ )+ base_b.get_credentials(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key="secret-key-val",+ aws_region_name="us-east-1",+ )+ mock_session_cls.assert_called_once()+++def test_ambient_env_path_boto3_session_constructed_once_when_cached():+ """Else branch: boto3.Session() inside _auth_with_env_vars runs once for two cache hits."""+ base_a = BaseAWSLLM()+ base_b = BaseAWSLLM()+ real_creds = Credentials("AKIAENV", "secret-env", None)+ mock_session_instance = MagicMock()+ mock_session_instance.get_credentials.return_value = real_creds+ with patch.dict(os.environ, _os_environ_without_aws_keys(), clear=True):+ with patch(+ "boto3.Session", return_value=mock_session_instance+ ) as mock_session_cls:+ base_a.get_credentials()+ base_b.get_credentials()+ mock_session_cls.assert_called_once()+++def test_explicit_session_token_tuple_not_cached_in_iam_cache():+ """Temporary key+secret+session paths must not use process-wide iam_cache between calls."""+ base = BaseAWSLLM()+ with patch.object(+ base,+ "_auth_with_aws_session_token",+ return_value=(+ Credentials("ak", "sk", "token"),+ None,+ ),+ ) as mock_sess:+ base.get_credentials(+ aws_access_key_id="AKIA",+ aws_secret_access_key="sec",+ aws_session_token="tok",+ )+ base.get_credentials(+ aws_access_key_id="AKIA",+ aws_secret_access_key="sec",+ aws_session_token="tok",+ )+ assert mock_sess.call_count == 2+++def test_aws_profile_path_not_cached_in_iam_cache():+ base = BaseAWSLLM()+ with patch.object(+ base,+ "_auth_with_aws_profile",+ return_value=(Credentials("prof-ak", "prof-sk", None), None),+ ) as mock_profile:+ base.get_credentials(aws_profile_name="my-profile")+ base.get_credentials(aws_profile_name="my-profile")+ assert mock_profile.call_count == 2+++def test_web_identity_path_not_cached_in_iam_cache():+ base = BaseAWSLLM()+ with patch.object(+ base,+ "_auth_with_web_identity_token",+ return_value=(Credentials("wi-ak", "wi-sk", "wi-tok"), None),+ ) as mock_wi:+ kwargs = dict(+ aws_web_identity_token="jwt-token",+ aws_role_name="arn:aws:iam::123456789012:role/WebIdentity",+ aws_session_name="web-id-session",+ )+ base.get_credentials(**kwargs)+ base.get_credentials(**kwargs)+ assert mock_wi.call_count == 2++def test_boto3_init_tracer_wrapping():"""Test that all boto3 initializations are wrapped in tracer.trace or @tracer.wrap@@ -48,6 +196,8 @@ def test_boto3_init_tracer_wrapping():lines = content.split("\n")# Check each boto3 initialization is wrapped in tracer.tracefor line_number, line in enumerate(lines, 1):+ if line.lstrip().startswith("#"):+ continuefor pattern in boto3_init_patterns:if pattern in line:# Look back up to 5 lines for decorator or trace block@@ -544,7 +694,6 @@ def test_role_assumption_without_session_name():# Mock the STS response with proper expiration handlingmock_expiry = MagicMock()mock_expiry.tzinfo = timezone.utc- current_time = datetime.now(timezone.utc)# Create a timedelta object that returns 3600 when total_seconds() is calledtime_diff = MagicMock()time_diff.total_seconds.return_value = 3600@@ -597,24 +746,61 @@ def test_role_assumption_without_session_name():call_args = mock_sts_client.assume_role.call_argsassert call_args[1]["RoleSessionName"] == "my-custom-session"- # Test case 3: Verify caching works with auto-generated session names- # Clear the cache first- base_aws_llm.iam_cache = DualCache()-+ # Test case 3: AssumeRole is not stored in iam_cache; identical calls each invoke STS.+ BaseAWSLLM._shared_iam_cache.flush_cache()mock_sts_client.reset_mock()with patch("boto3.client", return_value=mock_sts_client):- # First callcredentials1 = base_aws_llm.get_credentials(aws_role_name="arn:aws:iam::2222222222222:role/LitellmEvalBedrockRole")- # Second call with same role should use cache (not call assume_role again)credentials2 = base_aws_llm.get_credentials(aws_role_name="arn:aws:iam::2222222222222:role/LitellmEvalBedrockRole")- # Should only be called once due to caching- assert mock_sts_client.assume_role.call_count == 1+ assert mock_sts_client.assume_role.call_count == 2+ assert credentials1.access_key == credentials2.access_key+++def test_assume_role_path_does_not_use_process_iam_cache():+ """AssumeRole credentials are not cached; each get_credentials repeats STS AssumeRole."""+ base_aws_llm = BaseAWSLLM()++ mock_sts_client = MagicMock()+ mock_expiry = MagicMock()+ mock_expiry.tzinfo = timezone.utc+ time_diff = MagicMock()+ time_diff.total_seconds.return_value = 3600+ mock_expiry.__sub__ = MagicMock(return_value=time_diff)++ mock_sts_client.assume_role.return_value = {+ "Credentials": {+ "AccessKeyId": "assumed-access-key",+ "SecretAccessKey": "assumed-secret-key",+ "SessionToken": "assumed-session-token",+ "Expiration": mock_expiry,+ }+ }+ mock_sts_client.get_caller_identity.return_value = {+ "Arn": "arn:aws:sts::111111111111:assumed-role/SomeOtherRole/session-name",+ }++ role_arn = "arn:aws:iam::2222222222222:role/LitellmEvalBedrockRole"+ env_without_irsa = {+ k: v+ for k, v in os.environ.items()+ if k not in ("AWS_ROLE_ARN", "AWS_WEB_IDENTITY_TOKEN_FILE")+ }++ with patch.dict(os.environ, env_without_irsa, clear=True):+ with patch("boto3.client", return_value=mock_sts_client):+ base_aws_llm.get_credentials(aws_role_name=role_arn)+ mock_sts_client.get_caller_identity.reset_mock()++ base_aws_llm.get_credentials(aws_role_name=role_arn)++ mock_sts_client.get_caller_identity.assert_called()+ assert mock_sts_client.assume_role.call_count == 2def test_cache_keys_are_different_for_different_roles():@@ -828,6 +1014,11 @@ def test_partial_credentials_still_use_ambient():Test that if only one credential is provided, we still use ambient credentials.This handles edge cases where configuration might be incomplete."""+ env_without_aws_region = {+ k: v+ for k, v in os.environ.items()+ if k not in ("AWS_REGION", "AWS_DEFAULT_REGION")+ }base_aws_llm = BaseAWSLLM()# Mock the boto3 STS client@@ -850,37 +1041,43 @@ def test_partial_credentials_still_use_ambient():}mock_sts_client.assume_role.return_value = mock_sts_response- with patch("boto3.client", return_value=mock_sts_client) as mock_boto3_client:+ with patch.dict(os.environ, env_without_aws_region, clear=True):+ with patch("boto3.client", return_value=mock_sts_client) as mock_boto3_client:- # Call with only access key (missing secret key)- credentials, ttl = base_aws_llm._auth_with_aws_role(- aws_access_key_id="AKIAEXAMPLE",- aws_secret_access_key=None,- aws_session_token=None,- aws_role_name="arn:aws:iam::2222222222222:role/LitellmEvalBedrockRole",- aws_session_name="test-session",- )+ # Call with only access key (missing secret key)+ credentials, ttl = base_aws_llm._auth_with_aws_role(+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key=None,+ aws_session_token=None,+ aws_role_name="arn:aws:iam::2222222222222:role/LitellmEvalBedrockRole",+ aws_session_name="test-session",+ )- # Should still pass partial credentials to boto3.client- mock_boto3_client.assert_called_once_with(- "sts",- aws_access_key_id="AKIAEXAMPLE",- aws_secret_access_key=None,- aws_session_token=None,- verify=True,- )+ # Should still pass partial credentials to boto3.client+ mock_boto3_client.assert_called_once_with(+ "sts",+ aws_access_key_id="AKIAEXAMPLE",+ aws_secret_access_key=None,+ aws_session_token=None,+ verify=True,+ )- # Should still call assume_role- mock_sts_client.assume_role.assert_called_once_with(- RoleArn="arn:aws:iam::2222222222222:role/LitellmEvalBedrockRole",- RoleSessionName="test-session",- )+ # Should still call assume_role+ mock_sts_client.assume_role.assert_called_once_with(+ RoleArn="arn:aws:iam::2222222222222:role/LitellmEvalBedrockRole",+ RoleSessionName="test-session",+ )def test_cross_account_role_assumption():"""Test assuming a role in a different AWS account (common in multi-account setups)."""+ env_without_aws_region = {+ k: v+ for k, v in os.environ.items()+ if k not in ("AWS_REGION", "AWS_DEFAULT_REGION")+ }base_aws_llm = BaseAWSLLM()# Mock the boto3 STS client@@ -903,31 +1100,32 @@ def test_cross_account_role_assumption():}mock_sts_client.assume_role.return_value = mock_sts_response- with patch("boto3.client", return_value=mock_sts_client) as mock_boto3_client:+ with patch.dict(os.environ, env_without_aws_region, clear=True):+ with patch("boto3.client", return_value=mock_sts_client) as mock_boto3_client:- # Assume role in different account (EKS/IRSA scenario)- credentials, ttl = base_aws_llm._auth_with_aws_role(- aws_access_key_id=None,- aws_secret_access_key=None,- aws_session_token=None,- aws_role_name="arn:aws:iam::999999999999:role/CrossAccountRole",- aws_session_name="cross-account-session",- )+ # Assume role in different account (EKS/IRSA scenario)+ credentials, ttl = base_aws_llm._auth_with_aws_role(+ aws_access_key_id=None,+ aws_secret_access_key=None,+ aws_session_token=None,+ aws_role_name="arn:aws:iam::999999999999:role/CrossAccountRole",+ aws_session_name="cross-account-session",+ )- # Should use ambient credentials- mock_boto3_client.assert_called_once_with("sts", verify=True)+ # Should use ambient credentials+ mock_boto3_client.assert_called_once_with("sts", verify=True)- # Should call assume_role with cross-account role- mock_sts_client.assume_role.assert_called_once_with(- RoleArn="arn:aws:iam::999999999999:role/CrossAccountRole",- RoleSessionName="cross-account-session",- )+ # Should call assume_role with cross-account role+ mock_sts_client.assume_role.assert_called_once_with(+ RoleArn="arn:aws:iam::999999999999:role/CrossAccountRole",+ RoleSessionName="cross-account-session",+ )- # Verify cross-account credentials are returned- assert credentials.access_key == "cross-account-access-key"- assert credentials.secret_key == "cross-account-secret-key"- assert credentials.token == "cross-account-session-token"- assert ttl is not None+ # Verify cross-account credentials are returned+ assert credentials.access_key == "cross-account-access-key"+ assert credentials.secret_key == "cross-account-secret-key"+ assert credentials.token == "cross-account-session-token"+ assert ttl is not Nonedef test_role_assumption_with_custom_session_name():@@ -1618,7 +1816,7 @@ def test_get_credentials_ecs_same_role_skips_assume_role():base_aws_llm,"_is_already_running_as_role",return_value=True,- ):+ ) as mock_already_running:with patch.object(base_aws_llm,"_auth_with_env_vars",@@ -1632,13 +1830,71 @@ def test_get_credentials_ecs_same_role_skips_assume_role():aws_role_name="arn:aws:iam::123456789012:role/MyEcsTaskRole",aws_region_name="us-east-1",)+ base_aws_llm.get_credentials(+ aws_role_name="arn:aws:iam::123456789012:role/MyEcsTaskRole",+ aws_region_name="us-east-1",+ )- # Should use env vars, NOT role assumption+ # Each get_credentials must check identity first; second call still checks before+ # taking the iam_cache hit (no pre-peek that bypasses _is_already_running_as_role).+ assert mock_already_running.call_count == 2+ # Cached env resolution: second call hits iam_cache, not _auth_with_env_vars again.mock_env_auth.assert_called_once()mock_role_auth.assert_not_called()assert credentials.access_key == "ecs-access-key"+def test_get_credentials_role_second_call_not_same_role_uses_assume_not_env_cache():+ """+ First request: already target role -> env path fills iam_cache.+ Second request (e.g. identity changed): not same role -> AssumeRole path; must not reuse+ cached env resolution from the first call.+ """+ base_aws_llm = BaseAWSLLM()++ env_creds = MagicMock()+ env_creds.access_key = "ambient-key"+ env_creds.secret_key = "ambient-secret"+ env_creds.token = "ambient-token"++ assumed_creds = MagicMock()+ assumed_creds.access_key = "assumed-key"+ assumed_creds.secret_key = "assumed-secret"+ assumed_creds.token = "assumed-token"++ role_arn = "arn:aws:iam::123456789012:role/TargetRole"++ with patch.object(+ base_aws_llm,+ "_is_already_running_as_role",+ side_effect=[True, False],+ ) as mock_already:+ with patch.object(+ base_aws_llm,+ "_auth_with_env_vars",+ return_value=(env_creds, None),+ ) as mock_env_auth:+ with patch.object(+ base_aws_llm,+ "_auth_with_aws_role",+ return_value=(assumed_creds, 3600),+ ) as mock_role_auth:+ first = base_aws_llm.get_credentials(+ aws_role_name=role_arn,+ aws_region_name="us-east-1",+ )+ second = base_aws_llm.get_credentials(+ aws_role_name=role_arn,+ aws_region_name="us-east-1",+ )++ assert mock_already.call_count == 2+ mock_env_auth.assert_called_once()+ mock_role_auth.assert_called_once()+ assert first.access_key == "ambient-key"+ assert second.access_key == "assumed-key"++def test_parse_arn_account_and_role_name():"""Test the ARN parser helper for various ARN formats."""parse = BaseAWSLLM._parse_arn_account_and_role_name