From 8317e628a83e0f55d9ff12c8b44704e146d96352 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 22 Nov 2026 03:22:21 -0400 Subject: [PATCH 1/6] fix(vectorize): support session tokens and default AWS credential chain in BedrockVectorizer BedrockVectorizer required static aws_access_key_id/aws_secret_access_key and never forwarded a session token, so temporary (STS/SSO) and IAM-role credentials failed. Forward aws_session_token (api_config or AWS_SESSION_TOKEN) and fall back to boto3's default credential chain when no static keys are given. --- redisvl/utils/vectorize/bedrock.py | 39 ++++++++++------- tests/unit/test_bedrock_vectorizer.py | 60 +++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 14 deletions(-) create mode 100644 tests/unit/test_bedrock_vectorizer.py diff --git a/redisvl/utils/vectorize/bedrock.py b/redisvl/utils/vectorize/bedrock.py index 3a590b3ec..46a6033be 100644 --- a/redisvl/utils/vectorize/bedrock.py +++ b/redisvl/utils/vectorize/bedrock.py @@ -31,6 +31,7 @@ class BedrockVectorizer(BaseVectorizer): directly in the `api_config` dictionary or through environment variables: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY + - AWS_SESSION_TOKEN (optional, for temporary credentials) - AWS_REGION (defaults to us-east-1) The vectorizer supports synchronous operations with batch processing and @@ -104,8 +105,9 @@ def __init__( Args: model (str): The Bedrock model ID to use. Defaults to amazon.titan-embed-text-v2:0 api_config (Optional[Dict[str, str]]): AWS credentials and config. - Can include: aws_access_key_id, aws_secret_access_key, aws_region - If not provided, will use environment variables. + Can include: aws_access_key_id, aws_secret_access_key, + aws_session_token, aws_region. If not provided, will use + environment variables, then boto3's default credential chain. dtype (str): the default datatype to use when embedding text as byte arrays. Used when setting `as_buffer=True` in calls to embed() and embed_many(). Defaults to 'float32'. @@ -113,7 +115,7 @@ def __init__( better performance with repeated texts. Defaults to None. Raises: - ValueError: If credentials are not provided in config or environment. + ValueError: If only one of the access key / secret key is provided. ImportError: If boto3 is not installed. ValueError: If an invalid dtype is provided. """ @@ -143,7 +145,7 @@ def _initialize_client(self, api_config: dict[str, Any] | None, **kwargs): Raises: ImportError: If boto3 is not installed - ValueError: If AWS credentials are not provided + ValueError: If only one of the access key / secret key is provided """ try: import boto3 # type: ignore @@ -162,22 +164,31 @@ def _initialize_client(self, api_config: dict[str, Any] | None, **kwargs): aws_secret_access_key = api_config.get( "aws_secret_access_key", os.getenv("AWS_SECRET_ACCESS_KEY") ) + aws_session_token = api_config.get( + "aws_session_token", os.getenv("AWS_SESSION_TOKEN") + ) aws_region = api_config.get("aws_region", os.getenv("AWS_REGION", "us-east-1")) - if not aws_access_key_id or not aws_secret_access_key: + # Static keys must be supplied as a pair. When neither is given, fall back + # to boto3's default credential chain (SSO, IAM roles, shared profiles...). + if bool(aws_access_key_id) != bool(aws_secret_access_key): raise ValueError( - "AWS credentials required. Provide via api_config or environment variables " - "AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY" + "Both aws_access_key_id and aws_secret_access_key must be provided " + "together (via api_config or the AWS_ACCESS_KEY_ID and " + "AWS_SECRET_ACCESS_KEY environment variables), or neither to use " + "the default AWS credential chain." ) + client_kwargs: dict[str, Any] = {"region_name": aws_region} + if aws_access_key_id and aws_secret_access_key: + client_kwargs["aws_access_key_id"] = aws_access_key_id + client_kwargs["aws_secret_access_key"] = aws_secret_access_key + if aws_session_token: + client_kwargs["aws_session_token"] = aws_session_token + client_kwargs.update(kwargs) + # Store client as a regular attribute instead of PrivateAttr - self._client = boto3.client( - "bedrock-runtime", - aws_access_key_id=aws_access_key_id, - aws_secret_access_key=aws_secret_access_key, - region_name=aws_region, - **kwargs, - ) + self._client = boto3.client("bedrock-runtime", **client_kwargs) def _set_model_dims(self) -> int: """ diff --git a/tests/unit/test_bedrock_vectorizer.py b/tests/unit/test_bedrock_vectorizer.py new file mode 100644 index 000000000..a9cf15f65 --- /dev/null +++ b/tests/unit/test_bedrock_vectorizer.py @@ -0,0 +1,60 @@ +import sys +from unittest.mock import MagicMock, patch + +import pytest + +from redisvl.utils.vectorize.bedrock import BedrockVectorizer + + +@pytest.fixture +def boto3_mock(monkeypatch): + for var in ( + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + "AWS_SESSION_TOKEN", + "AWS_REGION", + ): + monkeypatch.delenv(var, raising=False) + boto3 = MagicMock() + with patch.dict(sys.modules, {"boto3": boto3}): + yield boto3 + + +def _make(**kwargs): + with patch.object(BedrockVectorizer, "_set_model_dims", return_value=3): + return BedrockVectorizer(**kwargs) + + +def test_session_token_is_forwarded(boto3_mock): + _make( + api_config={ + "aws_access_key_id": "AKIA", + "aws_secret_access_key": "secret", + "aws_session_token": "token", + } + ) + kwargs = boto3_mock.client.call_args.kwargs + assert kwargs["aws_session_token"] == "token" + assert kwargs["aws_access_key_id"] == "AKIA" + + +def test_session_token_from_env(boto3_mock, monkeypatch): + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIA") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "secret") + monkeypatch.setenv("AWS_SESSION_TOKEN", "token") + _make() + assert boto3_mock.client.call_args.kwargs["aws_session_token"] == "token" + + +def test_default_credential_chain_when_no_keys(boto3_mock): + _make() + kwargs = boto3_mock.client.call_args.kwargs + assert "aws_access_key_id" not in kwargs + assert "aws_secret_access_key" not in kwargs + assert "aws_session_token" not in kwargs + assert kwargs["region_name"] == "us-east-1" + + +def test_partial_static_keys_raise(boto3_mock): + with pytest.raises(ValueError, match="together"): + _make(api_config={"aws_access_key_id": "AKIA"}) From 62ab031412a718b740c2ac41fdfc65d8f03ce74b Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 22 Nov 2026 18:58:48 -0400 Subject: [PATCH 2/6] fix(vectorize): do not mix AWS_SESSION_TOKEN from env with explicit api_config keys --- redisvl/utils/vectorize/bedrock.py | 10 ++++++++-- tests/unit/test_bedrock_vectorizer.py | 13 +++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/redisvl/utils/vectorize/bedrock.py b/redisvl/utils/vectorize/bedrock.py index 46a6033be..2a73af1c0 100644 --- a/redisvl/utils/vectorize/bedrock.py +++ b/redisvl/utils/vectorize/bedrock.py @@ -164,9 +164,15 @@ def _initialize_client(self, api_config: dict[str, Any] | None, **kwargs): aws_secret_access_key = api_config.get( "aws_secret_access_key", os.getenv("AWS_SECRET_ACCESS_KEY") ) - aws_session_token = api_config.get( - "aws_session_token", os.getenv("AWS_SESSION_TOKEN") + # An environment session token only pairs with environment keys; explicit + # keys from api_config must not inherit a leftover AWS_SESSION_TOKEN. + keys_from_api_config = bool( + api_config.get("aws_access_key_id") + or api_config.get("aws_secret_access_key") ) + aws_session_token = api_config.get("aws_session_token") + if aws_session_token is None and not keys_from_api_config: + aws_session_token = os.getenv("AWS_SESSION_TOKEN") aws_region = api_config.get("aws_region", os.getenv("AWS_REGION", "us-east-1")) # Static keys must be supplied as a pair. When neither is given, fall back diff --git a/tests/unit/test_bedrock_vectorizer.py b/tests/unit/test_bedrock_vectorizer.py index a9cf15f65..05df4a1eb 100644 --- a/tests/unit/test_bedrock_vectorizer.py +++ b/tests/unit/test_bedrock_vectorizer.py @@ -58,3 +58,16 @@ def test_default_credential_chain_when_no_keys(boto3_mock): def test_partial_static_keys_raise(boto3_mock): with pytest.raises(ValueError, match="together"): _make(api_config={"aws_access_key_id": "AKIA"}) + + +def test_env_session_token_not_mixed_with_explicit_keys(boto3_mock, monkeypatch): + monkeypatch.setenv("AWS_SESSION_TOKEN", "leftover") + _make( + api_config={ + "aws_access_key_id": "AKIA", + "aws_secret_access_key": "secret", + } + ) + kwargs = boto3_mock.client.call_args.kwargs + assert kwargs["aws_access_key_id"] == "AKIA" + assert "aws_session_token" not in kwargs From 70fffae4c5db37bf63714b5f4e829c6d542e7bca Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 23 Nov 2026 17:58:35 -0400 Subject: [PATCH 3/6] fix(vectorize): let boto3 resolve env credentials and surface missing-credentials errors - Do not copy AWS_* environment credentials into client kwargs; boto3 resolves them itself and keeps refresh support. - Reject an explicit aws_session_token without access key and secret. - Reject conflicting credential values between api_config and kwargs; keep forwarding unrelated boto3 options. - Propagate NoCredentialsError without retries or ValueError wrapping. --- redisvl/utils/vectorize/bedrock.py | 89 +++++++++++++++++---------- tests/unit/test_bedrock_vectorizer.py | 62 ++++++++++++++++++- 2 files changed, 118 insertions(+), 33 deletions(-) diff --git a/redisvl/utils/vectorize/bedrock.py b/redisvl/utils/vectorize/bedrock.py index 2a73af1c0..835cd1592 100644 --- a/redisvl/utils/vectorize/bedrock.py +++ b/redisvl/utils/vectorize/bedrock.py @@ -7,7 +7,7 @@ from pydantic import ConfigDict from tenacity import retry, stop_after_attempt, wait_random_exponential -from tenacity.retry import retry_if_not_exception_type +from tenacity.retry import retry_if_exception if TYPE_CHECKING: from redisvl.extensions.cache.embeddings.embeddings import EmbeddingsCache @@ -22,6 +22,17 @@ _PILLOW_INSTALLED = True +def _is_retryable(exc: BaseException) -> bool: + """Do not retry programming errors or missing credentials.""" + if isinstance(exc, TypeError): + return False + try: + from botocore.exceptions import NoCredentialsError + except ImportError: + return True + return not isinstance(exc, NoCredentialsError) + + class BedrockVectorizer(BaseVectorizer): """The BedrockVectorizer class utilizes Amazon Bedrock's API to generate embeddings for text or image data. @@ -158,39 +169,47 @@ def _initialize_client(self, api_config: dict[str, Any] | None, **kwargs): if api_config is None: api_config = {} - aws_access_key_id = api_config.get( - "aws_access_key_id", os.getenv("AWS_ACCESS_KEY_ID") - ) - aws_secret_access_key = api_config.get( - "aws_secret_access_key", os.getenv("AWS_SECRET_ACCESS_KEY") - ) - # An environment session token only pairs with environment keys; explicit - # keys from api_config must not inherit a leftover AWS_SESSION_TOKEN. - keys_from_api_config = bool( - api_config.get("aws_access_key_id") - or api_config.get("aws_secret_access_key") - ) - aws_session_token = api_config.get("aws_session_token") - if aws_session_token is None and not keys_from_api_config: - aws_session_token = os.getenv("AWS_SESSION_TOKEN") aws_region = api_config.get("aws_region", os.getenv("AWS_REGION", "us-east-1")) - # Static keys must be supplied as a pair. When neither is given, fall back - # to boto3's default credential chain (SSO, IAM roles, shared profiles...). - if bool(aws_access_key_id) != bool(aws_secret_access_key): + # Explicit credentials come from api_config and/or constructor kwargs. + # Environment credentials are deliberately not copied here: when the + # caller supplies none, boto3 resolves them itself (including refresh). + credential_names = ( + "aws_access_key_id", + "aws_secret_access_key", + "aws_session_token", + ) + explicit: dict[str, Any] = {} + for name in credential_names: + from_config = api_config.get(name) + from_kwargs = kwargs.pop(name, None) + if from_config and from_kwargs and from_config != from_kwargs: + raise ValueError( + f"Conflicting values for {name} in api_config and the " + "constructor arguments." + ) + value = from_config or from_kwargs + if value: + explicit[name] = value + + # Static keys must be supplied as a pair, and a session token only + # makes sense together with them. When no explicit credentials are + # given, fall back to boto3's default chain (env, SSO, IAM roles...). + has_key = "aws_access_key_id" in explicit + has_secret = "aws_secret_access_key" in explicit + if has_key != has_secret: raise ValueError( "Both aws_access_key_id and aws_secret_access_key must be provided " - "together (via api_config or the AWS_ACCESS_KEY_ID and " - "AWS_SECRET_ACCESS_KEY environment variables), or neither to use " - "the default AWS credential chain." + "together, or neither to use the default AWS credential chain." + ) + if "aws_session_token" in explicit and not has_key: + raise ValueError( + "aws_session_token requires aws_access_key_id and " + "aws_secret_access_key to be provided as well." ) client_kwargs: dict[str, Any] = {"region_name": aws_region} - if aws_access_key_id and aws_secret_access_key: - client_kwargs["aws_access_key_id"] = aws_access_key_id - client_kwargs["aws_secret_access_key"] = aws_secret_access_key - if aws_session_token: - client_kwargs["aws_session_token"] = aws_session_token + client_kwargs.update(explicit) client_kwargs.update(kwargs) # Store client as a regular attribute instead of PrivateAttr @@ -206,12 +225,16 @@ def _set_model_dims(self) -> int: Raises: ValueError: If embedding dimensions cannot be determined """ + from botocore.exceptions import NoCredentialsError + try: # Call the protected _embed method to avoid caching this test embedding embedding = self._embed("dimension check") return len(embedding) except (KeyError, IndexError) as ke: raise ValueError(f"Unexpected response from the Bedrock API: {str(ke)}") + except NoCredentialsError: + raise except Exception as e: # pylint: disable=broad-except # fall back (TODO get more specific) raise ValueError(f"Error setting embedding model dimensions: {str(e)}") @@ -219,7 +242,7 @@ def _set_model_dims(self) -> int: @retry( wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6), - retry=retry_if_not_exception_type(TypeError), + retry=retry_if_exception(_is_retryable), ) def _embed(self, content: Any, **kwargs) -> list[float]: """ @@ -237,7 +260,7 @@ def _embed(self, content: Any, **kwargs) -> list[float]: ValueError: If attempting to embed an image with a text model ValueError: If embedding fails """ - from botocore.exceptions import ValidationError + from botocore.exceptions import NoCredentialsError, ValidationError body = self._serialize_request_body(content) @@ -251,13 +274,15 @@ def _embed(self, content: Any, **kwargs) -> list[float]: if "Malformed input request" in str(e) and "inputImage" in body: raise ValueError("Attempted to embed image with text model.") from e raise ValueError(f"Embedding text failed: {e}") + except NoCredentialsError: + raise except Exception as e: raise ValueError(f"Embedding text failed: {e}") @retry( wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6), - retry=retry_if_not_exception_type(TypeError), + retry=retry_if_exception(_is_retryable), ) def _embed_many( self, contents: list[Any], batch_size: int = 10, **kwargs @@ -279,7 +304,7 @@ def _embed_many( ValueError: If attempting to embed an image with a text model ValueError: If embedding fails """ - from botocore.exceptions import ValidationError + from botocore.exceptions import NoCredentialsError, ValidationError if not isinstance(contents, list): raise TypeError("`contents` must be a list") @@ -313,6 +338,8 @@ def _embed_many( embeddings.extend(batch_embeddings) return embeddings + except NoCredentialsError: + raise except Exception as e: raise ValueError(f"Embedding texts failed: {e}") diff --git a/tests/unit/test_bedrock_vectorizer.py b/tests/unit/test_bedrock_vectorizer.py index 05df4a1eb..65ea68f12 100644 --- a/tests/unit/test_bedrock_vectorizer.py +++ b/tests/unit/test_bedrock_vectorizer.py @@ -38,12 +38,17 @@ def test_session_token_is_forwarded(boto3_mock): assert kwargs["aws_access_key_id"] == "AKIA" -def test_session_token_from_env(boto3_mock, monkeypatch): +def test_env_credentials_left_to_boto3(boto3_mock, monkeypatch): + # Environment credentials (incl. the session token) are resolved by boto3 + # itself so botocore keeps its refresh support; we must not copy them. monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIA") monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "secret") monkeypatch.setenv("AWS_SESSION_TOKEN", "token") _make() - assert boto3_mock.client.call_args.kwargs["aws_session_token"] == "token" + kwargs = boto3_mock.client.call_args.kwargs + assert "aws_access_key_id" not in kwargs + assert "aws_secret_access_key" not in kwargs + assert "aws_session_token" not in kwargs def test_default_credential_chain_when_no_keys(boto3_mock): @@ -71,3 +76,56 @@ def test_env_session_token_not_mixed_with_explicit_keys(boto3_mock, monkeypatch) kwargs = boto3_mock.client.call_args.kwargs assert kwargs["aws_access_key_id"] == "AKIA" assert "aws_session_token" not in kwargs + + +def test_session_token_without_keys_raises(boto3_mock): + with pytest.raises(ValueError, match="aws_session_token requires"): + _make(api_config={"aws_session_token": "token"}) + boto3_mock.client.assert_not_called() + + +def test_conflicting_credentials_raise(boto3_mock): + with pytest.raises(ValueError, match="Conflicting"): + _make( + api_config={ + "aws_access_key_id": "AKIA", + "aws_secret_access_key": "secret", + }, + aws_access_key_id="OTHER", + ) + boto3_mock.client.assert_not_called() + + +def test_unrelated_boto3_kwargs_forwarded(boto3_mock): + _make( + api_config={ + "aws_access_key_id": "AKIA", + "aws_secret_access_key": "secret", + }, + endpoint_url="http://localhost:4566", + ) + kwargs = boto3_mock.client.call_args.kwargs + assert kwargs["endpoint_url"] == "http://localhost:4566" + assert kwargs["aws_access_key_id"] == "AKIA" + + +def test_no_credentials_error_not_retried(boto3_mock): + from botocore.exceptions import NoCredentialsError + + vec = _make() + vec._client.invoke_model.side_effect = NoCredentialsError() + with pytest.raises(NoCredentialsError): + vec._embed("hello") + assert vec._client.invoke_model.call_count == 1 + with pytest.raises(NoCredentialsError): + vec._embed_many(["hello"]) + assert vec._client.invoke_model.call_count == 2 + + +def test_missing_credentials_surface_from_constructor(boto3_mock): + from botocore.exceptions import NoCredentialsError + + boto3_mock.client.return_value.invoke_model.side_effect = NoCredentialsError() + with pytest.raises(NoCredentialsError): + BedrockVectorizer() + assert boto3_mock.client.return_value.invoke_model.call_count == 1 From f948a96fa2d37821f961a8fc675c37ec8db94868 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 25 Nov 2026 00:41:05 -0400 Subject: [PATCH 4/6] fix(vectorize): surface missing SSO login without retries Treat SSOTokenLoadError like NoCredentialsError in the constructor, embed and embed_many paths, and skip the botocore-dependent tests when the SDK is not installed. Co-Authored-By: Claude Sonnet 5.5 --- redisvl/utils/vectorize/bedrock.py | 26 +++++++++++++++++--------- tests/unit/test_bedrock_vectorizer.py | 27 +++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/redisvl/utils/vectorize/bedrock.py b/redisvl/utils/vectorize/bedrock.py index 835cd1592..f2110170b 100644 --- a/redisvl/utils/vectorize/bedrock.py +++ b/redisvl/utils/vectorize/bedrock.py @@ -23,14 +23,14 @@ def _is_retryable(exc: BaseException) -> bool: - """Do not retry programming errors or missing credentials.""" + """Do not retry programming errors, missing credentials or missing SSO login.""" if isinstance(exc, TypeError): return False try: - from botocore.exceptions import NoCredentialsError + from botocore.exceptions import NoCredentialsError, SSOTokenLoadError except ImportError: return True - return not isinstance(exc, NoCredentialsError) + return not isinstance(exc, (NoCredentialsError, SSOTokenLoadError)) class BedrockVectorizer(BaseVectorizer): @@ -225,7 +225,7 @@ def _set_model_dims(self) -> int: Raises: ValueError: If embedding dimensions cannot be determined """ - from botocore.exceptions import NoCredentialsError + from botocore.exceptions import NoCredentialsError, SSOTokenLoadError try: # Call the protected _embed method to avoid caching this test embedding @@ -233,7 +233,7 @@ def _set_model_dims(self) -> int: return len(embedding) except (KeyError, IndexError) as ke: raise ValueError(f"Unexpected response from the Bedrock API: {str(ke)}") - except NoCredentialsError: + except (NoCredentialsError, SSOTokenLoadError): raise except Exception as e: # pylint: disable=broad-except # fall back (TODO get more specific) @@ -260,7 +260,11 @@ def _embed(self, content: Any, **kwargs) -> list[float]: ValueError: If attempting to embed an image with a text model ValueError: If embedding fails """ - from botocore.exceptions import NoCredentialsError, ValidationError + from botocore.exceptions import ( + NoCredentialsError, + SSOTokenLoadError, + ValidationError, + ) body = self._serialize_request_body(content) @@ -274,7 +278,7 @@ def _embed(self, content: Any, **kwargs) -> list[float]: if "Malformed input request" in str(e) and "inputImage" in body: raise ValueError("Attempted to embed image with text model.") from e raise ValueError(f"Embedding text failed: {e}") - except NoCredentialsError: + except (NoCredentialsError, SSOTokenLoadError): raise except Exception as e: raise ValueError(f"Embedding text failed: {e}") @@ -304,7 +308,11 @@ def _embed_many( ValueError: If attempting to embed an image with a text model ValueError: If embedding fails """ - from botocore.exceptions import NoCredentialsError, ValidationError + from botocore.exceptions import ( + NoCredentialsError, + SSOTokenLoadError, + ValidationError, + ) if not isinstance(contents, list): raise TypeError("`contents` must be a list") @@ -338,7 +346,7 @@ def _embed_many( embeddings.extend(batch_embeddings) return embeddings - except NoCredentialsError: + except (NoCredentialsError, SSOTokenLoadError): raise except Exception as e: raise ValueError(f"Embedding texts failed: {e}") diff --git a/tests/unit/test_bedrock_vectorizer.py b/tests/unit/test_bedrock_vectorizer.py index 65ea68f12..7b6272266 100644 --- a/tests/unit/test_bedrock_vectorizer.py +++ b/tests/unit/test_bedrock_vectorizer.py @@ -110,7 +110,7 @@ def test_unrelated_boto3_kwargs_forwarded(boto3_mock): def test_no_credentials_error_not_retried(boto3_mock): - from botocore.exceptions import NoCredentialsError + NoCredentialsError = pytest.importorskip("botocore.exceptions").NoCredentialsError vec = _make() vec._client.invoke_model.side_effect = NoCredentialsError() @@ -123,9 +123,32 @@ def test_no_credentials_error_not_retried(boto3_mock): def test_missing_credentials_surface_from_constructor(boto3_mock): - from botocore.exceptions import NoCredentialsError + NoCredentialsError = pytest.importorskip("botocore.exceptions").NoCredentialsError boto3_mock.client.return_value.invoke_model.side_effect = NoCredentialsError() with pytest.raises(NoCredentialsError): BedrockVectorizer() assert boto3_mock.client.return_value.invoke_model.call_count == 1 + + +def test_missing_sso_login_not_retried(boto3_mock): + SSOTokenLoadError = pytest.importorskip("botocore.exceptions").SSOTokenLoadError + + vec = _make() + vec._client.invoke_model.side_effect = SSOTokenLoadError(error_msg="no token") + with pytest.raises(SSOTokenLoadError): + vec._embed("hello") + assert vec._client.invoke_model.call_count == 1 + with pytest.raises(SSOTokenLoadError): + vec._embed_many(["hello"]) + assert vec._client.invoke_model.call_count == 2 + + +def test_missing_sso_login_surfaces_from_constructor(boto3_mock): + SSOTokenLoadError = pytest.importorskip("botocore.exceptions").SSOTokenLoadError + + invoke_model = boto3_mock.client.return_value.invoke_model + invoke_model.side_effect = SSOTokenLoadError(error_msg="no token") + with pytest.raises(SSOTokenLoadError): + BedrockVectorizer() + assert invoke_model.call_count == 1 From 471bd32116cfd5662f34bae68fcaf1903283d26e Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 25 Nov 2026 00:53:34 -0400 Subject: [PATCH 5/6] fix(vectorize): do not retry or wrap partial credentials errors --- redisvl/utils/vectorize/bedrock.py | 26 +++++++++++++++------ tests/unit/test_bedrock_vectorizer.py | 33 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/redisvl/utils/vectorize/bedrock.py b/redisvl/utils/vectorize/bedrock.py index f2110170b..26816cd17 100644 --- a/redisvl/utils/vectorize/bedrock.py +++ b/redisvl/utils/vectorize/bedrock.py @@ -23,14 +23,20 @@ def _is_retryable(exc: BaseException) -> bool: - """Do not retry programming errors, missing credentials or missing SSO login.""" + """Do not retry programming errors, credential errors or missing SSO login.""" if isinstance(exc, TypeError): return False try: - from botocore.exceptions import NoCredentialsError, SSOTokenLoadError + from botocore.exceptions import ( + NoCredentialsError, + PartialCredentialsError, + SSOTokenLoadError, + ) except ImportError: return True - return not isinstance(exc, (NoCredentialsError, SSOTokenLoadError)) + return not isinstance( + exc, (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError) + ) class BedrockVectorizer(BaseVectorizer): @@ -225,7 +231,11 @@ def _set_model_dims(self) -> int: Raises: ValueError: If embedding dimensions cannot be determined """ - from botocore.exceptions import NoCredentialsError, SSOTokenLoadError + from botocore.exceptions import ( + NoCredentialsError, + PartialCredentialsError, + SSOTokenLoadError, + ) try: # Call the protected _embed method to avoid caching this test embedding @@ -233,7 +243,7 @@ def _set_model_dims(self) -> int: return len(embedding) except (KeyError, IndexError) as ke: raise ValueError(f"Unexpected response from the Bedrock API: {str(ke)}") - except (NoCredentialsError, SSOTokenLoadError): + except (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError): raise except Exception as e: # pylint: disable=broad-except # fall back (TODO get more specific) @@ -262,6 +272,7 @@ def _embed(self, content: Any, **kwargs) -> list[float]: """ from botocore.exceptions import ( NoCredentialsError, + PartialCredentialsError, SSOTokenLoadError, ValidationError, ) @@ -278,7 +289,7 @@ def _embed(self, content: Any, **kwargs) -> list[float]: if "Malformed input request" in str(e) and "inputImage" in body: raise ValueError("Attempted to embed image with text model.") from e raise ValueError(f"Embedding text failed: {e}") - except (NoCredentialsError, SSOTokenLoadError): + except (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError): raise except Exception as e: raise ValueError(f"Embedding text failed: {e}") @@ -310,6 +321,7 @@ def _embed_many( """ from botocore.exceptions import ( NoCredentialsError, + PartialCredentialsError, SSOTokenLoadError, ValidationError, ) @@ -346,7 +358,7 @@ def _embed_many( embeddings.extend(batch_embeddings) return embeddings - except (NoCredentialsError, SSOTokenLoadError): + except (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError): raise except Exception as e: raise ValueError(f"Embedding texts failed: {e}") diff --git a/tests/unit/test_bedrock_vectorizer.py b/tests/unit/test_bedrock_vectorizer.py index 7b6272266..913e5e0ee 100644 --- a/tests/unit/test_bedrock_vectorizer.py +++ b/tests/unit/test_bedrock_vectorizer.py @@ -152,3 +152,36 @@ def test_missing_sso_login_surfaces_from_constructor(boto3_mock): with pytest.raises(SSOTokenLoadError): BedrockVectorizer() assert invoke_model.call_count == 1 + + +def test_partial_credentials_on_refresh_not_retried(boto3_mock): + # botocore raises this from invoke_model when refreshing expiring env + # credentials and one of the variables has gone missing. + PartialCredentialsError = pytest.importorskip( + "botocore.exceptions" + ).PartialCredentialsError + + vec = _make() + vec._client.invoke_model.side_effect = PartialCredentialsError( + provider="env", cred_var="AWS_SECRET_ACCESS_KEY" + ) + with pytest.raises(PartialCredentialsError): + vec._embed("hello") + assert vec._client.invoke_model.call_count == 1 + with pytest.raises(PartialCredentialsError): + vec._embed_many(["hello"]) + assert vec._client.invoke_model.call_count == 2 + + +def test_partial_credentials_surface_from_constructor(boto3_mock): + PartialCredentialsError = pytest.importorskip( + "botocore.exceptions" + ).PartialCredentialsError + + invoke_model = boto3_mock.client.return_value.invoke_model + invoke_model.side_effect = PartialCredentialsError( + provider="env", cred_var="AWS_SECRET_ACCESS_KEY" + ) + with pytest.raises(PartialCredentialsError): + BedrockVectorizer() + assert invoke_model.call_count == 1 From 5a9ec15d5e472e7b394f46ade429ec641fdb1eda Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 25 Nov 2026 08:35:56 -0400 Subject: [PATCH 6/6] fix(vectorize): surface expired Bedrock SSO login errors --- redisvl/utils/vectorize/bedrock.py | 55 +++++++++++------------- tests/unit/test_bedrock_vectorizer.py | 61 +++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 30 deletions(-) diff --git a/redisvl/utils/vectorize/bedrock.py b/redisvl/utils/vectorize/bedrock.py index 26816cd17..800f25f72 100644 --- a/redisvl/utils/vectorize/bedrock.py +++ b/redisvl/utils/vectorize/bedrock.py @@ -22,21 +22,32 @@ _PILLOW_INSTALLED = True +def _credential_errors() -> tuple[type[Exception], ...]: + from botocore.exceptions import ( + NoCredentialsError, + PartialCredentialsError, + SSOTokenLoadError, + TokenRetrievalError, + UnauthorizedSSOTokenError, + ) + + return ( + NoCredentialsError, + PartialCredentialsError, + SSOTokenLoadError, + TokenRetrievalError, + UnauthorizedSSOTokenError, + ) + + def _is_retryable(exc: BaseException) -> bool: - """Do not retry programming errors, credential errors or missing SSO login.""" + """Do not retry programming errors or credential and login failures.""" if isinstance(exc, TypeError): return False try: - from botocore.exceptions import ( - NoCredentialsError, - PartialCredentialsError, - SSOTokenLoadError, - ) + return not isinstance(exc, _credential_errors()) except ImportError: return True - return not isinstance( - exc, (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError) - ) class BedrockVectorizer(BaseVectorizer): @@ -231,19 +242,13 @@ def _set_model_dims(self) -> int: Raises: ValueError: If embedding dimensions cannot be determined """ - from botocore.exceptions import ( - NoCredentialsError, - PartialCredentialsError, - SSOTokenLoadError, - ) - try: # Call the protected _embed method to avoid caching this test embedding embedding = self._embed("dimension check") return len(embedding) except (KeyError, IndexError) as ke: raise ValueError(f"Unexpected response from the Bedrock API: {str(ke)}") - except (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError): + except _credential_errors(): raise except Exception as e: # pylint: disable=broad-except # fall back (TODO get more specific) @@ -270,12 +275,7 @@ def _embed(self, content: Any, **kwargs) -> list[float]: ValueError: If attempting to embed an image with a text model ValueError: If embedding fails """ - from botocore.exceptions import ( - NoCredentialsError, - PartialCredentialsError, - SSOTokenLoadError, - ValidationError, - ) + from botocore.exceptions import ValidationError body = self._serialize_request_body(content) @@ -289,7 +289,7 @@ def _embed(self, content: Any, **kwargs) -> list[float]: if "Malformed input request" in str(e) and "inputImage" in body: raise ValueError("Attempted to embed image with text model.") from e raise ValueError(f"Embedding text failed: {e}") - except (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError): + except _credential_errors(): raise except Exception as e: raise ValueError(f"Embedding text failed: {e}") @@ -319,12 +319,7 @@ def _embed_many( ValueError: If attempting to embed an image with a text model ValueError: If embedding fails """ - from botocore.exceptions import ( - NoCredentialsError, - PartialCredentialsError, - SSOTokenLoadError, - ValidationError, - ) + from botocore.exceptions import ValidationError if not isinstance(contents, list): raise TypeError("`contents` must be a list") @@ -358,7 +353,7 @@ def _embed_many( embeddings.extend(batch_embeddings) return embeddings - except (NoCredentialsError, PartialCredentialsError, SSOTokenLoadError): + except _credential_errors(): raise except Exception as e: raise ValueError(f"Embedding texts failed: {e}") diff --git a/tests/unit/test_bedrock_vectorizer.py b/tests/unit/test_bedrock_vectorizer.py index 913e5e0ee..eaf770eaa 100644 --- a/tests/unit/test_bedrock_vectorizer.py +++ b/tests/unit/test_bedrock_vectorizer.py @@ -185,3 +185,64 @@ def test_partial_credentials_surface_from_constructor(boto3_mock): with pytest.raises(PartialCredentialsError): BedrockVectorizer() assert invoke_model.call_count == 1 + + +@pytest.mark.parametrize( + ("session_profile", "error_name"), + [(True, "TokenRetrievalError"), (False, "UnauthorizedSSOTokenError")], + ids=["sso-session", "legacy-sso"], +) +def test_expired_sso_login_surfaces_from_constructor( + tmp_path, monkeypatch, session_profile, error_name +): + boto3 = pytest.importorskip("boto3") + exceptions = pytest.importorskip("botocore.exceptions") + from botocore.credentials import SSOProvider + from botocore.stub import Stubber + from botocore.tokens import SSOTokenProvider + from botocore.utils import JSONFileCache, SSOTokenLoader + from tenacity import wait_none + + start_url = "https://example.awsapps.com/start" + sso_config = f"sso_start_url = {start_url}\nsso_region = us-east-1\n" + profile = ( + "[profile expired]\n" + "sso_account_id = 123456789012\n" + "sso_role_name = TestRole\n" + ) + if session_profile: + profile += f"sso_session = expired\n\n[sso-session expired]\n{sso_config}" + else: + profile += sso_config + + config_file = tmp_path / "config" + config_file.write_text(profile) + monkeypatch.setenv("AWS_CONFIG_FILE", str(config_file)) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(tmp_path / "credentials")) + monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") + for provider in (SSOProvider, SSOTokenProvider): + monkeypatch.setattr(provider, "_SSO_TOKEN_CACHE_DIR", str(tmp_path)) + SSOTokenLoader(JSONFileCache(str(tmp_path))).save_token( + start_url, + {"accessToken": "expired", "expiresAt": "2000-01-01T00:00:00Z"}, + session_name="expired" if session_profile else None, + ) + + session = boto3.Session(profile_name="expired") + bedrock = session.client("bedrock-runtime", region_name="us-east-1") + sso = session.client("sso", region_name="us-east-1") + # Older botocore versions let the SSO service reject an expired legacy token. + stubber = Stubber(sso) + for _ in range(6): + stubber.add_client_error("get_role_credentials", "UnauthorizedException") + + with ( + stubber, + patch.object(session._session, "create_client", return_value=sso), + patch.object(boto3, "client", return_value=bedrock), + patch.object(bedrock, "invoke_model", wraps=bedrock.invoke_model) as invoke, + patch.object(BedrockVectorizer._embed.retry, "wait", wait_none()), + pytest.raises(getattr(exceptions, error_name)), + ): + BedrockVectorizer() + invoke.assert_called_once()