Skip to content

Bedrock: send the requests with the core of the AWS SDK; the list of models, the API key, the credentials of an application - #74

Merged
alexey-milovidov merged 10 commits into
mainfrom
bedrock-converse-models
Dec 5, 2026
Merged

alexey-milovidov merged 10 commits into
mainfrom
bedrock-converse-models

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

The Bedrock provider, as ClickHouse needs it for the AI agent of clickhouse-client.

#73 was merged into the branch of #72 after that one had been squashed into main, so its commits did not reach main. This pull request has them, and five more commits on top. The first one answers the question in ClickHouse/ClickHouse#137792 (comment): can the provider reuse the AWS SDK that the application already links, instead of the generated clients of Bedrock.

The first new commit: the requests are sent by the core of the AWS SDK

  • The provider no longer uses the generated clients of bedrock-runtime, bedrock and sts: hundreds of model classes for the four operations it calls. It writes and reads the JSON of the Converse API itself, and aws-cpp-sdk-core (Aws::Client::AWSClient) sends, signs and retries the requests, decodes the event stream of ConverseStream, and assumes a role. Of the service libraries only the endpoint rules are used.
  • BedrockTransport is the seam between the two halves. The request mapper, the response parser, the stream, the model discovery and the client are plain JSON code above it, and their unit tests run without the AWS SDK, over a fake transport.
  • create_client(config, AwsCredentialsSource) takes the credentials from the application: a function that returns the access key, the secret and the session token. An application that creates its clients only this way does not link the credential chain of the AWS SDK. A request is never sent unsigned: a source that returns no access key is a ConfigurationError.
  • The path of a request is encoded strictly, everything but the unreserved characters of RFC 3986 (Aws::Http::URI::SetRfc3986Encoded). By default the AWS SDK leaves the colon of a model identifier as it is and signs the path so. An HTTP client of the application that encodes the colon, as the one of ClickHouse does, then sends another path than the signed one, and the signature does not match.
  • An HTTP client of the application that returns before the body is read is supported for ConverseStream: the events are decoded from its stream.

In ClickHouse the provider now adds 200 KB to the stripped binary instead of 1.47 MB, and 6 files of the AWS SDK to compile instead of 290.

The second new commit: redirects are not followed

The clients of Amazon Bedrock and of AWS STS ask the HTTP client not to follow redirects (followRedirects is FollowRedirectsPolicy::NEVER). An HTTP client that follows a redirect repeats the request at the address that the answer names, with its headers and its body, and the signer is not asked again. So the API key, which the signer sends only over TLS, went to an http address in cleartext when the endpoint, or a gateway in front of it, answered with a redirect to one; the signed headers and the conversation went the same way. The services answer at the endpoint that they are asked at, so nothing is lost. Found in the review of the pull request of ClickHouse: ClickHouse/ClickHouse#137792 (comment)

Three more commits: the findings of Cursor Bugbot

  • A request for events that is repeated starts with a clean stream. The error that a failed attempt had left was never cleared, and the decoder stayed where it was inside a message: with an HTTP client that writes the response to the stream of the request, as the one of the AWS SDK over curl does, the events of the next attempt were all dropped. On the same path, the message of an error of the service was lost ("the response has no body"), because EventDecoderStream of the AWS SDK gives back only what the decoder has refused after a flush. The stream that such a client writes to is now one of the provider: it gives back what was not flushed as it is. A request whose events have been given out is not repeated when its connection fails afterwards.
  • A stream of events that stops before messageStop is an error, not an answer, also when its body ends properly for the HTTP client.
  • The endpoint of AWS STS has its FIPS and dual-stack variants, as the endpoint rules of the service make them, in the partition of the Region (Aws::Endpoint::AWSPartitions of the core). The role was assumed at an endpoint that is not a FIPS one while AWS_USE_FIPS_ENDPOINT was set. A variant that the partition does not have is a ConfigurationError.

What #73 had

  • The list of models. Client::list_models returned the foundation model IDs of the Region. A current model is invoked through an inference profile and not by its own ID, so the list had IDs that Converse refuses and lacked the ones it takes. It now returns the system-defined inference profiles of the models that output text (ListInferenceProfiles, all pages, ACTIVE only), followed by the text models that are invoked on demand by their own IDs (ListFoundationModels with byOutputModality=TEXT). An error of either request names the operation and the exception of AWS.
  • The API key of Amazon Bedrock (AWS_BEARER_TOKEN_BEDROCK) was never used. When the variable is set and the configuration names no identity of its own (a profile, a role, a web identity token), the requests carry the key instead of a signature. The AWS SDK sends such a key only to an https endpoint.
  • BedrockConfig::aws_sdk_initialized_by_application, for an application that calls Aws::InitAPI and Aws::ShutdownAPI itself. The provider called Aws::InitAPI in any case; the AWS SDK counts the calls, so the second one initializes nothing and makes the Aws::ShutdownAPI of the application do nothing as well. The AWS SDK was then never shut down, and one of its threads used the logging after the static destructors had destroyed it: a segmentation fault when the process exits.
  • The build against an AWS SDK with custom memory management, where Aws::String is not std::string: the conversions are explicit.
  • InputValidator::is_valid_model_id matched the ID against five regular expressions, which refused IDs that Bedrock lists. It refuses only what cannot be an identifier now.
  • The regular expressions of CredentialRedactor were objects of namespace scope, compiled before main by every program that links the provider. They are built on first use, and two that nothing used are gone.
  • No request to the EC2 instance metadata service for a Region that is known.
  • ai/ai.h includes ai/bedrock.h when the provider is built.

The client of the control plane with two operations, which #73 added to avoid the generated one, is gone: the core sends these two requests as well.

How it was tested

The CI of this repository does not build the Bedrock provider (AI_SDK_ENABLE_BEDROCK is off), so it does not check this change beyond the formatting.

  • The JSON half: 84 unit tests, built and run standalone, and the tests of the stream and of the client 200 times under ThreadSanitizer.
  • The AWS half: inside ClickHouse, over its HTTP client, against a mock of Bedrock that checks Signature Version 4 of every signed request. Converse, a tool call round trip, the list of models in two pages, the API key over TLS, a redirect to an address without TLS that is not followed, a model with a colon and a model addressed by its ARN, the errors of the service; and, with a throwaway test that is not committed anywhere, ConverseStream with events split across reads, an exception inside the stream, a stream that is cut off, a stream without its end, AssumeRole with its errors, the endpoints of AWS STS for the Regions of every partition that the AWS SDK has, and the credentials of an application. The streams were also checked with an HTTP client that writes the response to the stream of the request the way CurlHttpClient of the AWS SDK does: a request that is repeated after an error of the service and after an error of a proxy, the message of an error of the service, and a connection that fails after an event was given out.

The real Amazon Bedrock was not called, and no credential of AWS was used.

Related: #73
Related: #72
Related: ClickHouse/ClickHouse#137792

🤖 Generated with Claude Code


Note

High Risk
Large rewrite of authentication, signing, streaming, and AWS integration paths; incorrect handling could break requests, leak credentials, or mis-route traffic despite extensive unit testing without live Bedrock.

Overview
Refactors the Bedrock provider so HTTP to Amazon Bedrock goes through a thin BedrockTransport + AwsApiClient layer on aws-cpp-sdk-core only, instead of generated bedrock-runtime, bedrock, and sts clients. Converse/ConverseStream bodies are built and parsed as JSON (nlohmann::json); STS AssumeRole is hand-formed XML over the same core client.

New public surface: create_client(config, AwsCredentialsSource) for app-owned credentials (avoids linking the SDK default credential chain when used alone), AWS_BEARER_TOKEN_BEDROCK bearer auth when no profile/role/web-identity is set, and BedrockConfig::aws_sdk_initialized_by_application so the host owns Aws::InitAPI/ShutdownAPI. Redirect following is disabled for Bedrock and STS clients; request paths use strict RFC 3986 encoding (relevant for model IDs/ARNs with :). list_models now prefers inference profile IDs plus on-demand text foundation models.

CMake drops the sts AWS SDK component; adds transport/STS endpoint sources. Tests gain fake-transport unit coverage; model ID validation and credential redaction are relaxed/lazy-initialized respectively.

Reviewed by Cursor Bugbot for commit 042cbe2. Bugbot is set up for automated code reviews on this repo. Configure here.

alexey-milovidov and others added 6 commits December 5, 2026 04:17
`GET /v1beta/models` lists every model of the Gemini API: the ones for
embeddings, for images and video, and for the Live API too. The client speaks
`generateContent`, so a model of the list that cannot be asked through it is of
no use to a caller that offers the list for a choice.

`GoogleClient::list_models` now leaves out a model that says which methods it
serves (`supportedGenerationMethods`) and does not name `generateContent`. A
model that does not say is listed, as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…inside an application that owns the AWS SDK

`Client::list_models` of the Bedrock provider returned the foundation model IDs
of the Region. A current model is invoked through an inference profile and not
by its own ID, so the list had IDs that Converse refuses and lacked the ones it
takes. `ModelDiscovery::list_converse_model_ids` returns the system-defined
inference profiles of the models that output text (`ListInferenceProfiles`, all
pages, `ACTIVE` only), followed by the text models that are invoked on demand
by their own IDs (`ListFoundationModels` with `byOutputModality=TEXT`). An
error of either request names the operation and the exception of AWS.

An API key of Amazon Bedrock in the `AWS_BEARER_TOKEN_BEDROCK` environment
variable was never used: the AWS clients were constructed with a credentials
provider, and such a client signs with it and has no other way to authorize a
request, so with the key alone every request failed to be signed. When the
variable is set and the configuration names no identity of its own (a profile,
a role, a web identity token), the clients are constructed with the bearer
token scheme alone, with the key as its token. The AWS SDK sends such a token
only to an `https` endpoint.

`BedrockConfig::aws_sdk_initialized_by_application` is for an application that
calls `Aws::InitAPI` and `Aws::ShutdownAPI` itself. The provider called
`Aws::InitAPI` in any case. The AWS SDK counts the calls: the second one
initializes nothing, and it makes the `Aws::ShutdownAPI` of the application do
nothing as well. The AWS SDK was then never shut down, and a thread of it that
was still running when the process exited used the logging that the static
destructors had destroyed already: a segmentation fault at exit.

The provider did not compile against an AWS SDK that is built with custom
memory management, where `Aws::String` has an allocator of its own and is not
`std::string`: the conversions are explicit now.

`InputValidator::is_valid_model_id` matched the ID against five regular
expressions, which refused IDs that Bedrock lists. Which IDs exist is for
Bedrock to say: the validator refuses only what cannot be an identifier (an
empty one, or one with whitespace, control or non-ASCII characters).

The regular expressions of `CredentialRedactor` were objects of namespace
scope, so every program that links the provider compiled them before `main`.
They are built on first use, and two that nothing used are gone.

The configuration of an AWS client was default-constructed, which asks the EC2
instance metadata service for the Region when neither the environment nor the
profile has one, although the Region is set from `BedrockConfig` right after.
`client_configuration_with_known_region` skips that request. The credential
chain is made separately and still uses the role of the instance.

`ai/ai.h` includes `ai/bedrock.h` when the provider is built
(`AI_SDK_HAS_BEDROCK`), as it does for the other providers.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
`ModelDiscovery` used `Aws::Bedrock::BedrockClient`, which is generated with
every operation of the control plane of Bedrock (108 of them) as a virtual
function. A program that links the AWS SDK statically carries all of them, with
their requests and responses, although the provider calls only
`ListFoundationModels` and `ListInferenceProfiles`: in ClickHouse it was the
largest part of what the provider added to the binary, and 557 source files of
the AWS SDK to compile.

`ControlPlaneClient` in `model_discovery.cpp` is the same client without the
other operations: the same base class (`smithy::client::AwsSmithyClientT`) with
the same parameters as the generated client (the endpoint provider and the error
marshaller of Bedrock, the same authentication schemes), and the generated
requests and results of the two operations. So the requests are signed, sent to
the same endpoint and read in the same way. A build that links the whole
`aws-cpp-sdk-bedrock` library is not affected; a build that compiles the AWS SDK
itself needs only the endpoint provider, the error marshaller and the models of
the two operations from it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…dentials of an application

The provider used the generated clients of `bedrock-runtime`, `bedrock` and
`sts`: hundreds of model classes for the four operations it calls. An
application that already links the AWS SDK for something else paid for all of
that again.

Now the provider writes and reads the JSON of the Converse API itself, and
only `aws-cpp-sdk-core` sends, signs and retries the requests
(`Aws::Client::AWSClient`), decodes the event stream and assumes a role. Of
the service libraries the endpoint rules alone are used.

- `BedrockTransport` is the seam between the two halves. The request mapper,
  the response parser, the stream, the model discovery and the client are
  plain JSON code above it, and their tests run without the AWS SDK, over a
  fake transport.
- `create_client(config, AwsCredentialsSource)` takes the credentials from the
  application instead of looking for them. An application that creates its
  clients only this way does not link the credential chain of the AWS SDK. A
  request is never sent unsigned: a source without an access key is an error.
- The path of a request is encoded strictly, everything but the unreserved
  characters of RFC 3986. By default the AWS SDK leaves the colon of a model
  identifier as it is and signs the path so, and an HTTP client of the
  application that encodes the colon would send another path than the signed
  one.
- An HTTP client of the application that returns before the body is read is
  supported for `ConverseStream`: the events are decoded from its stream.

In ClickHouse the provider now adds 200 KB to the stripped binary instead of
1.47 MB.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
alexey-milovidov added a commit to ClickHouse/ClickHouse that referenced this pull request Dec 5, 2026
The branch of #137759 has moved
`contrib/ai-sdk-cpp` to the commit of `main` that has the Gemini changes
(ClickHouse/ai-sdk-cpp#72, merged).

Here `contrib/ai-sdk-cpp` is the head of
ClickHouse/ai-sdk-cpp#74: `main` merged into the branch
of the Bedrock provider. The files are the same as at the commit that was used
before the merge, `a02d72e7c965c343c2e3c4086ef2a170c4ea317f`.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 6718cb7. Configure here.

The clients of Amazon Bedrock and of AWS STS ask the HTTP client not to
follow redirects (`followRedirects` is `FollowRedirectsPolicy::NEVER`).

An HTTP client that follows a redirect repeats the request at the address
that the answer names, with its headers and its body. The API key of
Bedrock is a bearer token, and the signer refuses to send it over a
connection without TLS, but it is not asked again for the repeated request:
an endpoint or a gateway that answers with a redirect to an `http` address
got the key sent there in cleartext. The signed headers, with the session
token, and the conversation went the same way.

The services answer at the endpoint that they are asked at, so nothing is
lost.

Found in the review of ClickHouse/ClickHouse#137792:
ClickHouse/ClickHouse#137792 (comment)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
alexey-milovidov added a commit to ClickHouse/ClickHouse that referenced this pull request Dec 5, 2026
An endpoint of Amazon Bedrock, or a gateway in front of it, that answered an
`https` request with `307 Temporary Redirect` to an `http` address got the
API key of the `AWS_BEARER_TOKEN_BEDROCK` environment variable sent there in
cleartext: `PocoHTTPClient` followed up to ten redirects, and repeated the
request at the new location with all of its headers. The check that the key
is sent only over TLS looked at the endpoint only, and the signer of the AWS
SDK, which refuses a connection without TLS as well, is not asked again for
a repeated request.

Now the clients of Amazon Bedrock in the AI SDK ask not to follow redirects
(`followRedirects` of the client configuration of the AWS SDK), and
`PocoHTTPClient` does what such a client asks for: a redirect is the
`TOO_MANY_REDIRECTS` exception, and nothing is sent to its location. It is so
for the signed requests as well. The other clients, the ones of S3 with
their `s3_max_redirects` among them, follow redirects as before.

`contrib/ai-sdk-cpp` moves to the commit with this change:
ClickHouse/ai-sdk-cpp#74

The test `06038_client_ai_bedrock_provider` has a new case: the mock behind
TLS answers with a redirect to its address without TLS. Before the change
the request was repeated there with the API key and was answered.

Found in the review:
#137792 (comment)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
alexey-milovidov and others added 3 commits December 5, 2026 17:14
A request for events (`ConverseStream`) that the AWS SDK repeats kept what
its failed attempt had left behind:

- The error that ended the stream was never cleared. An HTTP client that
  writes the response to the stream of the request, as the one of the AWS
  SDK over curl does, may write the body of an HTTP error there too. It is
  not a stream of events, the decoder says so, and then the events of the
  next attempt, a successful one, were all dropped and the request failed.
- The decoder stayed where it was inside a message:
  `EventStreamDecoder::Reset` resets only the handler of the events. Now
  the decoder is put to the start of a message for every attempt.

The stream that such an HTTP client writes to is now one of the provider
instead of `EventDecoderStream` of the AWS SDK. That one gives back only
what the decoder has refused after a flush, and the HTTP clients of the AWS
SDK do not flush the body of an error of the service: the name of the error
came from a header, and its message was lost ("the response has no body").
The new stream gives back what was not flushed as it is. It also gives back
the beginning of what went to the decoder, until an event is found in it:
this is the text of an error that is not one of the service, such as the
one of a proxy.

A request whose events have been given out to the caller is not repeated
when its connection fails afterwards: the events would be given out once
more.

An HTTP client that returns a stream to read the response from, as the one
of ClickHouse does, was not affected: the events are read from that stream
after the request has succeeded.

Found by Cursor Bugbot:
#74 (comment)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A response to `ConverseStream` whose body ended properly for the HTTP
client, while its events stopped before `messageStop`, was taken for a whole
answer: the stream ended with the text that had arrived and without an
error. Now it ends with the error "the stream of events ended before the end
of the message", unless the caller has asked to stop or another error is
already reported.

Found by Cursor Bugbot:
#74 (comment)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The endpoint of AWS STS that a role is assumed at (`role_arn` of the
configuration or of a profile) was always the Regional one. With
`AWS_USE_FIPS_ENDPOINT`, or `use_fips_endpoint` in the profile, the requests
to Amazon Bedrock went to its FIPS endpoint, and the role was assumed at an
endpoint that is not a FIPS one. The dual-stack setting was not looked at
either.

The endpoint is now made the way the endpoint rules of AWS STS make it
(`make_sts_endpoint`): the partition of the Region comes from the partitions
that the core of the AWS SDK has (`Aws::Endpoint::AWSPartitions`), with its
DNS suffixes and the variants of the endpoints that it has, so the Regions
of every partition get the right suffix, not only the ones that were listed
here. A variant that the partition does not have is a `ConfigurationError`,
as it is an error in the endpoint rules: the Regional endpoint is not used
in its place silently.

The generated client of AWS STS, which has these rules inside, is still not
linked. An endpoint that the configuration, the environment or the profile
sets is used as it is, as before.

Found by Cursor Bugbot:
#74 (comment)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
alexey-milovidov added a commit to ClickHouse/ClickHouse that referenced this pull request Dec 5, 2026
…nt of Amazon Bedrock

The changes of the provider of Amazon Bedrock in the AI SDK, made for the
findings of the review of ClickHouse/ai-sdk-cpp#74:

- A request for events that is repeated starts with a clean stream, the
  message of an error of the service is not lost when an HTTP client writes
  the response to the stream of the request, and a request whose events have
  been given out is not repeated.
- A stream of events that stops before the end of the message is an error.
- The endpoint of AWS STS, where a role is assumed, has its FIPS and
  dual-stack variants, in the partition of the Region. The code that makes
  it is a new source file, `sts_endpoint.cpp`.

None of them changes what the client does. Its AI agent does not ask for
streams of events, and it takes the credentials of AWS from the chain of
ClickHouse: the code of the SDK that assumes a role is not called. The pin
moves so that it stays at the head of the branch that is reviewed there.

Related: #137792

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@alexey-milovidov alexey-milovidov self-assigned this Dec 5, 2026
@alexey-milovidov
alexey-milovidov merged commit 9faf3c9 into main Dec 5, 2026
3 checks passed
alexey-milovidov added a commit to ClickHouse/ClickHouse that referenced this pull request Dec 6, 2026
ClickHouse/ai-sdk-cpp#74 is merged as one squashed
commit, `9faf3c91dff6`. The submodule pointed to the last commit of the
branch of that pull request, `042cbe2743dd`, which is not in `main`. The two
commits have the same tree (`c8d6630c64f4`), so nothing changes in what is
built.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant