Skip to content

Restrict user-controllable S3 credential resolution - #104889

Closed
pamarcos wants to merge 84 commits into
ClickHouse:masterfrom
pamarcos:harden-s3-env-credentials
Closed

pamarcos wants to merge 84 commits into
ClickHouse:masterfrom
pamarcos:harden-s3-env-credentials

Conversation

@pamarcos

@pamarcos pamarcos commented May 13, 2026 •

Copy link
Copy Markdown
Member

Restricts user-controlled S3 credential resolution so SQL-visible S3 entry points cannot inherit server-managed credentials from environment/IMDS/IRSA, top-level <s3> config, or stale endpoint-scoped config.

The change covers s3(), the S3 engine, S3Queue through shared configuration, S3 named collections, dynamic S3 disks, BACKUP TO S3, and Glue catalog creation. It also redacts AWS ARNs from S3 exceptions and makes config reload drop revoked endpoint credentials instead of preserving stale clients.

Closes https://github.com/ClickHouse/clickhouse-private/issues/54202

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Tightened validation of S3 credentials provided through user SQL to prevent S3 table functions, engines, named collections, dynamic disks, backups, and Glue catalogs from reusing server-managed credentials.

pamarcos added 10 commits May 13, 2026 16:52
Reject user-controlled `use_environment_credentials` and `role_arn` paths that could make
S3 clients use server environment credentials. Also redact AWS ARNs in S3 error messages.
Do not depend on whether a named collection came from SQL because user overrides of
config collections still enter the S3 named collection path. Apply the
`use_environment_credentials` and `role_arn` restrictions uniformly.
Replace the `role_arn` output parameter with an explicit result struct so
callers can read whether `extra_credentials` was present and whether it supplied
`role_arn` without mixing parsing metadata into the argument list.
The previous version dropped the `PreformattedMessage` and only forwarded
the sanitized text to `Exception`, so anonymized error reporting
(`Exception::callback`, `ErrorCodes` statistics, `message_format_string`)
stopped working for `S3Exception`. Keep the `PreformattedMessage` shape and
sanitize only the `text` field.
`object_storage_type` also accepts `s3_plain`, `s3_with_keeper`, and
`s3_plain_rewritable` (registered in `ObjectStorageFactory`), so the
previous exact `value_str == "s3"` check let a user write
`disk(object_storage_type=s3_plain, use_environment_credentials=1, ...)`
and bypass the hardening. Match `s3` and any `s3_*` variant.
The previous gtest only checked a single ARN in the middle of a message.
Add cases for: passthrough with no ARN, empty input, ARN at start and at
end of the message, multiple ARNs in one message, and the degenerate
`arn:` token.
Replace the previous SQL test with a shell test that scopes every
global name (named collections, table names, disk names) to
`$CLICKHOUSE_DATABASE`, so several invocations of the test can run in
parallel without colliding on shared state. Cover additional vectors
from the underlying ClickHouse Cloud finding: dynamic-disk subtypes
`s3_plain`, `s3_with_keeper`, `s3_plain_rewritable`; `disk()` with
`role_arn` but only one of the keys; nested `disk(cache, disk=disk(s3))`.
Also include positive cases that exercise the same code path with
`DESCRIBE TABLE` so we never touch the network.
`hasExplicitS3Credentials` looked at the merged `auth_settings` after the
global `<s3>` section and any endpoint-scoped config block had already been
loaded. An on-prem operator that configures static admin keys in `<s3>`
would therefore implicitly authorize any user-supplied `role_arn` for STS
`AssumeRole`, signed with the admin keys. Track key provenance instead so
the check only counts keys supplied in the same SQL scope as the user-
supplied `role_arn`. Applies to both the `s3()` table function and S3 named
collections.
…arn`

`BACKUP TO S3` builds its own `S3Client` outside of `StorageS3Configuration`,
so the hardening checks added there do not apply to backups. Reject
`use_environment_credentials = 1` in named-collection backups and reject
any user-supplied `role_arn` that is not paired with `access_key_id` and
`secret_access_key` in the same SQL scope, for both the named-collection
and the positional-args entry points.
Add stateless cases for the variants the new hardening introduces:
named collection with `role_arn` and only `access_key_id` (no secret),
`s3()` with one positional key empty alongside `extra_credentials(role_arn=...)`,
and four `BACKUP TO S3` variants (positional, partial keys, named
collection with `role_arn`, named collection with `use_environment_credentials = 1`).
Add an integration test under `test_s3_credentials_hardening` that puts
static admin keys in the top-level `<s3>` config block and asserts that
user SQL cannot reuse those keys via `role_arn`. This scenario cannot be
expressed in a stateless test because it depends on server-config state.
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ba32738]

Summary: ✅


AI Review

Summary

This PR restricts user-controllable S3 credential resolution across table functions, table engines, named collections, dynamic disks, backups, and Glue catalogs by resetting server-managed credential state unless the request uses explicit user credentials or authorized endpoint-scoped configuration. I did not find a remaining correctness or security issue that needs an inline review comment, and the PR CI report currently shows no failed checks.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels May 13, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens ClickHouse’s S3 integration to prevent user-provided SQL (table function/engine args, named collections, dynamic disks, and BACKUP TO S3) from steering AWS credential resolution toward server-managed credentials (env/IMDS/IRSA or operator-configured <s3> keys), and adds ARN redaction in S3-related error messages.

Changes:

  • Add parse-time validation to reject user-controllable use_environment_credentials and to require explicit user-supplied key pairs when role_arn is provided via SQL scope.
  • Extend the same restrictions to dynamic disk configurations for all S3-backed disk types and to BACKUP TO S3 (positional args + named collections).
  • Add AWS ARN redaction for S3Exception messages plus unit/integration coverage for both hardening and sanitization.

Reviewed changes

Copilot reviewed 12 out of 13 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04235_s3_user_credentials_hardening.sh Stateless coverage for rejecting env creds / unauthorized role_arn across table function, named collections, dynamic disks, and backup.
tests/queries/0_stateless/04235_s3_user_credentials_hardening.reference Expected output for the stateless test’s “allowed” cases.
tests/integration/test_s3_credentials_hardening/test.py Integration regression test ensuring user SQL cannot piggy-back on server <s3> credentials for STS AssumeRole.
tests/integration/test_s3_credentials_hardening/configs/config.d/admin_s3.xml Test config injecting “admin” <s3> keys to validate the privilege-escalation scenario.
tests/integration/test_s3_credentials_hardening/init.py Initializes the new integration test package.
src/Storages/ObjectStorage/S3/Configuration.h Changes credential-collection API to return structured info about what user supplied.
src/Storages/ObjectStorage/S3/Configuration.cpp Implements the new hardening checks for named collections and table function arguments, including role_arn gating.
src/IO/tests/gtest_s3_uri.cpp Unit tests for AWS ARN sanitization behavior.
src/IO/S3Common.h Declares sanitizer helpers and wires sanitization into S3Exception.
src/IO/S3Common.cpp Implements ARN redaction for S3 error messages and preformatted exception messages.
src/IO/S3/Credentials.cpp Sanitizes STS AssumeRole failure log messages.
src/Disks/getDiskConfigurationFromAST.cpp Rejects env creds and unauthorized role_arn in dynamic S3 disk configs.
src/Backups/registerBackupEngineS3.cpp Applies the same restrictions to BACKUP TO S3 for named collections and extra_credentials(...).

Comment thread src/IO/S3Common.cpp Resolved
Comment thread src/IO/S3/Credentials.cpp Resolved
pamarcos added 2 commits May 14, 2026 11:49
When the dynamic `disk()` function is given `type`/`object_storage_type` via
`from_env`/`from_zk` (or augmented by an `include` directive), the literal
`s3`/`s3_*` token never appears in this function. The previous code only
checked for the literal value, so `is_s3_configuration` stayed `false` and
the new `use_environment_credentials` / `role_arn` ACCESS_DENIED checks were
skipped — even though the disk could still resolve to S3 after substitution.

Fail closed for indirect type sources: track when `type` is set via
`from_env`/`from_zk`, and when `include` is present, and apply the S3
credential checks in those cases too.

Also tighten the `role_arn` authorization check: only treat `access_key_id`
and `secret_access_key` as user-supplied keys when they are literals. Indirect
`from_env`/`from_zk` values must not authorize a user-controlled `role_arn`,
since they could resolve to credentials configured by the operator.

The stateless test `04235_s3_user_credentials_hardening` is extended with
coverage for each bypass scenario and tagged `no-fasttest` (the fast-test
build is compiled without S3 support, which made the existing positive cases
fail with `Unknown table function s3`).

Addresses review feedback on ClickHouse#104889
`sanitizeS3PreformattedMessage` previously only redacted ARNs in `text`. The
`format_string_args` vector — which holds stringified argument values — was
left untouched. Those args are propagated into structured logs and telemetry
(`Exception::message_format_string_args`,
`system.query_log.exception_format_string_args`), so an ARN passed as a
format argument to an `S3Exception` would still leak through that channel
even after the human-readable message was redacted.

Sanitize every element of `format_string_args` too. `format_string` stays
untouched: it is a literal template (e.g. `"{}"`) that never contains
user-supplied data, and preserving it keeps anonymized error reporting
(`Exception::callback`, `ErrorCodes` statistics) working for
`S3Exception`. The header docstring is updated to match.

Also fix a typo in the STS log line in
`AwsAuthSTSAssumeRoleCredentialsProvider::Reload`: the code path is
`AssumeRole`, not "AssumeRule". Making the spelling correct keeps logs
searchable.

The `gtest_s3_uri.SanitizePreformattedMessage` test covers both the
args-sanitization and the `format_string` passthrough.

Addresses Copilot review comments on
ClickHouse#104889

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 12 out of 13 changed files in this pull request and generated no new comments.

pamarcos added 2 commits May 18, 2026 19:40
Do not let user-controlled `S3` URLs inherit top-level `<s3>` credentials or the AWS environment provider chain unless a matching endpoint-scoped config exists. Preserve the parsed credential set when `S3ObjectStorage` refreshes settings so a later config update cannot reintroduce top-level credentials.

Force new dynamic `S3` disk configs to serialize `use_environment_credentials` as false when omitted, and reject Glue `aws_role_arn` unless Glue access keys are provided in the same settings.
`GlueCatalog::GlueCatalog` configured the AWS credential chain with
`use_environment_credentials = true`. Combined with the fact that
`DatabaseDataLake` is only reachable from user SQL (`CREATE DATABASE ENGINE =
DataLakeCatalog(...)` with `catalog_type = 'glue'`), this left a
user-controlled inheritance path open: a user could create a Glue database
without `aws_role_arn`, without explicit `aws_access_key_id` /
`aws_secret_access_key`, and the resulting AWS client would fall back to the
server's environment / IMDS / IRSA / STS credentials.

This is the same pattern the rest of this PR forbids elsewhere (`s3()`, S3
named collections, dynamic disks, `BACKUP TO S3`); the existing Glue check
only blocked the narrower `aws_role_arn` + missing-keys case.

Fail closed at validation time: `DatabaseDataLake::validateSettings` now
requires user-supplied `aws_access_key_id` and `aws_secret_access_key` for
Glue catalog. As defense in depth, also flip
`creds_config.use_environment_credentials` to `false` in `GlueCatalog` so
that even if validation is bypassed in the future, the AWS client cannot
silently inherit server credentials.

The integration test helper `create_clickhouse_glue_database` is updated to
forward the test minio keys as settings (in addition to the positional engine
args, which only authenticate the underlying object storage reads) when the
caller opts into credentials. A new test `test_glue_requires_explicit_keys`
covers the negative case where neither `aws_role_arn` nor explicit keys are
provided.

Addresses review feedback on ClickHouse#104889
pamarcos added 3 commits May 26, 2026 12:54
Limit the new `DatabaseDataLake::validateSettings` Glue credential checks to fresh metadata. Existing metadata still loads with the previous Glue credential chain so startup does not reject pre-existing `DataLakeCatalog` databases after upgrade.

Addresses review on ClickHouse#104889.
Clear configured S3 auth headers and encryption credentials when preparing a user-controlled S3 request with no matching endpoint config. This prevents top-level `<s3>` secrets from being sent to arbitrary URLs while preserving endpoint-scoped credentials.

The hardening integration mock now detects leaked top-level headers. See ClickHouse#104889.
Use endpoint-scoped server config where tests intentionally exercise environment credentials, and pass explicit user keys where tests exercise `extra_credentials(role_arn = ...)`.

Also update the Glue e2e credential-mode test to assert that fresh Glue catalogs cannot rely on server AWS environment credentials. See ClickHouse#104889.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 50 out of 52 changed files in this pull request and generated 2 comments.

Comment thread src/IO/S3AuthSettings.cpp Resolved
Comment thread src/Backups/registerBackupEngineS3.cpp Resolved
pamarcos added 3 commits June 3, 2026 15:37
Restore `test_empty_file` coverage under the credential hardening by passing explicit MinIO credentials to the `s3` table function.
`access_header` is only a fallback credential mechanism. Treat enabled `use_environment_credentials` as an active credential mechanism even when it comes from the default, and make the access-header test fixture opt out explicitly.
Carry the endpoint config matched by the initiator through internal backup and restore settings. Internal `BACKUP` and `RESTORE` subqueries may ignore endpoint user filters only when their current `S3` URL resolves to that same endpoint block. This keeps incremental base backups working while avoiding a blanket internal bypass.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 55 out of 57 changed files in this pull request and generated 5 comments.

Comment thread src/IO/S3Settings.cpp Resolved
Comment thread src/IO/S3Settings.cpp Resolved
Comment thread src/IO/S3Settings.cpp Resolved
pamarcos added 2 commits June 3, 2026 16:44
Catch POCO URI parse exceptions while matching endpoint-scoped `S3` settings and rethrow them as ClickHouse `BAD_ARGUMENTS` exceptions. This keeps endpoint authorization and config matching on the normal error path instead of exposing POCO exception types.
Document that named collections used with `s3` and `s3Cluster` cannot enable `use_environment_credentials` regardless of whether they come from SQL or configuration.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 55 out of 57 changed files in this pull request and generated no new comments.

Comment thread src/Backups/BackupIO_S3.cpp Resolved
Normalize `gcp_oauth` detection with the same case-insensitive predicate used by the HTTP factory, strip unsafe legacy dynamic disk `role_arn` values during metadata load, and pass endpoint `session_token` plus `access_header` values through `BACKUP` `S3` clients. Add focused integration coverage for the mixed-case, dynamic disk, and backup endpoint cases.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 55 out of 57 changed files in this pull request and generated 3 comments.

Comment on lines 127 to 136
Aws::Auth::AWSCredentials credentials(access_key_id, secret_access_key);
HTTPHeaderEntries headers;
if (access_key_id.empty())
{
credentials = Aws::Auth::AWSCredentials(settings.auth_settings[S3AuthSetting::access_key_id], settings.auth_settings[S3AuthSetting::secret_access_key]);
headers = settings.auth_settings.headers;
credentials = Aws::Auth::AWSCredentials(
settings.auth_settings[S3AuthSetting::access_key_id],
settings.auth_settings[S3AuthSetting::secret_access_key],
settings.auth_settings[S3AuthSetting::session_token]);
headers = settings.auth_settings.getHeaders();
}
Comment on lines +295 to +297
applyEndpointCredentialsOrReset(s3_settings, s3_uri, context_, allow_config_credentials, ignore_endpoint_user_filter);
if (!access_key_id_.empty())
s3_settings.resetCredentialsForUserControlledRequest();
Comment on lines +395 to +397
applyEndpointCredentialsOrReset(s3_settings, s3_uri, context_, allow_config_credentials, ignore_endpoint_user_filter);
if (!access_key_id_.empty())
s3_settings.resetCredentialsForUserControlledRequest();
@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 750/853 (87.92%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 17 line(s) · Uncovered code

Full report · Diff report

@pamarcos

Copy link
Copy Markdown
Member Author

Closing in favor of #106855

@pamarcos pamarcos closed this Jun 26, 2026
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Jul 7, 2026
…er-credentials

Restrict server-managed S3 credentials in user queries (chokepoint, alternative to ClickHouse#104889)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…er-credentials

Restrict server-managed S3 credentials in user queries (chokepoint, alternative to ClickHouse#104889)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants