diff --git a/include/ai/ai.h b/include/ai/ai.h index d4d7de3..a011efe 100644 --- a/include/ai/ai.h +++ b/include/ai/ai.h @@ -16,6 +16,10 @@ #include "google.h" #endif +#ifdef AI_SDK_HAS_BEDROCK +#include "bedrock.h" +#endif + // Type definitions #include "types/client.h" #include "types/enums.h" diff --git a/include/ai/bedrock.h b/include/ai/bedrock.h index efdbaa7..4e7db21 100644 --- a/include/ai/bedrock.h +++ b/include/ai/bedrock.h @@ -80,6 +80,10 @@ struct SecurityConfig { }; /// Configuration for Bedrock client +/// +/// When none of `profile`, `role_arn` and `web_identity_token_file` is set +/// and the `AWS_BEARER_TOKEN_BEDROCK` environment variable has an API key of +/// Amazon Bedrock, the requests carry the key instead of a signature. struct BedrockConfig { /// AWS region (e.g., "us-east-1"). If empty, uses AWS_REGION env var. std::string region; @@ -107,6 +111,17 @@ struct BedrockConfig { /// Security configuration SecurityConfig security; + + /// Whether the application initializes the AWS SDK for C++ itself: it has + /// called `Aws::InitAPI` before the provider is used, and it calls + /// `Aws::ShutdownAPI` after the last client of the provider is destroyed. + /// + /// The provider does not call `Aws::InitAPI` then. The AWS SDK counts the + /// calls: a second `Aws::InitAPI` initializes nothing, and it makes the + /// `Aws::ShutdownAPI` of the application do nothing as well, so the threads + /// of the AWS SDK are still running when the static objects that they use + /// are destroyed at the exit of the process. + bool aws_sdk_initialized_by_application = false; }; /// Create a Bedrock client with default configuration diff --git a/include/ai/types/client.h b/include/ai/types/client.h index 7fc071f..d0a26d1 100644 --- a/include/ai/types/client.h +++ b/include/ai/types/client.h @@ -61,6 +61,9 @@ class Client { /// models endpoint (`GET /v1/models`). Makes a network request. Where the /// provider says what a model is for (Gemini: `supportedGenerationMethods`), /// the models that cannot be asked through this client are left out. + /// Bedrock lists the inference profiles of the Region whose models output + /// text, followed by the text models that are invoked on demand by their + /// own IDs. virtual ModelListResult list_models() { if (pimpl_) return pimpl_->list_models(); diff --git a/src/providers/bedrock/aws_sdk_manager.cpp b/src/providers/bedrock/aws_sdk_manager.cpp index d2bff37..2cc2ea9 100644 --- a/src/providers/bedrock/aws_sdk_manager.cpp +++ b/src/providers/bedrock/aws_sdk_manager.cpp @@ -9,7 +9,11 @@ namespace ai { namespace bedrock { -void ensure_aws_sdk_initialized() { +void ensure_aws_sdk_initialized(const BedrockConfig& config) { + if (config.aws_sdk_initialized_by_application) { + return; + } + static std::once_flag once; std::call_once(once, [] { // Intentionally leaked: see the comment in the header. @@ -19,5 +23,12 @@ void ensure_aws_sdk_initialized() { }); } +Aws::Client::ClientConfigurationInitValues +client_configuration_with_known_region() { + Aws::Client::ClientConfigurationInitValues init_values; + init_values.shouldDisableIMDS = true; + return init_values; +} + } // namespace bedrock } // namespace ai diff --git a/src/providers/bedrock/aws_sdk_manager.h b/src/providers/bedrock/aws_sdk_manager.h index 7232f1b..d7dedd0 100644 --- a/src/providers/bedrock/aws_sdk_manager.h +++ b/src/providers/bedrock/aws_sdk_manager.h @@ -1,16 +1,32 @@ #pragma once +#include "ai/bedrock.h" + +#include + namespace ai { namespace bedrock { -/// Initializes the AWS SDK for C++ once per process. +/// Initializes the AWS SDK for C++ once per process, unless the application +/// does it (`BedrockConfig::aws_sdk_initialized_by_application`). /// /// The SDK does not support `Aws::InitAPI` after `Aws::ShutdownAPI`, and /// calling `Aws::ShutdownAPI` from a static destructor races with other static /// objects (and with streams that may still be running on background /// threads). So the SDK is initialized on first use and is never shut down: /// its resources are released by the operating system at process exit. -void ensure_aws_sdk_initialized(); +void ensure_aws_sdk_initialized(const BedrockConfig& config); + +/// The initial values of a client configuration whose Region the caller sets. +/// +/// The default constructor of the configuration asks the EC2 instance +/// metadata service for the Region when neither the environment nor the +/// profile names one: a network request, made every time a client is +/// created, for a value that is overwritten. This does not change where the +/// credentials are looked for: the credential chain is made separately, and +/// still uses the role of the instance. +Aws::Client::ClientConfigurationInitValues +client_configuration_with_known_region(); } // namespace bedrock } // namespace ai diff --git a/src/providers/bedrock/bedrock_client.cpp b/src/providers/bedrock/bedrock_client.cpp index 29bba7f..f38d7e6 100644 --- a/src/providers/bedrock/bedrock_client.cpp +++ b/src/providers/bedrock/bedrock_client.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -79,7 +80,8 @@ struct BedrockClient::Impl { profile = config.profile; endpoint_override = config.endpoint_override; - Aws::Client::ClientConfiguration client_config; + Aws::Client::ClientConfiguration client_config( + client_configuration_with_known_region()); client_config.region = region; client_config.connectTimeoutMs = static_cast(config.security.connection_timeout.count() * 1000); @@ -90,8 +92,19 @@ struct BedrockClient::Impl { client_config.endpointOverride = endpoint_override; } - client = std::make_shared( - make_credentials_provider(config, region), client_config); + if (uses_bedrock_api_key(config)) { + SecureLogger::log_debug("Using the API key of Amazon Bedrock"); + client = std::make_shared( + make_api_key_auth_schemes( + Aws::BedrockRuntime::BedrockRuntimeClient::GetServiceName(), + region), + nullptr, + Aws::BedrockRuntime::BedrockRuntimeClientConfiguration( + client_config)); + } else { + client = std::make_shared( + make_credentials_provider(config, region), client_config); + } valid = true; SecureLogger::log_debug("Bedrock client initialized - region: " + region); @@ -99,7 +112,7 @@ struct BedrockClient::Impl { }; BedrockClient::BedrockClient(const BedrockConfig& config) { - ensure_aws_sdk_initialized(); + ensure_aws_sdk_initialized(config); pimpl_ = std::make_unique(config); SecureLogger::log_info("Bedrock client created for region: " + pimpl_->region); @@ -146,17 +159,19 @@ GenerateResult BedrockClient::generate_text_single_step( if (!outcome.IsSuccess()) { auto result = pimpl_->response_parser.parse_converse_error(outcome.GetError()); - SecureLogger::log_api_error("Converse", options.model, pimpl_->region, - outcome.GetError().GetExceptionName(), - outcome.GetError().GetMessage(), - result.is_retryable.value_or(false)); + SecureLogger::log_api_error( + "Converse", options.model, pimpl_->region, + std::string(outcome.GetError().GetExceptionName()), + std::string(outcome.GetError().GetMessage()), + result.is_retryable.value_or(false)); return result; } auto result = pimpl_->response_parser.parse_converse_response(outcome.GetResult()); SecureLogger::log_api_call("Converse", options.model, pimpl_->region, - outcome.GetResult().GetRequestId(), latency); + std::string(outcome.GetResult().GetRequestId()), + latency); // Execute tools if the model made tool calls if (result.has_tool_calls() && options.has_tools()) { @@ -247,14 +262,13 @@ bool BedrockClient::supports_model(const std::string& model_name) const { } ModelListResult BedrockClient::list_models() { - // `ListFoundationModels` returns foundation model IDs of the Region; - // inference profile IDs (`global.anthropic...`) are not part of it. + // What Converse can be asked with on demand: the inference profiles + // (`global.anthropic...`) come first, because a current model is invoked + // through one and not by its own ID. try { ModelDiscovery discovery(pimpl_->config); ModelListResult listed; - for (const auto& info : discovery.list_models()) { - listed.models.push_back(info.model_id); - } + listed.models = discovery.list_converse_model_ids(); return listed; } catch (const std::exception& e) { return ModelListResult("Failed to list Bedrock models: " + diff --git a/src/providers/bedrock/bedrock_credentials.cpp b/src/providers/bedrock/bedrock_credentials.cpp index 9357d89..af57f67 100644 --- a/src/providers/bedrock/bedrock_credentials.cpp +++ b/src/providers/bedrock/bedrock_credentials.cpp @@ -1,14 +1,17 @@ #include "bedrock_credentials.h" #include "ai/errors.h" +#include "aws_sdk_manager.h" #include "secure_logger.h" #include #include #include +#include #include #include +#include #include #include #include @@ -22,6 +25,9 @@ namespace { // Refresh assumed-role credentials this long before they expire constexpr auto kCredentialsRefreshMargin = std::chrono::minutes(5); +// The environment variable with an API key of Amazon Bedrock +constexpr char kBedrockApiKeyVariable[] = "AWS_BEARER_TOKEN_BEDROCK"; + /// Credentials of the source identity: the configured profile, or the /// default credential chain (env vars, profile, IMDS, ...) std::shared_ptr make_source_provider( @@ -43,7 +49,8 @@ class AssumeRoleCredentialsProvider : public Aws::Auth::AWSCredentialsProvider { : role_arn_(config.role_arn), role_session_name_(config.role_session_name), external_id_(config.external_id) { - Aws::STS::STSClientConfiguration sts_config; + Aws::STS::STSClientConfiguration sts_config( + client_configuration_with_known_region()); sts_config.region = region; sts_client_ = std::make_shared( make_source_provider(config), nullptr, sts_config); @@ -88,7 +95,7 @@ class AssumeRoleCredentialsProvider : public Aws::Auth::AWSCredentialsProvider { auto outcome = sts_client_->AssumeRole(request); if (!outcome.IsSuccess()) { throw ConfigurationError("Failed to assume role: " + - outcome.GetError().GetMessage()); + std::string(outcome.GetError().GetMessage())); } const auto& credentials = outcome.GetResult().GetCredentials(); @@ -157,5 +164,37 @@ std::shared_ptr make_credentials_provider( return make_source_provider(config); } +bool uses_bedrock_api_key(const BedrockConfig& config) { + if (!config.profile.empty() || !config.role_arn.empty() || + !config.web_identity_token_file.empty()) { + return false; + } + const char* api_key = std::getenv(kBedrockApiKeyVariable); + return api_key != nullptr && *api_key != '\0'; +} + +BedrockAuthSchemes make_api_key_auth_schemes(const char* service_name, + const std::string& region) { + const char* api_key = std::getenv(kBedrockApiKeyVariable); + if (api_key == nullptr || *api_key == '\0') { + throw ConfigurationError(std::string(kBedrockApiKeyVariable) + + " is not set"); + } + + static const char kAllocationTag[] = "BedrockApiKey"; + std::shared_ptr token_provider = + Aws::MakeShared( + kAllocationTag, Aws::Auth::AWSBearerToken(Aws::String(api_key))); + + BedrockAuthSchemes schemes; + schemes.emplace( + smithy::BearerTokenAuthSchemeOption::bearerTokenAuthSchemeOption.schemeId, + smithy::BearerTokenAuthScheme( + Aws::MakeShared( + kAllocationTag, token_provider), + service_name, Aws::String(region))); + return schemes; +} + } // namespace bedrock } // namespace ai diff --git a/src/providers/bedrock/bedrock_credentials.h b/src/providers/bedrock/bedrock_credentials.h index 90a6ed4..402ef09 100644 --- a/src/providers/bedrock/bedrock_credentials.h +++ b/src/providers/bedrock/bedrock_credentials.h @@ -5,6 +5,9 @@ #include #include +// The header of a client brings the auth scheme types: their own headers +// do not include what they need. +#include #include namespace ai { @@ -23,5 +26,32 @@ std::shared_ptr make_credentials_provider( const BedrockConfig& config, const std::string& region); +/// Whether the requests carry the API key of Amazon Bedrock instead of a +/// signature: the `AWS_BEARER_TOKEN_BEDROCK` environment variable has one, +/// and the configuration names no identity of its own (a profile, a role or +/// a web identity token). +bool uses_bedrock_api_key(const BedrockConfig& config); + +/// The ways to authorize a request that a client of Bedrock is constructed +/// with: the type that its generated constructor takes. +using BedrockAuthSchemes = Aws::UnorderedMap< + Aws::String, + Aws::Crt::Variant>; + +/// The API key of the `AWS_BEARER_TOKEN_BEDROCK` environment variable, sent +/// as a bearer token, as the only way to authorize the requests of a client. +/// +/// An AWS client that is constructed with a credentials provider signs with +/// it and has no other way to authorize a request. One that is constructed +/// from the configuration of the service alone knows the API key, but it +/// also makes the default credential chain of that configuration and looks +/// for a token of IAM Identity Center first. So the client is given the one +/// scheme it is to use. +/// @param service_name the signing name of the service (`GetServiceName` of +/// the client) +/// @throws ConfigurationError if the variable is not set +BedrockAuthSchemes make_api_key_auth_schemes(const char* service_name, + const std::string& region); + } // namespace bedrock } // namespace ai diff --git a/src/providers/bedrock/bedrock_response_parser.cpp b/src/providers/bedrock/bedrock_response_parser.cpp index 55b5325..65ccbb5 100644 --- a/src/providers/bedrock/bedrock_response_parser.cpp +++ b/src/providers/bedrock/bedrock_response_parser.cpp @@ -30,8 +30,10 @@ GenerateResult BedrockResponseParser::parse_converse_response( continue; } const auto& tool_use = block.GetToolUse(); + // `Aws::String` is not `std::string` when the AWS SDK is built with + // custom memory management: the conversion is explicit. gen_result.tool_calls.emplace_back( - tool_use.GetToolUseId(), tool_use.GetName(), + std::string(tool_use.GetToolUseId()), std::string(tool_use.GetName()), BedrockRequestMapper::from_document(tool_use.GetInput())); ai::logger::log_debug("Parsed Bedrock tool call: {}", tool_use.GetName()); } diff --git a/src/providers/bedrock/bedrock_stream.cpp b/src/providers/bedrock/bedrock_stream.cpp index 1cdb8a8..94c6b7e 100644 --- a/src/providers/bedrock/bedrock_stream.cpp +++ b/src/providers/bedrock/bedrock_stream.cpp @@ -125,7 +125,9 @@ void BedrockStreamImpl::on_content_block_start( } const auto& tool_use = event.GetStart().GetToolUse(); pending_tool_calls_[event.GetContentBlockIndex()] = - PendingToolCall{tool_use.GetToolUseId(), tool_use.GetName(), {}}; + PendingToolCall{std::string(tool_use.GetToolUseId()), + std::string(tool_use.GetName()), + {}}; } void BedrockStreamImpl::on_content_block_delta( @@ -212,9 +214,10 @@ void BedrockStreamImpl::on_error( ai::logger::log_error("Bedrock stream error: {} - {}", error.GetExceptionName(), error.GetMessage()); if (!error.GetExceptionName().empty()) { - push_error(error.GetExceptionName() + ": " + error.GetMessage()); + push_error(std::string(error.GetExceptionName()) + ": " + + std::string(error.GetMessage())); } else { - push_error("Stream error: " + error.GetMessage()); + push_error("Stream error: " + std::string(error.GetMessage())); } } diff --git a/src/providers/bedrock/credential_redactor.cpp b/src/providers/bedrock/credential_redactor.cpp index ca6bba6..3519ade 100644 --- a/src/providers/bedrock/credential_redactor.cpp +++ b/src/providers/bedrock/credential_redactor.cpp @@ -6,30 +6,47 @@ namespace ai { namespace bedrock { namespace { +// The patterns are built on first use, not before `main`: a program that +// links the provider and never logs does not pay for them. + // AWS Access Key ID pattern: AKIA followed by 16 alphanumeric characters // Also matches ASIA (temporary credentials) and AIDA (IAM user IDs) -const std::regex kAccessKeyIdPattern(R"((A[KS]IA|AIDA)[A-Z0-9]{16})"); +const std::regex& access_key_id_pattern() { + static const std::regex pattern(R"((A[KS]IA|AIDA)[A-Z0-9]{16})"); + return pattern; +} -// AWS Secret Access Key pattern: 40 character base64-like string -// Note: We use a simpler pattern since std::regex doesn't support lookbehind -// This is used in context-aware redaction only -const std::regex kSecretKeyPattern(R"([A-Za-z0-9+/]{40})"); +// AWS Secret Access Key in a credential context, like +// "SecretAccessKey": "..." or secret_access_key=...: a 40 character +// base64-like string alone would match too much +const std::regex& secret_key_in_context_pattern() { + static const std::regex pattern( + R"((secret[_-]?access[_-]?key|SecretAccessKey)\s*[=:"']\s*([A-Za-z0-9+/]{40}))", + std::regex::icase); + return pattern; +} // AWS Session Token pattern: Long base64 string (typically 300+ chars) // Session tokens start with specific patterns -const std::regex kSessionTokenPattern( - R"((FwoGZXIvYXdzE|IQoJb3JpZ2luX2Vj)[A-Za-z0-9+/=]{100,})"); +const std::regex& session_token_pattern() { + static const std::regex pattern( + R"((FwoGZXIvYXdzE|IQoJb3JpZ2luX2Vj)[A-Za-z0-9+/=]{100,})"); + return pattern; +} // AWS Account ID in ARN context: 12 digit number after arn:aws:...: -const std::regex kAccountIdInArnPattern( - R"((arn:aws:[a-z0-9-]+:[a-z0-9-]*:)([0-9]{12})(:))"); - -// Generic 12-digit account ID pattern (more aggressive) -const std::regex kAccountIdPattern(R"(\b[0-9]{12}\b)"); +const std::regex& account_id_in_arn_pattern() { + static const std::regex pattern( + R"((arn:aws:[a-z0-9-]+:[a-z0-9-]*:)([0-9]{12})(:))"); + return pattern; +} // AWS credentials in environment variable format -const std::regex kEnvCredentialPattern( - R"((AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|aws_secret_access_key|aws_session_token)\s*[=:]\s*([^\s'"]+))"); +const std::regex& env_credential_pattern() { + static const std::regex pattern( + R"((AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|aws_secret_access_key|aws_session_token)\s*[=:]\s*([^\s'"]+))"); + return pattern; +} } // namespace @@ -47,7 +64,7 @@ std::string CredentialRedactor::redact(const std::string& input) { result = redact_account_id(result); // Redact credentials in environment variable format - result = std::regex_replace(result, kEnvCredentialPattern, + result = std::regex_replace(result, env_credential_pattern(), "$1=" + std::string(kRedactedPlaceholder)); return result; @@ -59,16 +76,16 @@ bool CredentialRedactor::contains_sensitive_data(const std::string& input) { } // Check for any sensitive patterns - if (std::regex_search(input, kAccessKeyIdPattern)) { + if (std::regex_search(input, access_key_id_pattern())) { return true; } - if (std::regex_search(input, kSessionTokenPattern)) { + if (std::regex_search(input, session_token_pattern())) { return true; } - if (std::regex_search(input, kAccountIdInArnPattern)) { + if (std::regex_search(input, account_id_in_arn_pattern())) { return true; } - if (std::regex_search(input, kEnvCredentialPattern)) { + if (std::regex_search(input, env_credential_pattern())) { return true; } @@ -78,32 +95,25 @@ bool CredentialRedactor::contains_sensitive_data(const std::string& input) { } std::string CredentialRedactor::redact_access_key_id(const std::string& input) { - return std::regex_replace(input, kAccessKeyIdPattern, kRedactedPlaceholder); + return std::regex_replace(input, access_key_id_pattern(), + kRedactedPlaceholder); } std::string CredentialRedactor::redact_secret_key(const std::string& input) { // Be more conservative with secret key detection to avoid false positives // Only redact if it appears to be in a credential context - std::string result = input; - - // Look for patterns like "SecretAccessKey": "..." or secret_access_key=... - std::regex secret_context_pattern( - R"((secret[_-]?access[_-]?key|SecretAccessKey)\s*[=:"']\s*([A-Za-z0-9+/]{40}))", - std::regex::icase); - - result = std::regex_replace(result, secret_context_pattern, - "$1" + std::string(kRedactedPlaceholder)); - - return result; + return std::regex_replace(input, secret_key_in_context_pattern(), + "$1" + std::string(kRedactedPlaceholder)); } std::string CredentialRedactor::redact_session_token(const std::string& input) { - return std::regex_replace(input, kSessionTokenPattern, kRedactedPlaceholder); + return std::regex_replace(input, session_token_pattern(), + kRedactedPlaceholder); } std::string CredentialRedactor::redact_account_id(const std::string& input) { // Only redact account IDs in ARN context to avoid false positives - return std::regex_replace(input, kAccountIdInArnPattern, + return std::regex_replace(input, account_id_in_arn_pattern(), "$1" + std::string(kRedactedPlaceholder) + "$3"); } diff --git a/src/providers/bedrock/input_validator.cpp b/src/providers/bedrock/input_validator.cpp index 3dbb8a5..41ed57a 100644 --- a/src/providers/bedrock/input_validator.cpp +++ b/src/providers/bedrock/input_validator.cpp @@ -1,45 +1,11 @@ #include "input_validator.h" #include -#include #include namespace ai { namespace bedrock { -namespace { -// Model ID patterns for validation -// Standard Bedrock model ID: provider.model-name-version -// Examples: anthropic.claude-3-5-sonnet-20241022-v2:0, -// amazon.titan-text-express-v1 -const std::regex kStandardModelIdPattern( - R"(^[a-z0-9-]+\.[a-z0-9-]+(-[a-z0-9]+)*(-v[0-9]+)?(:[0-9]+)?$)", - std::regex::icase); - -// Cross-region inference profile format: geo.provider.model-name-version -// Examples: us.anthropic.claude-sonnet-5-5, eu.anthropic.claude-opus-5-5, -// apac.anthropic.claude-haiku-5-5, global.anthropic.claude-fable-5-2 -const std::regex kInferenceProfilePattern( - R"(^[a-z]{2,6}\.[a-z0-9-]+\.[a-z0-9-]+(-[a-z0-9]+)*(-v[0-9]+)?(:[0-9]+)?$)", - std::regex::icase); - -// ARN format for custom/fine-tuned models -// Example: arn:aws:bedrock:us-east-1:123456789012:custom-model/my-model -const std::regex kArnModelIdPattern( - R"(^arn:aws:bedrock:[a-z0-9-]+:[0-9]+:(custom-model|provisioned-model|foundation-model)/[a-zA-Z0-9-_/]+$)"); - -// Provisioned throughput ARN format -const std::regex kProvisionedArnPattern( - R"(^arn:aws:bedrock:[a-z0-9-]+:[0-9]+:provisioned-model-throughput/[a-zA-Z0-9-_]+$)"); - -// Inference profile ARN format -// Example: -// arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.anthropic.claude-3-5-sonnet-v1:0 -const std::regex kInferenceProfileArnPattern( - R"(^arn:aws:bedrock:[a-z0-9-]+:[0-9]+:inference-profile/[a-zA-Z0-9-_.:/]+$)"); - -} // namespace - InputValidator::InputValidator() : config_() {} InputValidator::InputValidator(const SecurityConfig& config) @@ -102,36 +68,13 @@ std::optional InputValidator::validate( } bool InputValidator::is_valid_model_id(const std::string& model_id) const { - if (model_id.empty()) { - return false; - } - - // Check standard Bedrock model ID format - if (std::regex_match(model_id, kStandardModelIdPattern)) { - return true; - } - - // Check cross-region inference profile format (e.g., us.anthropic.claude-...) - if (std::regex_match(model_id, kInferenceProfilePattern)) { - return true; - } - - // Check ARN format for custom models - if (std::regex_match(model_id, kArnModelIdPattern)) { - return true; - } - - // Check provisioned throughput ARN format - if (std::regex_match(model_id, kProvisionedArnPattern)) { - return true; - } - - // Check inference profile ARN format - if (std::regex_match(model_id, kInferenceProfileArnPattern)) { - return true; - } - - return false; + // A model ID, the ID of an inference profile or an ARN: which of them + // exist, and in which form, is for Bedrock to say. Only what cannot be an + // identifier at all is refused here: an empty one, and one with whitespace, + // control or non-ASCII characters. + return !model_id.empty() && + std::all_of(model_id.begin(), model_id.end(), + [](unsigned char c) { return c > 0x20 && c < 0x7F; }); } bool InputValidator::is_valid_max_tokens(int max_tokens) const { diff --git a/src/providers/bedrock/input_validator.h b/src/providers/bedrock/input_validator.h index 81f91a1..8871e4e 100644 --- a/src/providers/bedrock/input_validator.h +++ b/src/providers/bedrock/input_validator.h @@ -6,7 +6,6 @@ #include #include -#include #include namespace ai { @@ -26,10 +25,11 @@ class InputValidator { /// @return std::nullopt if valid, error message string if invalid std::optional validate(const GenerateOptions& options) const; - /// Validate model ID format - /// Accepts: provider.model-name-version patterns and ARN formats + /// Check that a model ID can be an identifier: it is not empty and has no + /// whitespace, control or non-ASCII characters. The form is not checked: + /// Bedrock says whether it has such a model, inference profile or ARN. /// @param model_id The model identifier to validate - /// @return true if valid format + /// @return true if it can be sent to Bedrock bool is_valid_model_id(const std::string& model_id) const; /// Validate max_tokens is positive (the upper bound depends on the model and diff --git a/src/providers/bedrock/model_discovery.cpp b/src/providers/bedrock/model_discovery.cpp index a8fc63b..1836299 100644 --- a/src/providers/bedrock/model_discovery.cpp +++ b/src/providers/bedrock/model_discovery.cpp @@ -9,19 +9,142 @@ #include #include #include +#include +#include -#include +#include +#include +#include +#include #include #include +#include +#include #include #include #include +#include +#include +#include +#include +#include +#include +#include namespace ai { namespace bedrock { namespace { +// The name that the AWS SDK gives to the service. The endpoint settings of +// the environment and of the profile are looked up by it +// (`AWS_ENDPOINT_URL_BEDROCK`). An array of its own: +// `Aws::Bedrock::SERVICE_NAME` is defined together with +// `Aws::Bedrock::BedrockClient`. +const char kControlPlaneServiceName[] = "bedrock"; +const char kControlPlaneAllocationTag[] = "BedrockModelDiscovery"; + +} // namespace + +/// The two operations of the control plane of Bedrock that the provider calls. +/// +/// `Aws::Bedrock::BedrockClient` is generated with every operation of the +/// service, more than a hundred, as a virtual function, so a program that +/// links the AWS SDK statically carries all of them, with their requests and +/// responses, to list the models. This is the same client without the other +/// operations: the same base class with the same parameters, so the requests +/// are signed, sent to the same endpoint and read in the same way. +class ControlPlaneClient + : public smithy::client::AwsSmithyClientT< + kControlPlaneServiceName, + Aws::Bedrock::BedrockClientConfiguration, + smithy::AuthSchemeResolverBase<>, + Aws::Crt::Variant, + Aws::Bedrock::Endpoint::BedrockEndpointProviderBase, + smithy::client::JsonOutcomeSerializer, + smithy::client::JsonOutcome, + Aws::Client::BedrockErrorMarshaller> { + public: + template + using Outcome = + Aws::Utils::Outcome>; + + ControlPlaneClient(const BedrockAuthSchemes& auth_schemes, + const Aws::Bedrock::BedrockClientConfiguration& config) + : AwsSmithyClientT( + config, + kControlPlaneServiceName, + "Bedrock", + Aws::Http::CreateHttpClient(config), + Aws::MakeShared( + kControlPlaneAllocationTag), + Aws::MakeShared( + kControlPlaneAllocationTag), + Aws::MakeShared>( + kControlPlaneAllocationTag, + Aws::Vector( + {smithy::SigV4AuthSchemeOption::sigV4AuthSchemeOption, + smithy::BearerTokenAuthSchemeOption:: + bearerTokenAuthSchemeOption})), + auth_schemes) {} + + Outcome ListFoundationModels( + const Aws::Bedrock::Model::ListFoundationModelsRequest& request) const { + return get( + request, "/foundation-models"); + } + + Outcome + ListInferenceProfiles( + const Aws::Bedrock::Model::ListInferenceProfilesRequest& request) const { + return get( + request, "/inference-profiles"); + } + + private: + template + Outcome get(const Aws::AmazonWebServiceRequest& request, + const char* path) const { + auto outcome = + MakeRequestDeserialize(&request, request.GetServiceRequestName(), + Aws::Http::HttpMethod::HTTP_GET, + [path](Aws::Endpoint::AWSEndpoint& endpoint) { + endpoint.AddPathSegments(path); + }); + if (!outcome.IsSuccess()) { + return Outcome(std::move(outcome.GetError())); + } + return Outcome(Result(outcome.GetResult())); + } +}; + +namespace { + +// What `Aws::Bedrock::BedrockClient` registers when it is constructed with a +// credentials provider: the signature with the credentials of the provider, +// and the bearer token that the AWS SDK finds itself. +BedrockAuthSchemes make_credentials_auth_schemes( + const std::shared_ptr& provider, + const Aws::Bedrock::BedrockClientConfiguration& config) { + BedrockAuthSchemes schemes; + schemes.emplace( + smithy::SigV4AuthSchemeOption::sigV4AuthSchemeOption.schemeId, + smithy::SigV4AuthScheme( + Aws::MakeShared( + kControlPlaneAllocationTag, provider), + kControlPlaneServiceName, config.region)); + schemes.emplace( + smithy::BearerTokenAuthSchemeOption::bearerTokenAuthSchemeOption.schemeId, + smithy::BearerTokenAuthScheme( + Aws::MakeShared( + kControlPlaneAllocationTag, + config.ResolveCredentialProviderConfig()), + kControlPlaneServiceName, config.region)); + return schemes; +} + // Extract provider from model ID (e.g., "anthropic" from // "anthropic.claude-3-5-sonnet-v1:0") std::string extract_provider(const std::string& model_id) { @@ -36,7 +159,7 @@ std::string extract_provider(const std::string& model_id) { ModelDiscovery::ModelDiscovery(const BedrockConfig& config) { // Ensure AWS SDK is initialized before creating any AWS clients - ensure_aws_sdk_initialized(); + ensure_aws_sdk_initialized(config); initialize_client(config); } @@ -58,20 +181,29 @@ void ModelDiscovery::initialize_client(const BedrockConfig& config) { // Configure AWS client. `endpoint_override` is not applied: it is the // endpoint of the Bedrock runtime service, not of the Bedrock control plane // that lists the models. - Aws::Client::ClientConfiguration client_config; + Aws::Client::ClientConfiguration client_config( + client_configuration_with_known_region()); client_config.region = region_; client_config.connectTimeoutMs = static_cast(config.security.connection_timeout.count() * 1000); client_config.requestTimeoutMs = static_cast(config.security.request_timeout.count() * 1000); - // The same identity as `BedrockClient` (role, web identity, profile, or the - // default chain) - auto credentials_provider = make_credentials_provider(config, region_); - - // Create Bedrock client (not BedrockRuntime - this is for management APIs) - client_ = std::make_shared(credentials_provider, - client_config); + // The same identity as `BedrockClient` (the API key of Bedrock, a role, a + // web identity, a profile, or the default chain). This is the client of + // Bedrock, not of BedrockRuntime: it is for the management APIs. + const Aws::Bedrock::BedrockClientConfiguration control_plane_config( + client_config); + if (uses_bedrock_api_key(config)) { + client_ = std::make_shared( + make_api_key_auth_schemes(kControlPlaneServiceName, region_), + control_plane_config); + } else { + client_ = std::make_shared( + make_credentials_auth_schemes( + make_credentials_provider(config, region_), control_plane_config), + control_plane_config); + } SecureLogger::log_debug("ModelDiscovery initialized for region: " + region_); } @@ -83,6 +215,85 @@ std::vector ModelDiscovery::list_models() { return models; } +std::vector ModelDiscovery::list_converse_model_ids() { + // The models that output text. Without `byInferenceType`: a model that is + // not invoked on demand by its own ID is the one an inference profile is + // for. + Aws::Bedrock::Model::ListFoundationModelsRequest models_request; + models_request.SetByOutputModality(Aws::Bedrock::Model::ModelModality::TEXT); + auto models_outcome = client_->ListFoundationModels(models_request); + if (!models_outcome.IsSuccess()) { + const auto& error = models_outcome.GetError(); + // The name of the operation tells which permission is missing. + throw std::runtime_error( + "ListFoundationModels: " + std::string(error.GetExceptionName()) + + ": " + std::string(error.GetMessage())); + } + + std::set text_models; + std::vector on_demand_models; + for (const auto& summary : models_outcome.GetResult().GetModelSummaries()) { + const std::string model_id(summary.GetModelId()); + text_models.insert(model_id); + const auto& inference_types = summary.GetInferenceTypesSupported(); + if (std::find(inference_types.begin(), inference_types.end(), + Aws::Bedrock::Model::InferenceType::ON_DEMAND) != + inference_types.end()) { + on_demand_models.push_back(model_id); + } + } + + // A profile names its models by ARN: + // "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-...". + const auto is_text_model = [&text_models](const Aws::String& model_arn) { + const auto slash = model_arn.rfind('/'); + return slash != Aws::String::npos && + text_models.count(std::string(model_arn.substr(slash + 1))) != 0; + }; + + std::vector ids; + Aws::String next_token; + do { + Aws::Bedrock::Model::ListInferenceProfilesRequest profiles_request; + profiles_request.SetTypeEquals( + Aws::Bedrock::Model::InferenceProfileType::SYSTEM_DEFINED); + if (!next_token.empty()) { + profiles_request.SetNextToken(next_token); + } + auto profiles_outcome = client_->ListInferenceProfiles(profiles_request); + if (!profiles_outcome.IsSuccess()) { + const auto& error = profiles_outcome.GetError(); + throw std::runtime_error( + "ListInferenceProfiles: " + std::string(error.GetExceptionName()) + + ": " + std::string(error.GetMessage())); + } + + const auto& result = profiles_outcome.GetResult(); + for (const auto& profile : result.GetInferenceProfileSummaries()) { + if (profile.GetStatus() != + Aws::Bedrock::Model::InferenceProfileStatus::ACTIVE) { + continue; + } + const auto& profile_models = profile.GetModels(); + if (std::any_of(profile_models.begin(), profile_models.end(), + [&](const auto& model) { + return is_text_model(model.GetModelArn()); + })) { + ids.emplace_back(profile.GetInferenceProfileId()); + } + } + next_token = result.GetNextToken(); + } while (!next_token.empty()); + + SecureLogger::log_info("Fetched " + std::to_string(ids.size()) + + " inference profiles and " + + std::to_string(on_demand_models.size()) + + " on-demand models from Bedrock API"); + + ids.insert(ids.end(), on_demand_models.begin(), on_demand_models.end()); + return ids; +} + bool ModelDiscovery::is_model_accessible(const std::string& model_id) { auto models = list_models(); @@ -110,11 +321,11 @@ std::vector ModelDiscovery::fetch_models_from_api() { if (!outcome.IsSuccess()) { const auto& error = outcome.GetError(); - SecureLogger::log_error( - "Failed to list foundation models: " + error.GetExceptionName() + - " - " + error.GetMessage()); + SecureLogger::log_error("Failed to list foundation models: " + + std::string(error.GetExceptionName()) + " - " + + std::string(error.GetMessage())); throw std::runtime_error("Failed to list foundation models: " + - error.GetMessage()); + std::string(error.GetMessage())); } const auto& result = outcome.GetResult(); diff --git a/src/providers/bedrock/model_discovery.h b/src/providers/bedrock/model_discovery.h index 18d774e..01278e4 100644 --- a/src/providers/bedrock/model_discovery.h +++ b/src/providers/bedrock/model_discovery.h @@ -8,16 +8,11 @@ #include #include -// Forward declarations for AWS SDK types -namespace Aws { -namespace Bedrock { -class BedrockClient; -} -} // namespace Aws - namespace ai { namespace bedrock { +class ControlPlaneClient; + /// Lists the foundation models available in a Region class ModelDiscovery { public: @@ -32,6 +27,15 @@ class ModelDiscovery { /// @throws std::runtime_error if API call fails std::vector list_models(); + /// The IDs that the Converse API can be asked with on demand: the + /// system-defined inference profiles of the models that output text + /// (`ListInferenceProfiles`), followed by the models that output text and + /// are invoked on demand by their own IDs (`ListFoundationModels`). A + /// current model is usually invoked through an inference profile only, and + /// its own ID is refused. Model access grants are not checked. + /// @throws std::runtime_error if an API call fails + std::vector list_converse_model_ids(); + /// Check if a specific model is accessible /// @param model_id The model identifier to check /// @return true if model is in the available list @@ -44,7 +48,7 @@ class ModelDiscovery { /// Initialize the Bedrock client void initialize_client(const BedrockConfig& config); - std::shared_ptr client_; + std::shared_ptr client_; std::string region_; }; diff --git a/tests/unit/input_validator_test.cpp b/tests/unit/input_validator_test.cpp index 78eed5e..96a502b 100644 --- a/tests/unit/input_validator_test.cpp +++ b/tests/unit/input_validator_test.cpp @@ -55,13 +55,28 @@ TEST_F(InputValidatorTest, ValidArnModelIds) { "foundation-model/anthropic/claude")); } +// The form of a model ID is for Bedrock to say: what it lists and documents +// is not refused before it is asked +TEST_F(InputValidatorTest, ValidModelIdsOfOtherForms) { + EXPECT_TRUE( + validator_.is_valid_model_id("us-gov.anthropic.claude-sonnet-5-5")); + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws:bedrock:us-east-1:123456789012:" + "application-inference-profile/abcdef123456")); + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws-us-gov:bedrock:us-gov-west-1:123456789012:" + "inference-profile/us-gov.anthropic.claude-sonnet-5-5")); + EXPECT_TRUE(validator_.is_valid_model_id( + "arn:aws:bedrock:us-east-1:123456789012:imported-model/abcdef123456")); +} + // Test invalid model IDs TEST_F(InputValidatorTest, InvalidModelIds) { EXPECT_FALSE(validator_.is_valid_model_id("")); - EXPECT_FALSE(validator_.is_valid_model_id("invalid")); - EXPECT_FALSE(validator_.is_valid_model_id("no-dot-separator")); EXPECT_FALSE(validator_.is_valid_model_id("has spaces.model")); - EXPECT_FALSE(validator_.is_valid_model_id("special!chars.model")); + EXPECT_FALSE(validator_.is_valid_model_id("line\nbreak.model")); + EXPECT_FALSE(validator_.is_valid_model_id("tab\tseparated.model")); + EXPECT_FALSE(validator_.is_valid_model_id("non-ascii-\xC3\xA9.model")); } // Test max_tokens validation