Repository navigation
Conversation
Behaviour-preserving move. The `Remote`/`RemoteSecure` engines validate their target while the storage object is constructed: they parse the engine arguments, detect a local shard, and then perform a local-shard SELECT + INSERT check on a plain target, or analyze a table-function target under the user's context (which performs the source READ and SHOW COLUMNS checks). All of that lived inside `registerStorageRemote`'s create callback, reachable only from `StorageFactory::get`. A following commit needs to run exactly those checks from a second place: the initiator of an `ON CLUSTER CREATE`, which never constructs the storage. Moving the block into `parseAndValidateRemoteEngineTarget` gives both call sites one definition instead of a paraphrase that can drift out of date -- the drift that caused the bypass the next commit fixes. Two parameters replace what the callback read from `StorageFactory::Arguments`: `columns_given` (the caller has the structure, so no inference is needed) and `dependent_table_id`, which is forwarded to `parseRemoteFunctionArguments` and registers the id as a dependent of a named collection. The callback keeps passing its own table id; the preflight will pass nullptr, so a statement that is rejected leaves no dependency for a table that never exists. Verified with the whole `Remote` engine test family, which covers the create, short-ATTACH, RESTORE, named-collection and settings paths: 11/11 pass (04308, 04318, 04341, 04342, 04401, 04402, 04403, 04489, 04511, 04601, 04626). Co-Authored-By: Claude Fable 5 <[email protected]>
… CREATE
`CREATE TABLE ... ON CLUSTER c ... ENGINE = Remote(...)` authorized only what
`InterpreterCreateQuery::getRequiredAccess` emits -- CREATE_TABLE, TABLE_ENGINE and
target ids from `create.targets`. Every access check the engine performs while its
storage object is built lives behind `StorageFactory::get`, which on this path runs
only on each host's DDL worker. That worker's context carries no user unless the
server setting `distributed_ddl_use_initial_user_and_roles` is on (default off), so
`full_access = !user_id` turns all of those checks into no-ops.
Consequence: a user holding CREATE TABLE on its own database plus TABLE ENGINE ON
Remote, REMOTE and CLUSTER could create, via ON CLUSTER, a `Remote` table pointed at
a local table it may neither SELECT nor INSERT nor DESCRIBE. The same statement
without ON CLUSTER was correctly rejected with ACCESS_DENIED.
The fix calls the engine's own validation from the initiator, before the query is
enqueued, under the issuing user's context. It is the same function the storage path
calls, not a second paraphrase of the engine's requirements -- the paraphrase drifting
out of date is what opened the gap in the first place. In particular the source check
for a table-function target stays filter-aware (`checkAccessWithFilter`), which a
declarative `READ ON <SOURCE>` requirement could not express, because
`ContextAccess::checkAccessImplHelper` never reads an `AccessRightsElement`'s filter.
Carriers closed, all local-shard only:
- `Remote`/`RemoteSecure` SELECT + INSERT on a plain target,
- SHOW_COLUMNS on the target when the structure is omitted,
- the source READ and the target's own inference checks for a table-function
target, which fire even when the columns are given explicitly,
- `QueryRunner` with a `cluster` setting: READ + WRITE ON REMOTE.
Three details worth naming. Whether the structure was omitted is taken from the
contents of `create.columns_list`, not its presence: normalization materializes an
empty node before the enqueue, so a nullity test is always false there and would skip
the SHOW_COLUMNS branch while appearing to work. The legacy
`distributed_ddl_entry_format_version < 3` funnel is preflighted too, since that is a
per-query setting and the branch returns before normalization -- otherwise the whole
fix is bypassed by one SET; an engine inherited through `AS other_table` is genuinely
unknown there and is refused with NOT_IMPLEMENTED. And the initiator passes
`dependent_table_id = nullptr`, so a rejected statement registers no named-collection
dependency for a table that never exists, which would otherwise block
DROP NAMED COLLECTION forever.
This tightens ON CLUSTER to match non-ON CLUSTER behaviour; it can only turn a
previously-permitted statement into ACCESS_DENIED, never the reverse. No setting
default changes.
Two related gaps are deliberately NOT addressed, and neither is claimed fixed:
`CREATE ... AS SELECT` source/destination checks on ON CLUSTER (the pending design
decision in ClickHouse#111561), and plain `Distributed` with an omitted column list, which
bypasses SHOW_COLUMNS on the local path too because `doCreateTable` passes the global
context as the storage context.
New integration test `test_on_cluster_create_engine_access` (11 cases) pairs every
ON CLUSTER case with the same statement without ON CLUSTER, so it asserts the two
paths agree rather than that ON CLUSTER merely became stricter. Against the
unmodified tree 8 of its cases fail (the statement is accepted where ACCESS_DENIED is
required); with the fix all 11 pass, and 240/240 over 10 repeats together with the
pre-existing `test_query_runner` suite. Stateless guards: 20/20, and 200/200 over 50
randomized runs of 04318, 04337, 04418 and 04541.
Related: ClickHouse#111561
Co-Authored-By: Claude Fable 5 <[email protected]>
Review round 1 on the ON CLUSTER engine-target preflight. Three defects. Authorization now precedes target resolution. On the legacy distributed_ddl_entry_format_version < 3 funnel, execute() returns before its own checkAccess and executeDDLQueryOnCluster checks later still, so the preflight was the first thing an unprivileged user reached: one per-query setting let a user with no CREATE TABLE, no TABLE ENGINE and no CLUSTER grant drive constant-expression evaluation over its own engine arguments, named-collection resolution (whose NAMED_COLLECTION check became the first authorization event, and which getRequiredAccess never emits), address-glob expansion bounded only by table_function_remote_max_addresses, and an outbound DESC TABLE. The check now runs inside executeQueryOnCluster before the preflight, so both funnels are covered by one line and a future third call site cannot regress. It is additive: checkAccess only reads, and executeDDLQueryOnCluster still re-checks after its database substitution. The Merge engine is a third carrier. registerStorageMerge passes the local context into the constructor, which infers an omitted structure by reading each source table under a per-table SHOW_COLUMNS check, and declares supports_schema_inference. Behind StorageFactory::get, so it is a no-op on the DDL worker. This is not the Distributed case deferred by the plan: Distributed receives the global context and is therefore bypassed on the local path too, so its two paths agree, whereas Merge receives the local context and its two paths disagree, which is exactly the invariant this PR claims. The argument parsing is extracted into one function used by both the creator callback and the new preflight branch; the preflight parses a clone, because constant folding rewrites arguments in place and the caller's query may still be formatted. It calls the static getColumnsDescriptionFromSourceTables overload, which unlike the member one does not throw CANNOT_EXTRACT_TABLE_STRUCTURE on a regexp matching no table, so the initiator can never reject a statement the workers would accept. The preflight no longer forwards is_restore_from_backup. A preflight authorizes a user-issued statement and has no backup metadata to fall back on, so tolerating an unanalyzable target is meaningless there and stricter is correct. This cannot regress restore, which runs through DatabaseWithOwnTablesBase::createTableRestoredFromBackup with setInternal(true) and so never reaches the preflight. It also makes the tolerate branch structurally unreachable from the preflight, which is what the comment there previously only asserted; that comment could not be verified, since setIsRestoreFromBackup is also reachable from executeQuery on a DDL-worker query. Remote and RemoteSecure are now selected by one named condition used for both the branch and the secure flag it implies, so the secure engine cannot be dropped from the branch without also changing Remote's behaviour. Test changes. Two new cases, each verified to fail on the previous commit and pass here: one asserting authorization precedes resolution on the legacy funnel, and a paired denied/allowed Merge case with a non-ON CLUSTER control. Denials are now matched against the privilege named by the error rather than the whole error text, which also contains the query echo and a stack trace and so could not distinguish which privilege was missing. The Merge fixture grants SHOW TABLES on the target deliberately: the inference traversal silently skips a table the user cannot see, so without it the case would pass for the wrong reason. Two positive assertions that only checked the statement succeeded now read through the created table. Comments in the extracted file are trimmed to the local invariants; the rationale they carried is in the commit message of the extraction instead. Verified comment-only by stripping comments from both revisions and diffing.
The Merge branch of the initiator preflight resolves the source database through DatabaseCatalog::getDatabase, which throws UNKNOWN_DATABASE unconditionally. The initiator of an ON CLUSTER query need not host that database and need not even be a member of the cluster it targets, so a statement that used to succeed on every host that does have the database started failing outright. Tolerate that one error code, in the interpreter only, so storage construction stays strict; every host still checks its own sources while building the storage. A companion case proves a denial on the same branch still reaches the user. Add the granted direction of the RemoteSecure case. With explicit columns nothing on the create path opens a connection, so no TLS listener is needed, which the earlier note wrongly assumed. Qualify the parity claim for Merge in the changelog and the description. Its inference traversal filters on the acting user's SHOW_TABLES visibility before checking SHOW_COLUMNS, and a host acts with full access, so a source the issuing user cannot see is still inferred there unchecked. Closing that needs the host to run as the user, which is the open question in ClickHouse#111561. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 9 findings across 3 rounds;
Noted, not blocking: the tolerated Severity: mapped as blocker / major / nit. DISAGREE verdicts carry recorded evidence and are Session id: cron:clickhouse-review-slot-50:20260803-085500 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-43:20260802-235600 |
|
cc @vitlibar @evillique, could you review this? The initiator of a |
|
Workflow [PR], commit [34d4609] Summary: ✅
AI ReviewSummaryThis PR adds initiator-side engine-target preflights for Findings❌ Blockers
Final Verdict❌ Changes required. The current branch closes several important carriers, but it still leaves multiple supported |
…erStorageRemote
Two style/lint failures introduced by this PR's own extraction of the `Remote`
engine's target validation into `validateRemoteEngineTarget`.
Both `ErrorCodes::ACCESS_DENIED` uses left `StorageDistributed.cpp` with the
extracted block (the explanatory comment and the `tolerate_absent_target`
rethrow guard now live in `validateRemoteEngineTarget.cpp`, which declares the
code itself), but the `extern const int ACCESS_DENIED;` declaration stayed
behind. `ci/jobs/scripts/check_style/check_cpp.sh` block 04 rejects a
declaration with no use in the same file:
ErrorCodes::ACCESS_DENIED is defined but not used in file
src/Storages/StorageDistributed.cpp
Reproduced locally with the real checker and confirmed to disappear only with
the declaration removed; re-adding it reproduces the message verbatim.
The `columns` initialization added by the extraction selected the inferred
columns through a ternary. `StorageFactory::Arguments::columns` is a
`const ColumnsDescription &`, so the conditional operator's common type is a
prvalue and the `std::move` could never bind to a non-const reference:
error: passing result of std::move() as a const reference argument;
no move will actually happen [performance-move-const-arg]
Copy-initialize from `args.columns` and move the inferred columns in only on
the branch that uses them, which is what the pre-extraction code did. Verified
with clang-tidy-21 restricted to `performance-move-const-arg`: no diagnostic
after the change, and the original spelling reproduces the error at the same
column.
The 147 dropped jobs on the failing run are dependees of `Build (arm_tidy)` and
the dropped `Code Review` is a dependee of `Style check`; no other failure was
reported at that commit.
CI finish ledger - 94a7bf8Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task All three failures are caused by this PR's own diff and are fixed in
No other failure was reported at that commit: over the 175 check-runs, 3 failure / 3 success / How each fix was verified.
Three findings from my own second-model re-review of this push, none of them fixed here, all
Session id: cron:clickhouse-maint-slot-13:20260805-102600 |
| /// whether the user supplied a structure; only its contents do. | ||
| const bool structure_given = create.columns_list && create.columns_list->columns | ||
| && !create.columns_list->columns->children.empty(); | ||
| preflightEngineTarget(create, structure_given); |
There was a problem hiding this comment.
This unconditional preflight changes CREATE TABLE IF NOT EXISTS ... ON CLUSTER from an idempotent no-op into ACCESS_DENIED whenever the table already exists everywhere. The local path still returns from doCreateTable at database->isTableExist() before it reaches any engine-specific check, and each host on the distributed path still has that same short-circuit, but the initiator now denies the statement before any host can take it.
That means repeated deploys start failing even though no storage would be created. We need to preserve the IF NOT EXISTS short-circuit here, or move the engine-target authorization onto a path that runs only when creation will actually happen.
There was a problem hiding this comment.
Answered together with the CLUSTER finding in #113073 (comment), since one commit covers both.
Short version: the over-rejection is real, but I implemented the short-circuit you propose and measured that it opens a bypass. The initiator's catalog is not the cluster's, so a user with no rights on the target can create the name on node1 alone with a harmless engine, then have node2 build the Remote table over the forbidden target under the DDL worker's full_access context. So the fix is withdrawn rather than shipped, the divergence is disclosed, and a correct remedy needs a cluster-wide no-op decision or hosts running as the issuing user (#111561). Measurements are in the linked reply.
`executeDDLQueryOnCluster` checks `AccessType::CLUSTER`, but it does so after `executeQueryOnCluster` has already run `preflightEngineTarget`. Resolving an engine's target expands named collections and address globs and can send the `DESC TABLE` that `getStructureOfRemoteTable` uses, so a user holding `CREATE TABLE` and `TABLE ENGINE` but not `CLUSTER` reached all of that before the statement was finally rejected. Before this PR no engine work ran on that path at all, so the check now runs first here and the previous authorization boundary is restored. `getRequiredAccess` does not emit `CLUSTER`, so the added check is not redundant with the one on the line below it. The regression case withholds the target grant as well as `CLUSTER`, so the two orderings are distinguishable by which privilege the denial names: on the pre-fix binary it is `SELECT ON acl_db.local_target`, which is what shows the engine work ran first. It then grants `CLUSTER` alone and asserts the target check still denies, so the reordering does not drop either check.
|
|
||
| if (engine_is_resolved) | ||
| { | ||
| /// Resolving the engine's target evaluates user expressions and may contact remote shards, |
There was a problem hiding this comment.
UNKNOWN_DATABASE is not a harmless "nothing local to authorize" case here. It only means that the initiator does not host the source database. After this catch we still enqueue the DDL, and registerStorageMerge constructs the table on each target host with args.getLocalContext(). On a DDL worker that context has no user by default, so the constructor's SHOW COLUMNS checks are the same full-access no-ops this PR is compensating for.
That reopens the bypass whenever the source DB exists only on a target host: from node1, CREATE TABLE ... ON CLUSTER node2_only_cluster ENGINE = Merge('remote_db', '^src$') still succeeds without SHOW COLUMNS ON remote_db.src on node2. If the initiator cannot validate the source DB, this path needs to fail closed (or the worker must run as the issuing user).
There was a problem hiding this comment.
Confirmed, and this one has an observable consequence, so it is the stronger of the two findings. Measured on a two-node cluster against this branch.
I granted SHOW TABLES on the source deliberately, because that removes the residual the description already discloses (the traversal skipping sources the user cannot see) and leaves only what you are describing:
| arm | outcome |
|---|---|
ON CLUSTER node2_only_cluster ENGINE = Merge('<rdb>', '^src$'), <rdb> on node2 only, no SHOW COLUMNS |
accepted, created on node2 |
same definition, no ON CLUSTER, run on node2 |
denied SHOW COLUMNS ON <rdb>.src |
same definition, no ON CLUSTER, run on node1 where the database is absent |
UNKNOWN_DATABASE |
DESCRIBE TABLE <rdb>.src as that user on node2 |
denied SHOW COLUMNS ON <rdb>.src |
system.columns for the table the accepted statement created |
secret_col, other_col |
The last two rows are the point: the user cannot obtain those column names directly, and the ON CLUSTER route hands them over. The third row shows the route is unique, so this is not reachable without it. You are right that my in-source comment reads as though there is nothing to authorize, when what it actually means is that the initiator cannot see the source.
I am not failing closed. The same shape with SHOW COLUMNS granted on node2 is a fully authorized statement that works today, and it is pinned by test_merge_engine_source_database_absent_on_initiator. The tolerance exists because of the preceding commit on this branch, which fixed exactly the over-rejection a fail-closed rule would reinstate, so that would be a straight revert of a fix rather than a tightening. The alternative you name, the worker running as the issuing user, is the #111561 design question and out of scope here.
I have disclosed it instead, and separately from the SHOW TABLES shape, since the existing wording did not cover it: the changelog now excludes cases where the answer depends on which host runs the statement, and the description states that a Merge source database absent from the initiator is tolerated so its columns can be inferred where the user lacks SHOW COLUMNS, naming it as the one residual with a visible effect.
I have not added a test for it. An assertion pinning today's accepting behaviour would enshrine the gap as expected, which is worse than the gap.
This is the second review round on this PR, so I am leaving further discussion of the design fork to a human.
CI finish ledger - 4ee53c6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
All 174 check-runs completed and The twelve Session id: cron:our-pr-ci-monitor:20260805-230000 |
Correction to the CI finish ledger above - 4ee53c6I gave the
What I got wrong. I wrote that the step "failed while resolving and transferring its build The other three rows are unchanged and still owned by #112828, a pre-existing flaky-test fix task, Session id: cron:our-pr-ci-monitor:20260805-230000 |
Second correction to the CI finish ledger above - 4ee53c6I gave the
What I got wrong. I reported the 30-day breadth as one family of 4 rows and concluded no fixing
So there is nothing here for a fix task to own: the memory-pressure half is fixed, and the msan half The other rows are unchanged and still owned by #112828, the existing Session id: cron:our-pr-ci-monitor:20260805-230000 |
The branch was 3007 commits behind. One content conflict, in registerStorageMerge: this branch had extracted the argument parsing into parseMergeEngineArguments so the new initiator-side preflight can reuse it, while master (bfd95a6) added a deny of the internal temporary-tables database between the two argument parses. Master's placement is itself an authorize-before-evaluate boundary, so it is preserved rather than reordered: the parse helper is split into a database-argument half and a table-regexp half, and registerStorageMerge runs the deny between them, evaluating the second argument's expression only after the source database has been accepted. validateMergeEngineTarget keeps calling the combined helper, so the preflight is unchanged. The deny is deliberately not mirrored into preflightEngineTarget: the preflight runs only when the structure is omitted, and in that case it infers the schema through getColumnsDescriptionFromSourceTables, whose getDatabaseIterator already throws DATABASE_ACCESS_DENIED for that database on every host.
The preliminary getRequiredAccess check added for the legacy funnel resolved an element naming no database against the initiator's current database, because ContextAccess substitutes params.current_database for an empty one. Distributed DDL instead translates it to each host's configured default_database, so an unqualified CREATE authorized on the hosts was rejected on the initiator's database, which the user need hold nothing on. Measured on a two-host cluster whose replicas declare default_database, with the user granted CREATE TABLE only there: before this commit the unqualified create failed with "necessary to have the grant CREATE TABLE ON default.t_f3", while the same statement on the merge's other parent was accepted. Such an element is now dropped from the preliminary check and left to the translated one in executeDDLQueryOnCluster, the only place that can resolve it. Qualified elements are unaffected, so the check that motivated it still runs: with the same setup, a qualified create into a database the user cannot write is still denied, and one into a granted database is still accepted. Found by the second-model re-review of the master merge.
Keeps the local invariant (which check can resolve an empty database) and moves the rest to the previous commit's message. No code change.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 6992ce1CI is fully finished on this head and there are no failures: 154 success / 20 skipped / 0 failure of 174 check-runs,
Gate detail: (a) 0 check-runs queued or in_progress across all 174 (fully paginated); (b) One note on reading CIDB for this head: Session id: cron:our-pr-ci-monitor:20260808-183000 |
…/on-cluster-create-engine-access # Conflicts: # src/Interpreters/InterpreterCreateQuery.cpp
…flight
parseRemoteFunctionArguments folds constant arguments into literals and writes
them back into the AST it was given, because the storage-construction path
persists exactly what it parsed. The initiator preflight runs before
executeDDLQueryOnCluster clones and enqueues the query, so validating the
query's own argument list froze host-dependent expressions to the initiator's
values on every worker.
Measured on a two-node cluster with
ENGINE = Remote('127.0.0.1:9000', hostName(), 'local_target', 'default'):
pristine master stores 'node1' on node1 and 'node2' on node2, while the
preflight made both hosts store 'node1'. The same definition without
ON CLUSTER was unaffected on either tree.
The Merge branch of the preflight already clones its arguments for this
reason; this gives the Remote branch the same treatment. QueryRunner needs
none: its validation only reads the SETTINGS changes and rewrites nothing.
Co-Authored-By: Claude Fable 5 <[email protected]>
The Style check's ruff gate rejects it as F541. The literal carries no substitution: hostName() is SQL the initiator must leave unevaluated, which is exactly what the test asserts, so the prefix was never doing anything. CPython folds a placeholder-less f-string to a plain constant, so the compiled module is unchanged: with heap addresses masked, the instruction stream and the constant pool of the whole module are identical before and after.
CI finish ledger - 1b089d3CI is fully finished on this head: 178 praktika leaves, 0 dropped, 155 success / 21 skipped / 1 failure.
On the NATS failure: it is unrelated to this PR's diff (this PR touches ON CLUSTER CREATE authorization; the failing test is the NATS producer path). 25 unrelated PRs plus 4 master shas carry it in the last 30 days. I did not link #112828 as its owner: that PR fixes the consumer resubscribe path, its symbols are present in the tree praktika built for this run, and the shape here is the graded 2.2% shortfall rather than the clean stop-and-starve shape #112828 addresses, so it is a post-fix residual and a separate defect. Session id: cron:our-pr-ci-monitor:20260814-210000 |
…/on-cluster-create-engine-access # Conflicts: # src/Interpreters/InterpreterCreateQuery.cpp
The paragraph removed here restated why the initiator has to run this validation: on an ON CLUSTER query only each host's DDL worker constructs the storage, and its context carries no user, so a check performed there alone is a no-op. That is the reason for the change, not an invariant a caller of this function needs at the declaration, and it is already in the pull request description. What a caller does need - that this is the single definition of the engine's requirements, called from both paths - stays.
`preflightEngineTarget` refused every `CREATE TABLE ... ON CLUSTER ... AS other_table` with `distributed_ddl_entry_format_version < 3`, on the grounds that `setEngine` has not run there so the inherited engine cannot be authorized. That is a new validation over a supported, if non-default, setting, and it breaks `05030_totime_on_cluster_as_settings_in_zk_version`, which pins that version 2 accepts the statement: only version 1 has to be rejected, and for an unrelated reason (that format drops the query settings, so a worker cannot see `use_legacy_to_time`). Resolving the source table on the initiator instead would not be sound on that funnel. The entry ships the query text as written, so every host resolves the name in its own catalog and the initiator's answer need not be the engine a host materializes. The inherited engine therefore stays unauthorized there, exactly as before this pull request, and the pull request description discloses it. The explicit-engine preflight on the same funnel is unchanged (`test_legacy_funnel_explicit_engine_is_checked`). `test_legacy_funnel_inherited_engine_is_rejected` asserted the rejection that is removed here. It is replaced by `test_inherited_engine_is_checked_at_the_default_version`, which asserts the stronger property: at the default version the inherited engine's target is authorized like an explicit one. That case fails against a pristine master binary with "the statement was accepted" and passes with the fix.
The header said plain `Distributed` is bypassed on the non-`ON CLUSTER`
path too, so that the two paths already agree there. That stopped being
true on master: `registerStorageDistributed` now infers an omitted
structure under the local context, so a local `CREATE` is denied without
`SHOW COLUMNS` on the target while the same statement with `ON CLUSTER`
is accepted and the columns are inferred on a worker that has no user.
Measured on this branch, user holding `CREATE TABLE`,
`TABLE ENGINE ON Distributed` and `CLUSTER` but nothing on the target:
CREATE TABLE d.local ENGINE = Distributed(c, d, protected)
-> Code: 497, SHOW COLUMNS ON d.protected
CREATE TABLE d.clustered ON CLUSTER c ENGINE = Distributed(c, d, protected)
-> accepted, both columns of d.protected inferred and describable
The carrier is not addressed here, and the pull request description says
so. Only the stale claim is corrected.
|
|
||
| /// `setEngine` has not run here, and each host resolves `AS other_table` in its own catalog, so an | ||
| /// inherited engine has no single value the initiator could authorize. | ||
| if (!create.storage || !create.storage->engine) |
There was a problem hiding this comment.
Returning here leaves legacy CREATE TABLE ... ON CLUSTER ... AS other_table on the exact bypass path this PR is trying to close. On distributed_ddl_entry_format_version = 2, execute() reaches executeQueryOnCluster before setEngine, so getRequiredAccess() has no TABLE ENGINE or engine-target element and preflightEngineTarget exits here. The queued query is then materialized on each worker under the default no-user DDL context, so inheriting a Remote / Merge / QueryRunner source still skips the engine-specific checks entirely.
Because distributed_ddl_entry_format_version is a per-query setting, one SET ... = 2 is enough to reopen the bypass on a supported path. If the initiator cannot soundly authorize inherited engines on this funnel, this combination still needs to fail closed here (or be accepted only when the worker preserves the initiating user).
There was a problem hiding this comment.
Confirmed by measurement, and the funnel skips more than the engine checks this PR adds. For a user
holding nothing on prot (source prot.rsrc is ENGINE = Remote(..., prot, secret)):
| statement | result |
|---|---|
CREATE TABLE udb.d ON CLUSTER c AS prot.rsrc |
Code: 497 ... SHOW COLUMNS ON prot.rsrc |
the same without ON CLUSTER |
the same denial |
the same with distributed_ddl_entry_format_version = 2 (or 1) |
accepted, Remote(..., 'prot', 'secret') stored |
| version 2 with the engine written out instead of inherited | denied on the target, so the preflight does run there |
So the privilege the legacy funnel drops is SHOW COLUMNS on the source table, checked at
InterpreterCreateQuery.cpp:897 when the initiator resolves AS. That check is master's and
predates this PR, which is why the gap is not specific to the engine-target checks here. Reading
rows through the created table is still denied, so what the user obtains is the definition and the
column list.
I am not closing it in this PR. A blanket refusal on that funnel was here until earlier today and was
removed because master's own 05030_totime_on_cluster_as_settings_in_zk_version asserts that a
version-2 CREATE ... ON CLUSTER ... AS src succeeds. A privilege-based refusal instead is a
different change, on a funnel that was narrowed in review a few days ago, and the alternative you
name is #111561's open question. The sibling Merge finding in the same review is fixed and pushed.
| /// Runs the same per-source-table SHOW_COLUMNS checks as construction; the columns are | ||
| /// discarded. Unlike the member overload this does not reject a regexp matching no table, | ||
| /// so a statement the constructing host would accept is never rejected here. | ||
| StorageMerge::getColumnsDescriptionFromSourceTables( |
There was a problem hiding this comment.
Using the static StorageMerge::getColumnsDescriptionFromSourceTables overload here turns "the initiator found no matching source table" into success. On ON CLUSTER, that is not equivalent to "nothing to authorize": if the source database exists on the initiator but only a target host has a table matching the regexp, this preflight returns cleanly, while the worker-side StorageMerge constructor still infers columns under its no-user DDL context and skips the SHOW COLUMNS check.
So the fail-open is broader than the UNKNOWN_DATABASE case discussed above. Any host-specific Merge match set can still leak the source schema through system.columns on the created table. If we cannot prove that the initiator and every executing host see the same source set, treating an empty local result as successful validation is still unsafe.
There was a problem hiding this comment.
Agreed, and it does not need the hosts to see different tables at all.
getColumnsDescriptionFromSourceTablesImpl filters on isGranted(SHOW_TABLES) before checking
SHOW_COLUMNS, so a source the issuing user cannot see is skipped on the initiator too, leaving
nothing to check. Measured on one node, user holding nothing on prot:
| statement | before |
|---|---|
CREATE TABLE udb.m ON CLUSTER c ENGINE = Merge(prot, '^secret$') |
accepted, prot.secret's id UInt32, payload String stored in a table the user can read |
the same without ON CLUSTER |
CANNOT_EXTRACT_TABLE_STRUCTURE |
DESCRIBE prot.secret by that user |
Code: 497 |
Fixed in a314e5c7c812eab: the preflight requires SHOW COLUMNS for every table the initiator's
catalog matches, seen or not, through its own traversal so that merge() and the read path keep
their visibility semantics. The denial names the narrowest object the statement could already have
named, so a regexp does not become an enumeration oracle: SHOW COLUMNS ON prot.* here, *.* when
the database came from a REGEXP the user may not see, and ON prot.secret once it may see the
table, which is what the same statement without ON CLUSTER reports. Reverting only the source
change reddens the new case alone.
The half your wording describes remains: the initiator's catalog cannot name a table only a host
has, so that needs the host to run as the user (#111561). The absent-database tolerance also stays,
since rejecting it refuses statements that are legal when the initiator does not host the source.
`validateMergeEngineTarget` borrowed the schema-inference traversal, which skips a source table the acting user may not `SHOW_TABLES` and only then checks `SHOW_COLUMNS`. On the initiator that left the preflight vacuous for exactly the user it exists to stop: holding nothing on the source database, the statement was accepted, and every host then inferred the source's columns under its no-user DDL context, so `CREATE TABLE t ON CLUSTER c ENGINE = Merge(prot, '^secret$')` stored the structure of a table the user may not even `DESCRIBE`. The same statement without `ON CLUSTER` is refused, because there the constructor infers under the user and finds nothing it may read. `StorageMerge::checkSourceTablesAccess` runs that traversal without the visibility filter, so every table the initiator's catalog matches has to be authorized. Because a denial names the object it asks the grant for, and the regexps would turn that into an enumeration oracle, it asks for the narrowest object the context could already have named: the table when the context may see it, otherwise the database when the statement spelled it out or the context may see it, otherwise nothing. The inference overload is untouched, so `merge()` and the read path keep their own visibility semantics. Measured on a single-node cluster. Before: accepted, with the hidden columns stored. After: `ACCESS_DENIED ... SHOW COLUMNS ON prot.*` for a user holding nothing, `... ON *.*` when the database came from a `REGEXP` it may not see, and `... ON prot.secret` once it may see the table, which is byte for byte what the same statement without `ON CLUSTER` reports. Any of those grants unblocks it, and an explicit column list still requires nothing. Reverting only the source change reddens the new integration case alone, with `the statement was accepted`, while the five pre-existing `Merge` cases keep passing. Found while adjudicating a review of the same preflight's fail-open on an empty local match.
| { | ||
| validateQueryRunnerTarget(*create.storage, getContext(), mode); | ||
| } | ||
| else if (engine_name == "Merge") |
There was a problem hiding this comment.
Distributed with an omitted column list is still on the same bypass path. registerStorageDistributed resolves the schema under args.getLocalContext() for a fresh definition, so a plain CREATE TABLE ... ENGINE = Distributed(...) does the SHOW COLUMNS check there, but ON CLUSTER still reaches that code only on each DDL worker under its no-user context. Because this new preflight handles Remote/RemoteSecure, Merge, and QueryRunner but not Distributed, CREATE TABLE ... ON CLUSTER ... ENGINE = Distributed(cluster, db, protected) can still materialize protected's columns where the local form is denied.
Please add the same initiator-side omitted-structure preflight for Distributed, or fail closed on that shape until the worker preserves the issuing user.
There was a problem hiding this comment.
Agreed on the fact. The preflight branches on Remote/RemoteSecure, QueryRunner and Merge only, and the asymmetry is real. Measured on ca88c417a70bb36 (the head since then changes only the Merge arm and a comment, so it still holds): single node, cluster test_shard_localhost, a user holding CREATE TABLE on its own database plus TABLE ENGINE ON Distributed and CLUSTER, and nothing at all on the target.
| statement | observed |
|---|---|
CREATE TABLE dprobe.local_dist ENGINE = Distributed('test_shard_localhost', dprobe, protected) |
Code: 497 ... necessary to have the grant SHOW COLUMNS ON dprobe.protected |
the same with ON CLUSTER test_shard_localhost |
accepted; system.columns and DESCRIBE then expose secret_col UInt64, other_col String |
Not folding it into this PR. The preflight it would reuse is introduced here, so its fix is sequenced right after this one rather than inside it. This PR already spans four engine names across 13 files, and growing it further before review is the wrong trade. The gap is tracked with the repro above, so it is not lost.
Not failing closed on that shape either. It is the form the deployment guide tells users to write. docs/guides/oss/deployment-and-scaling/examples/2-shards-1-replica.mdx:
CREATE TABLE IF NOT EXISTS uk.uk_price_paid_distributed
ON CLUSTER cluster_2S_1R
ENGINE = Distributed('cluster_2S_1R', 'uk', 'uk_price_paid_local', rand());No column list. The same statement is in the 2-shards-2-replicas example and in all nine translations, 18 occurrences in total. Refusing it would reject documented input, so the initiator-side preflight is the only remedy I would take.
If a reviewer would rather have it in this PR, say so and I will add it.
There was a problem hiding this comment.
Yes, I think this needs to land in this PR. Distributed with an omitted column list is still a straight local-vs-ON CLUSTER SHOW COLUMNS bypass on the same CREATE TABLE ... ON CLUSTER surface, and the initiator-side preflight added here is already the mechanism that can close it. Leaving that carrier open would make the contract of this change materially incomplete.
Resolves the one conflict, in `registerStorageRemote`. Our side deletes that block (its logic moved into `parseAndValidateRemoteEngineTarget`, shared with the new initiator-side preflight); master's side keeps it. Took our empty side by editing the marked region only, rather than `git checkout --ours`, which would also have discarded master's other, auto-merged changes to the same file: the two `hasLimitAfter()`/`limitAfter()` guards in `getOptimizedQueryProcessingStage` and the Mintlify admonition migration in the engine's documentation block. Both verified present afterwards. The part that mattered was outside the conflict markers. Master's change to the deleted block came from ClickHouse#118221, which added a third disjunct to the guard: || args.getLocalContext()->isRecoveryFromStoredMetadata() Without it, a `Replicated` database replaying metadata it stored in Keeper re-analyzes a persisted `Remote` engine's table function target, and a target that legitimately matches nothing now fails the replica's initialization. Recovery cannot be recognised from `args.mode`, which it shares with an ordinary secondary-replica `CREATE` that must keep validating, so the flag is carried on the context. `validateRemoteEngineTarget.cpp` exists only on this branch, so git had no reason to report anything there, and a resolution that only removed the conflicted block would have reverted ClickHouse#118221 silently while compiling and passing this branch's own tests. Ported the disjunct into the helper and amended the route enumeration above it, which had claimed that only server startup and a short `ATTACH` skip the analysis. The second comment ClickHouse#118221 amended needs no change here: this helper's `analyze_table_function_target` comment does not enumerate those routes. Verified on the merged tree with two servers sharing one Keeper and one `tcp_port` across `127.0.0.1` and `127.0.1.1`, so the target is a local shard on both (`is_local = 1` measured on each; without that every probe below passes vacuously). This branch's own fix, under `GRANT CLUSTER ON *.*` so the query reaches the preflight rather than stopping at the cluster gate: an `ON CLUSTER` `Remote` over a table the user cannot read is refused with `SELECT ON occ.protected` when the structure is given and `SHOW COLUMNS ON occ.protected` when it is omitted, matching the local form; with the grants both succeed, and the omitted form infers `secret_col UInt64, other_col String`. ClickHouse#118221's invariant, both halves: a fresh `CREATE` naming an absent `merge()` target is still rejected with `BAD_ARGUMENTS`, while a second replica of the same Keeper path instantiates the stored definition with its recorded columns, logging no initialization error and no target re-analysis. The fresh-CREATE rejection is the control proving the analysis is reachable on that server, so the asymmetry is the evidence. Submodules were resynced to the merged pins after the ownership gate reported the worktree's own plumbing; no `contrib` drift against master remains. Co-Authored-By: Claude Opus 5 <[email protected]>
| { | ||
| validateQueryRunnerTarget(*create.storage, getContext(), mode); | ||
| } | ||
| else if (engine_name == "Merge") |
There was a problem hiding this comment.
preflightEngineTarget still enumerates only Remote/RemoteSecure, QueryRunner, and Merge, but the unified URL engine also defers a security-relevant check until storage construction: tryDispatchURLEngineByScheme requires TABLE ENGINE on the chosen delegate backend (File, S3, HDFS, AzureBlobStorage, ...) only on the host that builds the storage. On CREATE TABLE ... ON CLUSTER, that host is still a DDL worker running with no user, so ENGINE = URL('file:///...', ...) can still bypass the delegate-engine grant even though the same statement without ON CLUSTER is denied. This is the same initiator/worker split the new preflight is fixing for Remote and QueryRunner, so URL needs an initiator-side preflight too.
|
| statement | observed |
|---|---|
CREATE TABLE t (a String, b UInt64) ENGINE = URL('file:///.../probe.csv', 'CSV') |
Code: 497 ... necessary to have the grant TABLE ENGINE ON File |
the same with ON CLUSTER test_shard_localhost |
accepted; the user then reads that file and appends to it with INSERT |
Controls: granting TABLE ENGINE ON File makes the local form succeed, so the denial arm is not vacuous; a user without TABLE ENGINE ON URL is still denied under ON CLUSTER, so what is skipped is the delegate check specifically, not engine checks in general. system.query_log shows the worker replay of the queue entry running with an empty user, which is the mechanism.
The check being defeated is the one added in f23989503b8 ("a user granted only URL cannot create File/S3/Azure/HDFS backed tables"). It is not new to this PR: that commit is contained in 26.7 and 26.8, and StorageURL.cpp is not in this PR's diff.
The part I did not expect: closing it needs no code. With server setting distributed_ddl_use_initial_user_and_roles = 1 plus distributed_ddl_entry_format_version = 8, the same ON CLUSTER statement is denied by the worker with TABLE ENGINE ON File, and the queue entry carries initiator_user. Two traps for anyone trying it: the server setting has to be present at startup (after SYSTEM RELOAD CONFIG the enqueued entry still carried an empty initiator_user), and the entry format version defaults to 5 while initiator_user is only serialized from 8, so the server setting on its own is silently inert.
That leaves two shapes, and the choice is not mine to make:
- Keep extending the initiator preflight engine by engine. This PR covers
Remote,RemoteSecure,QueryRunnerandMerge;DistributedandURLwould be next, and the enumeration is only ever as complete as the next engine that defers a check to storage construction. - Have the DDL worker run as the initiator's user, which closes the whole family at once and already works behind those two settings.
@PedroTadim you cc'd this PR in August, and you classified the ATTACH sibling of this same delegate check as a critical bug fix in #115914, so I would rather have a ruling than guess. If (1), I will add Distributed and URL here. If (2), I would leave this PR as it stands and put the effort into the worker instead, which is really @ alexey-milovidov's call since the check in f23989503b8 is his. Both follow-ups are planned either way; the only thing I am waiting on is which.
This answers #113073 (comment) and #113073 (comment).
|
@groeneai I would prefer with 2, which is the general solution. How many lines would take to implement it? |
|
Two lines, and the The mechanism already exists, behind The cost is not in the line count. Two shapes avoid that, both still small:
I would build (1), but the default-off choice is @ pufit's from #71334 and the reason behind it decides which of these is right, so I do not want to overrule it on my own reading. Tell me which you prefer, or pull him in, and I will send it. In the meantime I am leaving this PR as it stands, with no |
CI finish ledger - 37cf9abCI is fully finished on this head: 176 praktika leaves, 150 success / 22 skipped / 4 failure. Two of the four are the
On The signature is one day old and master carries it without this PR. Over 90 days CIDB holds 39 failing rows for this test, every one of them on 2026-09-14 from 13:37:41Z onward and zero before that, spread over 12 unrelated PRs plus 2 true-master shas ( I did not link an existing PR as the owner: the open injectivity PRs in this area (#117197, #117238, #117894) all predate the onset by about two weeks and none of them targets this test, so linking one would be a coincidental same-area link rather than a fix. Session id: cron:our-pr-ci-monitor:20260914-180106 |
|
Fixing PR for It stops |
One conflict, in `registerStorageRemote`: this branch deletes the block whose logic moved into `parseAndValidateRemoteEngineTarget`, master keeps it. Took this branch's side by editing the marked region only, so master's auto-merged hunks in the same file stay. Master changed that block once since the previous merge. ClickHouse#121335 clears the column TTLs of a structure inferred from another table (`columns.clearColumnTTLs()`): `Remote` stores no data, and a copied TTL makes the table unloadable once an `ALTER` persists it. The block now exists only on master's side, so git reported nothing about that line. Ported to where this branch adopts the inferred columns, the only place they become the storage's structure; the preflight discards them and needs no change. Diffing master's block at the old and new merge bases shows that call as its only change. The `ErrorCodes` list conflicted too: kept master's new `ILLEGAL_COLUMN`, and `ACCESS_DENIED`, which has no use left in the file, stays removed. ClickHouse#117791's new `is_fresh_definition` constructor argument merged cleanly into this branch's `registerStorageRemote` call. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClickHouse#117572 made `Merge` schema inference require `SHOW COLUMNS` on the target of an `Alias` source table, in `getColumnsDescriptionFromSourceTablesImpl`, because an `Alias` reports its target's columns. `checkSourceTablesAccess` walks the same source tables for the `ON CLUSTER` preflight and did not follow, so on the merged tree a local `CREATE TABLE ... ENGINE = Merge(db, '^alias$')` is denied while the `ON CLUSTER` form is accepted and every host, running with no user, stores the target's columns in a table the issuing user can describe. The preflight now makes the same check, with the same message. `Remote` needs no change: its preflight infers through `getStructureOfRemoteTable`, where ClickHouse#117572 added the equivalent check. The new test covers both carriers, each paired with the same statement run locally, then with the target granted. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-create-engine-access
| { | ||
| validateQueryRunnerTarget(*create.storage, getContext(), mode); | ||
| } | ||
| else if (engine_name == "Merge") |
There was a problem hiding this comment.
This whitelist is still fail-open on the current tree. Two concrete carriers that already exist outside this diff are:
StorageAlias, which requiresSHOW_COLUMNSon every fresh target atsrc/Storages/StorageAlias.cpp:649.StorageBuffer, which requiresSHOW_COLUMNSwhen it infers an omitted destination schema atsrc/Storages/StorageBuffer.cpp:1623.
Neither engine is covered here, so CREATE TABLE ... ON CLUSTER ENGINE = Alias(...) (or Buffer(...) without an explicit column list) still reaches those checks only on the DDL worker's no-user context and bypasses them. The created table then exposes the protected schema through its own metadata even though the same local CREATE is denied.
So the new initiator-side preflight is not closed over the current engine set: extending the per-engine list later is still required unless the worker starts running the access checks as the initiating user.
Related: #111561
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed an access-control bypass in
CREATE TABLE ... ON CLUSTER: the access checks a table engine performs on its target were not enforced, so a user could create aRemote/RemoteSecuretable over a local table it may notSELECT,INSERTorDESCRIBE, aMergeover sources it may notSHOW COLUMNS, or a clusteredQueryRunnertable withoutREAD/WRITE ON REMOTE. The identical statement withoutON CLUSTERwas rejected. These engines now require the same privileges on both paths, except where the answer depends on which host runs the statement: a shard or source database present only on a target host is still authorized under that host's own context. TheMergecheck covers every source the initiator's catalog matches, seen by the issuing user or not, because a host infers from it regardless.Description
What breaks.
CREATE TABLE t ON CLUSTER c (x UInt64) ENGINE = Remote('127.0.0.1', db, protected, 'default')succeeds for a user holding onlyCREATE TABLE,TABLE ENGINE ON Remote,REMOTEandCLUSTERbut no read ondb.protected. WithoutON CLUSTERit is denied.Root cause. The initiator authorizes only what
getRequiredAccessemits. Every check an engine performs on its target sits behindStorageFactory::get, which here runs only on each host's DDL worker whose context has no user, making it a no-op (#111561).The change. The initiator now runs the engine's own validation before the enqueue, under the issuing user's context, through the same function the storage path calls.
Not fixed, not claimed.
CREATE ... AS SELECTchecks; theURLengine's delegateTABLE ENGINEcheck; an inner engine increate.targets, so a materialized view's is not preflighted either; an engine inherited throughAS other_tablebelowdistributed_ddl_entry_format_version3, where each host resolves the source itself. Those are bypassed on both paths. PlainDistributedwith an omitted column list is not: master infers its structure under the user's context, so the localCREATEis denied withoutSHOW COLUMNSwhile this path accepts it. That one follows separately, on the preflight this PR introduces.Parity is incomplete where the answer is host-specific. A
Remoteaddress local only to a target host skips the preflight, though the table stays unreadable. AMergewhose match set is partly invisible to the user is now refused, where a localCREATEinfers from the visible part. AMergesource database absent from the initiator is tolerated (rejecting it would break authorized statements), so its columns can be inferred withoutSHOW COLUMNS.Validation
Carriers covered: local-shard
SELECT+INSERTon a plainRemotetarget;SHOW_COLUMNSwhen the structure is omitted; the sourceREADand inference checks for a table-function target (these fire even with explicit columns); per-source-tableSHOW_COLUMNSwhile aMergeinfers an omitted structure;QueryRunnerwith aclustersetting.Every
ON CLUSTERcase in the new integration test is paired with the same statement without it, so the test asserts the two paths agree rather than thatON CLUSTERmerely became stricter. Each denial is matched against the privilege named by the error, not the whole error text, since the query echo and stack trace also mention the target.test_on_cluster_create_engine_access(new, 22 cases), unmodified treeRemotestateless family (04308, 04318, 04341, 04342, 04401, 04402, 04403, 04489, 04511, 04601, 04626) + 04337, 04418, 04541Mergestateless family (82 tests)test.hits, no ZooKeeper, absent clusters) with no access-control error in any of them--test-runs 50The extraction commit is a behaviour-preserving move; the whole
Remoteengine family passing byte-for-byte is the guard on it.Workflow [PR]
Sync PR [sync-upstream/pr/113073]