diff --git a/redisvl/utils/vectorize/bedrock.py b/redisvl/utils/vectorize/bedrock.py index 3a590b3e..800f25f7 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,34 @@ _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 or credential and login failures.""" + if isinstance(exc, TypeError): + return False + try: + return not isinstance(exc, _credential_errors()) + except ImportError: + return True + + class BedrockVectorizer(BaseVectorizer): """The BedrockVectorizer class utilizes Amazon Bedrock's API to generate embeddings for text or image data. @@ -31,6 +59,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 +133,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 +143,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 +173,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 @@ -156,28 +186,51 @@ 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") - ) 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: + # 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( - "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, 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} + client_kwargs.update(explicit) + 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: """ @@ -195,6 +248,8 @@ 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 _credential_errors(): + 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)}") @@ -202,7 +257,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]: """ @@ -234,13 +289,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 _credential_errors(): + 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 @@ -296,6 +353,8 @@ def _embed_many( embeddings.extend(batch_embeddings) return embeddings + 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 new file mode 100644 index 00000000..eaf770ea --- /dev/null +++ b/tests/unit/test_bedrock_vectorizer.py @@ -0,0 +1,248 @@ +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_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() + 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): + _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"}) + + +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 + + +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): + NoCredentialsError = pytest.importorskip("botocore.exceptions").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): + 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 + + +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 + + +@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()