Repository navigation
Infer an omitted Distributed structure under the user's context - #113220
PedroTadim merged 2 commits into
Conversation
When CREATE TABLE ... ENGINE = Distributed(...) omits the column list, the structure is inferred from the target table. For a local shard that inference reads the target's metadata and is gated by a SHOW_COLUMNS check in getStructureOfRemoteTableInShard. That check could not enforce anything. StorageDistributed's constructor infers using its own context, which is the global one, because the storage outlives any query context and needs a context for its background insert work. A global context has no user, so Context::getAccess computes full_access = !user_id and the check is a no-op. Since the engine sets supports_schema_inference, a columns-less CREATE is accepted rather than rejected, and reaches that inference. The effect is that a user holding CREATE TABLE on its own database plus TABLE ENGINE ON Distributed could learn the column names and types of any local table it is not allowed to describe, and the inferred columns are persisted into its own metadata, so the disclosure survives a restart. registerStorageDistributed now performs the inference itself under args.getLocalContext() and passes the resulting columns to the constructor, so the check runs against the creating user. The sibling Remote engine, which shares StorageDistributed, already does exactly this, and its comment names this hazard; Distributed was the engine that still had the hole. The inference is skipped when the definition comes from already-validated metadata stored on this server, that is server startup and short ATTACH queries, where there is no user to check against and the constructor's inference is the only source of the columns. SYSTEM RESTART REPLICA does not need to be admitted by that guard: it returns early unless the table is a StorageReplicatedMergeTree, so a Distributed table never reaches it. The required privilege is the narrowest one. SHOW_COLUMNS is weaker than the SELECT and INSERT that Remote requires, and SELECT implies it, so any user who can read the target is unaffected. Explicit column lists, Remote and RemoteSecure, the remote table function, and metadata loading are unchanged. Also worth noting for future readers: the explicit macro expansion the first version of this change performed was redundant, because Clusters::getCluster expands macros in the cluster name itself.
The creator-side inference added in the previous commit passed the raw engine
argument to getCluster, while StorageDistributed's constructor looks up the
macro-expanded cluster_name member. Two of the three lookups
Context::tryGetCluster performs expand the name internally, but
tryGetReplicatedDatabaseCluster does not, and that is the only way a Replicated
database's implicit cluster resolves. So a columns-less
Distributed('{macro}', ...) whose macro names a Replicated database resolved
before this series and threw CLUSTER_DOESNT_EXIST after it.
Expand the name first, inside the branch that infers, so the two resolutions are
identical and an expansion failure cannot become a new error for a create that
supplies its columns explicitly.
Measured on a single node with an embedded Keeper, a Replicated database
probe_repl_db and a macro naming it: the raw-name form fails with
Code: 701 CLUSTER_DOESNT_EXIST while the expanded form infers the columns.
Controls on the same binary: an explicit column list succeeds, and so does a
columns-less create naming the cluster by its expanded literal, so the failure
is specific to the raw-name lookup.
Also restate the constructor's empty-columns comment as an invariant rather than
a claim about the caller set.
Internal second-model review (click to expand)Two review rounds: an independent cold read of the resulting code plus a Round 0 (not published; the PR was held back)❌ blocker -- ❌ major -- the pre-construction cluster lookup resolved a different cluster Round 1 (this revision)
One cold finding dropped after reading the evidenceI flagged the temporary-table case (case 4) as a possibly vacuous oracle: Verdicts this revision: 3 agreed, 0 disagreed, 2 dropped. The reviewer made no |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-45:20260803-222900 |
|
cc @azat @pufit, could you review this? A columns-less |
|
Workflow [PR], commit [6213d92] Summary: ✅
AI ReviewSummaryThis PR moves omitted-schema inference for PR Metadata
Findings
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 17/19 (89.47%) · Uncovered code |
| /// local shard is not made against the global context the constructor holds. Skipped when the | ||
| /// definition comes from already-validated metadata, which has no user to check against. | ||
| ColumnsDescription columns = args.columns; | ||
| if (columns.empty() && !(isLoadingFromExistingMetadata(args.mode) || args.query.attach_short_syntax)) |
There was a problem hiding this comment.
args.getLocalContext() only carries the creator's access rights here for ordinary databases. A CREATE TABLE inside an ENGINE = Replicated database is replayed through DatabaseReplicatedTask::makeQueryContext (src/Interpreters/DDLTask.cpp:690), which inherits DDLTaskBase::makeQueryContext and only calls setUser when DDLLogEntry.initiator_user is present (src/Interpreters/DDLTask.cpp:309-330). Unlike executeDDLQueryOnCluster, DatabaseReplicated::tryEnqueueReplicatedDDL never fills initiator_user or initiator_user_roles (src/Databases/DatabaseReplicated.cpp:1474-1481), so Context::getAccess() falls back to full_access = !user_id again (src/Interpreters/Context.cpp:2291).
That means the same columns-less Distributed create is still accepted in replicated databases without SHOW COLUMNS, even though it is not an explicit ON CLUSTER query. We either need initiator-side validation before the replicated DDL is enqueued, or the PR contract/changelog narrowed to ordinary databases only.
There was a problem hiding this comment.
Confirmed, and it is worse than stated. I verified the four hops and then measured it.
Source: DatabaseReplicatedTask::makeQueryContext does inherit the base (DDLTask.cpp:689); setUser is guarded by preserve_user && !entry.initiator_user.empty() (:310, :330); tryEnqueueReplicatedDDL fills query, initiator, settings, tracing, initial_query_id, is_backup_restore and no initiator identity (DatabaseReplicated.cpp:1474-1481), unlike executeDDLQueryOnCluster.cpp:195-199; and full_access = !user_id at Context.cpp:2287. The replay's from_context is the DDLWorker's copy of the database context (DDLWorker.cpp:104, :575), which has no user.
Measured on a single node with an embedded Keeper: a restricted user with CREATE TABLE on its own databases plus TABLE ENGINE ON Distributed and no SHOW COLUMNS on the target. In an ordinary database the columns-less create is denied naming SHOW COLUMNS ON default.protected_target; inside a Replicated database the same create succeeds and persists the target's real columns. Raising distributed_ddl_use_initial_user_and_roles does not close it, since the missing field is the one the guard tests.
Two corrections to the direction you gave. First, distributed_ddl_use_initial_user_and_roles is not sufficient for ON CLUSTER either: initiator_user is only serialized at version >= INITIATOR_USER_VERSION = 8 (DDLTask.cpp:180-183) while distributed_ddl_entry_format_version defaults to 5, so the field is absent and the second conjunct fails regardless of the setting. With the setting on and the version raised to 8, the ON CLUSTER denial does fire; the Replicated path still does not. Second, the right framing is not ON CLUSTER plus a special case but "anything replayed from the DDL queue", which is how the description now reads.
Taking your first option. Initiator-side validation for the queue paths is the wider question of authorizing replicated DDL, and widening this PR into it mid-review is not the right move; it belongs with the mechanism #113073 introduces. The changelog and the scope paragraph now say the fix covers a CREATE the local server executes itself, and name both queue paths as uncovered, with the version gate stated. No code change.
No test case for this: a stateless test cannot create a Replicated database, since it needs Keeper and an interserver_http_port.
CI finish ledger - 6213d92CI is fully finished on this head: 175 checks reported, 153 success, 22 skipped, 0 failures.
Session id: cron:our-pr-ci-monitor:20260804-120000 |
…e-function branch Master commit a030cdd (#113220) added an inference of an omitted structure under the user's context for the classic `(db, table)` form of `Distributed`, declaring a local `columns` copy before the shared constructor call. This branch already declares such a copy earlier, for the table-function target branch, so the automatic merge produced a redefinition in the same scope. Keep the early declaration and gate the classic-form inference on the target not being a table function: a table-function target infers its columns in its own branch, and `remote_database` / `remote_table` are empty for it. All 16 tests of this PR and the new `04715_distributed_infer_columns_access` from #113220 pass locally. Co-Authored-By: Claude Fable 5 <[email protected]>
Backport #113220 to 26.6: Infer an omitted Distributed structure under the user's context
Backport #113220 to 26.5: Infer an omitted Distributed structure under the user's context
Backport #113220 to 26.3: Infer an omitted Distributed structure under the user's context
…r the user's context
Backport #113220 to 26.7: Infer an omitted Distributed structure under the user's context
Backport #113220 to 25.8: Infer an omitted Distributed structure under the user's context
…e from legacy column-less metadata After #113220, a plain `CREATE` infers the omitted structure under the user's context and `addColumnsDescriptionToCreateQueryIfNecessary` persists the inferred columns into the stored definition, so the `CREATE`-based tests no longer reach the constructor's global-context structure fetch. The remaining zero-version path is a column-less definition loaded from metadata written by an older server version, which `DatabaseOnDisk::createTableFromAST` deliberately loads with empty columns. The new test simulates such legacy metadata by stripping the persisted column list while the table is detached; before the fix in `getStructureOfRemoteTable` the re-`ATTACH` failed with the logical error `Sending a distributed query with unknown (zero) client version`.
| StorageID{remote_database, remote_table}, | ||
| local_context, | ||
| /* table_func_ptr = */ nullptr); | ||
| } |
There was a problem hiding this comment.
@PedroTadim please move getStructureOfRemoteTable that we have in ctor to this method as well
…cture under the user's context
…cture under the user's context
…cture under the user's context
…cture under the user's context
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a case where
CREATE TABLE ... ENGINE = Distributed(...)without a column list could reveal the structure of a local table the creating user is not allowed to see. For aCREATEthe local server executes itself, the structure is now inferred under the user's own context, soSHOW COLUMNSon the target table is required, as it already is for theRemoteengine. ACREATEreplayed from the DDL queue (ON CLUSTER, or one inside aReplicateddatabase) is not covered.Description
Related: #113073. Found while reviewing engine-level schema inference.
What breaks. A user with
CREATE TABLEon its own database plusTABLE ENGINE ON Distributedcan learn the columns of a local table it may notDESCRIBE, by creating a columns-lessDistributedtable over it. On master thatCREATEsucceeds and persists them.Root cause. The structure is inferred by
StorageDistributed's constructor, which holds only the global context because the storage outlives any query context. With no user,full_access = !user_idmakes theSHOW_COLUMNScheck ingetStructureOfRemoteTableInSharda no-op for a local shard. The check is in the right place; the context it got cannot enforce it.The change.
registerStorageDistributednow infers the structure underargs.getLocalContext()and passes the columns to the constructor, as the siblingRemoteengine does, skipping it for already-validated metadata (server startup, shortATTACH). Explicit column lists,Remote/RemoteSecureandremote()are unaffected.SHOW COLUMNSis the narrowest privilege here, weaker thanRemote'sSELECTplusINSERT.Scope: only a
CREATEthe local server executes itself. ACREATEreplayed from the DDL queue reaches the engine on a userless context, so the check is a no-op there; this PR does not change that. ForON CLUSTERthe worker sets a user only whendistributed_ddl_use_initial_user_and_rolesis on anddistributed_ddl_entry_format_versionis at least 8 (the initiator is serialized from version 8; the default is 5); with both raised the denial fires. Inside aReplicateddatabasetryEnqueueReplicatedDDLrecords no initiator, so no setting closes it. Both want #113073's initiator-side check.Validation. New test
04715_distributed_infer_columns_accesscovers the denial, inference onceSHOW COLUMNSis granted, explicit column lists, the temporary-table path and re-attach; it fails on master, passes here. 50 randomized runs pass, as do the existingDistributedinference andRemoteaccess tests. The queue paths need Keeper and were measured separately.Version info
26.8.1.929(included in26.8and later)26.6.3.13,26.5.7.16,26.3.18.8,25.8.30.8