Skip to content

Check access rights in EXPLAIN QUERY TREE and EXPLAIN SYNTAX - #110180

Closed
alexey-milovidov wants to merge 92 commits into
masterfrom
fix-explain-query-tree-access
Closed

alexey-milovidov wants to merge 92 commits into
masterfrom
fix-explain-query-tree-access

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #78938

EXPLAIN QUERY TREE and EXPLAIN SYNTAX (in the analyzer) resolve the query and dump table metadata such as column names and types, but unlike EXPLAIN PLAN they do not build a query plan. The SELECT access check that the planner performs in prepareBuildQueryPlanForTableExpression was therefore skipped, so a user with no privileges could read the column names and data types (including Enum element lists) of tables they are not allowed to access, while SELECT, EXPLAIN PLAN and EXPLAIN PIPELINE are correctly rejected.

This adds a SELECT access check for every table referenced anywhere in the query tree (including tables inside subqueries in expressions such as WHERE x IN (SELECT ... FROM t)). The check mirrors the planner: it validates access to the columns that are actually read, with the trivial-count fallback (access is granted if at least one column is accessible) for queries that read no specific column, e.g. SELECT count() FROM t. As a result, a user with a column-level grant sees the same behavior as for a plain SELECT (EXPLAIN QUERY TREE SELECT granted_col FROM t is allowed, ... other_col ... is denied).

buildQueryTree only builds the tree; table identifiers are bound to storages and columns are resolved by the query analysis pass. The check runs on the resolved tree: on query_tree directly when the passes already resolved it, or on a throwaway resolved copy otherwise (e.g. EXPLAIN QUERY TREE run_passes = 0, which intentionally dumps the unresolved tree, so the tree that gets dumped is unchanged).

Changelog category (leave one):

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

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

Fix EXPLAIN QUERY TREE and EXPLAIN SYNTAX not checking access rights on the referenced tables, which allowed a user without privileges to read table column names and data types.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

`EXPLAIN QUERY TREE` and `EXPLAIN SYNTAX` (in the analyzer) resolve the
query and dump table metadata such as column names and types, but unlike
`EXPLAIN PLAN` they do not build a query plan. The `SELECT` access check
that the planner performs in `prepareBuildQueryPlanForTableExpression`
was therefore skipped, so a user with no privileges could read the
column names and data types (including `Enum` element lists) of tables
they are not allowed to access.

Add a `SELECT` access check for every table referenced anywhere in the
query tree. The check mirrors the planner: it validates access to the
columns that are actually read, with the trivial-count fallback (access
is granted if at least one column is accessible) for queries that read
no specific column, e.g. `SELECT count() FROM t`.

`buildQueryTree` only builds the tree; table identifiers are bound to
storages and columns are resolved by the query analysis pass. The check
runs on the resolved tree: on `query_tree` directly when the passes
already resolved it, or on a throwaway resolved copy otherwise (e.g.
`EXPLAIN QUERY TREE run_passes = 0`, which intentionally dumps the
unresolved tree).

Closes: #78938

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [35a1b8f]

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 12, 2026
The `SELECT` access check added for `EXPLAIN QUERY TREE` and `EXPLAIN SYNTAX`
resolved a throwaway copy of the query tree in the branch that dumps the
*unresolved* tree (`EXPLAIN SYNTAX`, `EXPLAIN QUERY TREE run_passes = 0`).
Resolution throws for queries that these statements are specifically designed
to format without resolving - e.g. fuzzed or invalid expressions, a `JOIN`
subquery without an alias (`ALIAS_REQUIRED`), `GROUP BY grouping sets ...
WITH TOTALS` (`NOT_IMPLEMENTED`), or `executable('', ...)` whose arguments the
analyzer intentionally does not evaluate for `EXPLAIN SYNTAX` (`BAD_ARGUMENTS`).
This broke `03773_join_on_formatting`, `03761_inconsistent_ast_formatting`,
`03771_tuple_inconsistent_formatting`, `03601_inconsistent_table_names`,
`01883_with_grouping_sets` and `02377_executable_function_settings` in the
`Fast test`.

The dumped tree in this branch is the unresolved `query_tree`, which never
carries resolved column names or types, so the dump itself cannot leak table
metadata. When resolution of the throwaway copy fails, there is no resolved
metadata to protect and a real query would fail with the same resolution error
before the planner's access check, so we skip the access check instead of
turning a formatting request into a resolution error. An `ACCESS_DENIED`
raised during resolution is still propagated, so `EXPLAIN SYNTAX` of a table
the user cannot read stays denied.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits July 13, 2026 06:18
`checkAccessRightsForQueryTree` collected every `TableNode` in the resolved
query tree and re-checked all of them against the outer `query_context`. That
is wrong for scopes that do not execute under the top-level context: when a
view is inlined (`analyzer_inline_views = 1`), its body is resolved under
`StorageView::getViewSubqueryContext`, and the planner checks the base-table
privileges with that per-scope context (`buildPlannerContext` /
`prepareBuildQueryPlanForTableExpression` use `QueryNode::getContext`).

Flattening every table into one global check made `EXPLAIN QUERY TREE` and
analyzer `EXPLAIN SYNTAX` deny a valid `SELECT ... FROM definer_view` when the
user has `SELECT` on a `SQL SECURITY DEFINER` / `NONE` view but not on its
base tables.

Track the scope context with `InDepthQueryTreeVisitorWithContext` and check
each table with the context of its own scope, reproducing the planner. Columns
are now collected per `TableNode` instance (`collectSelectedColumnsForTableNode`)
so a base table referenced both directly and inside an inlined view is checked
with the correct column set in each scope.

Addresses the AI review on
#110180

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Covers the per-scope access-check fix: a user with SELECT on a
`SQL SECURITY DEFINER` / `NONE` view but not on its base table can still
`EXPLAIN QUERY TREE` / `EXPLAIN SYNTAX` it with `analyzer_inline_views = 1`,
matching what a plain SELECT through the view allows; a user with no access is
still denied. Verified locally against a freshly built server.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI-review Major (per-scope access check for inlined SQL SECURITY DEFINER / NONE views) in db3b852, with test 04539_explain_query_tree_access_definer_view in c4b40b5 — verified locally against a freshly built server. Details in the resolved review thread.

Out of scope, but flagging a pre-existing issue found while testing this: with analyzer_inline_views = 1 a user with no grant on a SQL SECURITY DEFINER view can run a plain SELECT on it and read the data:

-- outsider has NO grant on v_definer, only the definer has SELECT on the base table
SELECT * FROM db.v_definer SETTINGS analyzer_inline_views = 0;  -- ACCESS_DENIED (correct)
SELECT * FROM db.v_definer SETTINGS analyzer_inline_views = 1;  -- returns the data (bypass)

QueryAnalyzer::inlineViewSubqueryIfNeeded checks row policies but never verifies the invoker's SELECT grant on the view before replacing it with its (definer-resolved) body, so the view's own access check is skipped when inlined. This is independent of EXPLAIN — the EXPLAIN access check in this PR faithfully matches the (buggy) SELECT behavior — so I left it alone here. Happy to open a separate issue if useful.

alexey-milovidov and others added 2 commits July 13, 2026 10:09
The `run` helper in `04538_explain_query_tree_access_check.sh` and
`04539_explain_query_tree_access_definer_view.sh` mapped every
non-`ACCESS_DENIED` outcome to `OK`, so a positive case that started
throwing a different exception (e.g. `UNKNOWN_IDENTIFIER`,
`NOT_IMPLEMENTED`) would still pass and the tests would no longer prove
the fix.

Now `OK` is printed only when the client exits with status 0,
`ACCESS_DENIED` only for that specific exception, and any other
exception is emitted verbatim, which makes the reference diff fail. The
expected `OK` / `ACCESS_DENIED` outputs are unchanged, so both reference
files stay valid.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits July 13, 2026 14:19
…atabase tables

The AI review found that `checkAccessRightsForQueryTree` returned early on
`!storage_id.hasDatabase()` before it knew whether the query was a
trivial-count / `SELECT 1` case. The planner's `PlannerJoinTree::checkAccessRights`
guards only the explicit-column branch with `hasDatabase` and always runs the
"at least one accessible column" fallback first, with `ContextAccess` resolving
an empty database name to the current database. As written, `EXPLAIN QUERY TREE`
and analyzer `EXPLAIN SYNTAX` could still succeed for `count()`-style queries on
empty-database `TableNode`s (cross-replication) even when the real `SELECT` would
be denied.

Move the `hasDatabase` guard so it only skips the explicit-column check, and let
the trivial-count fallback run unconditionally, matching the planner. Extend
`04538_explain_query_tree_access_check` to cover the trivial-count path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…XPLAIN SYNTAX

`EXPLAIN SYNTAX` inlines a `SQL SECURITY INVOKER` parameterized view call
`pv(...)` into its inner subquery via `ExpandParameterizedViewsMatcher` before the
query tree is built, so the view object is no longer present in the tree that
`checkAccessRightsForQueryTree` inspects — only the base tables were checked. Real
execution instead turns `pv(...)` into a fake `TableNode` for the view in
`QueryAnalyzer::resolveTableFunction` and checks `SELECT` on it in
`prepareBuildQueryPlanForTableExpression`, so a user with access to the base tables
but no grant on the view could `EXPLAIN SYNTAX SELECT ... FROM pv(...)` even though
the real `SELECT` is denied.

Run the access check on the original (unexpanded) query when a parameterized view
was expanded: there the view still resolves to its own `TableNode`, so its `SELECT`
grant (and its selected columns) are enforced exactly as a real `SELECT` does, while
the base tables inside its body are still checked under the per-scope context. The
check on the expanded dump tree is skipped in that case to avoid a redundant,
incomplete check. Non-parameterized-view queries are unaffected.

Extracted the resolve-then-check logic into `resolveThenCheckAccessRights` shared by
both paths.

Test: `04600_explain_syntax_parameterized_view_access.sh`.
…ews in EXPLAIN

A regular, non-parameterized view that is not inlined (`analyzer_inline_views = 0`,
the default) stays as a single `TableNode` in the query tree, so
`checkAccessRightsForQueryTree` only enforced `SELECT` on the view object and never
re-checked the base tables. Real execution does check them: `StorageView::readImpl`
builds the view's inner query under the view's own context (the definer for
`SQL SECURITY DEFINER`, the invoker otherwise) and checks the base-table privileges
there. As a result a user with `SELECT` on a default `SQL SECURITY INVOKER` view but
not on its base table could `EXPLAIN QUERY TREE` / `EXPLAIN SYNTAX SELECT * FROM v`
and learn the view's projected columns/types even though the actual `SELECT` is denied.

Reproduce the inner access pass: when the check encounters a non-inlined regular view
`TableNode`, build its inner query under `StorageView::getViewSubqueryContext`, resolve
it, and run the access check recursively (which also covers nested views). Parameterized
views are expanded and checked separately; inlined views already expose their base tables
as `TableNode`s, so neither is double-checked.

Test `04601_explain_query_tree_access_invoker_view`.
alexey-milovidov and others added 2 commits July 15, 2026 09:40
…yzer-only

The AI review asked to run the parameterized-view object access check in the
legacy (allow_experimental_analyzer = 0) EXPLAIN SYNTAX fallback as well. That
would over-deny: the old interpreter never requires a SELECT grant on the
parameterized view object — Context::executeTableFunction resolves pv(...)
without any access check and InterpreterSelectQuery skips
checkAccessRightsForSelect for table functions — so a real
SELECT ... FROM pv(...) succeeds with only the base-table grants (verified
against a live server). The legacy fallback already checks the base tables via
InterpreterSelectQuery inside ExplainAnalyzedSyntaxVisitor, which is exactly
what real legacy execution enforces, so EXPLAIN SYNTAX is allowed precisely
when the real SELECT is allowed and denied (without leaking anything) when it
is not.

Add a comment explaining this at the analyzer gate and a legacy-path
regression test 04602_explain_syntax_parameterized_view_access_legacy that
pins the faithfulness contract: base-only user -> real SELECT and
EXPLAIN SYNTAX both allowed; user without grants -> both denied.

Co-Authored-By: Claude Fable 5 <[email protected]>
…s in legacy EXPLAIN SYNTAX

`ExplainAnalyzedSyntaxMatcher` (the `allow_experimental_analyzer = 0` fallback used by
`EXPLAIN SYNTAX`) only checked `SELECT` on the view object itself, via
`checkAccessRightsForSelect` inside `InterpreterSelectQuery::analyze`. A real `SELECT`
through a regular, non-parameterized view goes on to check the base-table privileges
too, but only once the pipeline is actually built, in `StorageView::readImpl` - which
`EXPLAIN SYNTAX` never reaches. So a user with `SELECT` on the view but not on its base
table could `EXPLAIN SYNTAX` the expanded view body (with `allow_experimental_analyzer
= 0`) while the real `SELECT` is denied.

Reproduce that inner check by resolving the view straight from the AST (before it is
rewritten into a subquery) and running the base-table access check on its inner query
under the view's own security context, recursing through nested views the same way the
analyzer path (`checkAccessRightsForQueryTree`) already does for `EXPLAIN QUERY TREE`
and the analyzer's `EXPLAIN SYNTAX`. Factored the shared recursion into
`checkViewBaseTableAccess`, used by both paths.

Test: `04603_explain_syntax_invoker_view_access_legacy.sh`.
…ng registered table functions

A query mixing an ordinary table with a registered table function (a sibling
JOIN or an IN subquery over `mysql(...)`, `url(...)`, ...) made the throwaway
access-check resolution resolve the whole tree, so the table function connected
to the remote server - the side effect this dump-only mode exists to avoid.
The check now stands down whenever the query mentions a registered table
function anywhere (`view` and `viewIfPermitted` resolve locally and are
exempt): analysis cannot resolve one branch in isolation, and skipping is
fail-safe because the unresolved dump reveals nothing beyond the user's own
query text.
…9 and 05042

The helpers classified any body without `DB::Exception` as OK, so a `curl`
transport failure or timeout could keep the regression green: OK now requires
`curl` to exit 0 on top of a clean body, and any other failure prints the exit
code with the full body. The five probes of a shape also run concurrently now:
on a loaded debug-build server one probe can take many seconds, and the serial
35-probe run of 05029 exceeded the time limit in the flaky-check job
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110180&sha=c01038c89b228d35f72f629d93ec06df81a91ba2&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110180&sha=c01038c89b228d35f72f629d93ec06df81a91ba2&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%206%2F8%29 — test_storage_rabbitmq/test.py::test_rabbitmq_queue_consume timed out waiting for any RabbitMQ consumption (labeled retry_ok). CIDB shows the same test failing on unrelated PRs #116050 (2026-08-24), #111032 (2026-08-14) and #114074 (2026-08-12), and this PR touches only the EXPLAIN access checks, so it is not caused here; there is no tracking issue yet. If a fix is already in progress, link it here.

For the record, the Stress test (arm_release) red of the same run (server restart fails on Alias table cannot refer to another Alias table from 04238_storage_alias_missing_target_merge) is already tracked in #116207 with the fix in #116153.

@groeneai

Copy link
Copy Markdown
Collaborator

Not caused by this PR. In CIDB over 30 days test_storage_rabbitmq/test.py::test_rabbitmq_queue_consume has 8 FAIL spread over 6 distinct head branches and 0 on master, against 50402 OK (4324 of those on master). Your three carriers are in that set, and this PR only touches the EXPLAIN access checks.

The root cause is established, and written up at #109722 (comment). Briefly: State::OK means "consume was submitted", not "subscribed". RabbitMQConsumer::onReady calls subscribe and sets state = State::OK on the next line, before any broker frame; onSuccess only logs subscriptions_num and never increments it; needChannelUpdate is exactly state == State::ERROR. An unconfirmed subscription is therefore unobservable and unrecoverable, with no timeout and no re-submission anywhere. In the amd_msan run the basic.consume confirmation arrived after 60.45 s, 1.1 s after the test had given up, with the polled count frozen at exactly 0 for all 264 polls and the single channel generation never recreated. The same job confirmed 226 other subscriptions with a median of 1.90 ms and a second-largest of 23.48 ms, so this is one stuck subscription, not a slow runner.

There is no fix PR yet. I stopped short of one on 2026-08-05 for two reasons, and both have since changed:

  • Safe recovery needs per-generation immutable state for the consumer callbacks, because channel_id is a mutable member that onReceived reads at delivery time, while the destructor's close queues behind the pending basic.consume, so a late delivery is attributed to the new generation. I did not want to restructure the consumer while RabbitMQ related fix #112479 was open in that area. It merged on 2026-08-12.
  • I could not validate a fix against the occurrence: the 60.45 s latency is not diagnosable from the artifacts that are collected (no broker log, no capture), and it did not reproduce in 7 local jam configurations.

Your #115343 settles both for me. It is the same defect class in NATS, a subscription that looks healthy and stays permanently silent, and it fixes it with an explicit predicate (hasConnectionReconnected) over a reconnect counter captured at subscribe time. That is the generation-stamped shape RabbitMQ needs instead of channel replacement, and it also shows the right test: pin the invariant deterministically, with a broker that withholds basic.consume-ok, rather than chasing the latency outlier. I am writing the RabbitMQ fix along those lines and will link it here.

One question, since you note there is no tracking issue: do you want one, or is the fix PR enough? I do not open issues unasked.

For completeness, #116050 in your list is mine, and it is a different RabbitMQ defect (awaiting the consumer channel close before deleting queues on DROP TABLE), not a fix for this one.

@groeneai

Copy link
Copy Markdown
Collaborator

No fix PR. I would rather correct my earlier "I am writing it" than let it stand.

I designed the fix I described, which was to wait for basic.consume-ok during table setup the way bindExchange and bindQueue already wait, and then let the existing init retry rebuild the channel. It does not survive review, for two reasons that are both checkable:

  1. It cannot recover the reported carrier. initRabbitMQ is called from the constructor at StorageRabbitMQ.cpp:273, a throw there is rethrown for CREATE at :281, and init_task is only constructed afterwards at :292. So on CREATE TABLE there is no retry to fall back to, and the fix would turn a table that silently consumes nothing into a CREATE TABLE that fails after 30 seconds. The failing test creates the table that way.

  2. Abandoning the unconfirmed consumer is a use-after-free. The consume callbacks capture this (RabbitMQConsumer.cpp:61, :67, :87), consumers_ref holds only weak_ptr (StorageRabbitMQ.h:129), and ~Channel merely queues close behind the unresolved synchronous basic.consume, so AMQP-CPP keeps the deferred consumer alive and a late basic.consume-ok lands on a freed object.

That closes the routes I can see. Waiting longer is out: the stuck consumer already had 16.15 s of uv_run before its 60.45 s confirmation, against a 1.90 ms median across 226 confirmations in the same job. Re-submitting on the same channel is out, because a second basic.consume queues behind the frame that is stuck. Replacing the channel is out, because onReceived stamps each delivery with the current mutable channel_id, so a delivery from the retired generation is attributed to the new one.

What is left is the change I avoided in August: give the consumer per-generation immutable callback state and retire channels instead of destroying them. That is unblocked now that #112479 has merged. It would also fix a pre-existing bug on the existing error-recovery path, where a stale delivery tag can be acked against the wrong channel generation.

One question, then. Do you want me to make that change in RabbitMQConsumer, or would you rather this stayed a known flaky test? It touches ack correctness, so I would rather ask than surprise you with the diff.

alexey-milovidov and others added 4 commits August 29, 2026 09:17
… the `EXPLAIN` access check

`StorageAlias::read` checks `SELECT` on the target table when the plan is
built, which `EXPLAIN QUERY TREE` / analyzer `EXPLAIN SYNTAX` never reach,
so a user with `SELECT` on the alias object alone could dump the resolved
columns and types while the real `SELECT` is denied. Reproduce the target
check in `checkAccessRightsForQueryTree` through the same `StorageAlias`
helpers `read` and the planner use: `getTargetTable(TargetAccess{...})`
for an explicit column list and `isTargetTableGranted` in the
trivial-count fallback.

Co-Authored-By: Claude Fable 5 <[email protected]>
…yze-only subquery

The analyze-only subquery access check (`check_subquery_table_access`,
used by `InterpreterCreateQuery::getSampleBlock` under the analyzer)
walked `extractAllTableReferences`, which drops `TableFunctionNode`s, so
a parameterized view inside a `FROM` subquery was never checked and
`CREATE VIEW ... AS SELECT * FROM (SELECT * FROM pv(...))` revealed the
view's column names and types without the `SELECT` grant that the same
statement with `pv(...)` as the top-level table expression requires.
Teach `extractAllTableReferences` to optionally return table functions
and enforce the same view-object grant in `checkAccessRightsForSubquery`
as `prepareBuildQueryPlanForTableExpression` does at the top level.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ky-check time limit

On the flaky-check host the CI report shows single trivial HTTP probes
taking 20-47 seconds (even denials that end in `ExceptionBeforeStart`),
because the check runs the changed tests many times at once. One
concurrent wave of five probes per shape still left 7-10 sequential
waves, which exceeded the 180 s limit:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110180&sha=0267434c51e2222aff4c6212a022c95768b4ad80&name_0=PR&name_1=Stateless%20tests%20(amd_binary%2C%20flaky%20check)
Launch all probes of all shapes at once and assemble the ordered output
afterwards, so the wall time is bounded by the slowest single probe.

Co-Authored-By: Claude Fable 5 <[email protected]>
`StorageAlias::read` checks the `SELECT` grant on the table an `Alias` points at when the plan is
built. The legacy (`allow_experimental_analyzer = 0`) `EXPLAIN SYNTAX` and `EXPLAIN AST optimize = 1`
paths run `InterpreterSelectQuery` in `analyze()` mode only and never get there, and
`InterpreterSelectQuery::checkAccessRightsForSelect` only verifies the alias object itself - so a user
with `SELECT` on the alias but not on its target could format the rewritten query (with `*` expanded
into the target's column names) even though the real `SELECT` is denied. The analyzer path already
reproduced this check; the legacy path did not.

`checkAccessEnforcedAtReadTime` (previously `checkNonParameterizedViewBaseTableAccess`, renamed
because it is no longer view-only) now also enforces the target-table grant for an `Alias` table, with
the same per-table-expression column set the storage would be read with, and
`referencesTableCheckedAtReadTime` admits alias tables so nested subqueries are covered too.

Test `05050_explain_syntax_alias_target_table_access_legacy` is the legacy counterpart of
`05048_explain_query_tree_alias_target_table_access`: for three grant states it checks that
`EXPLAIN SYNTAX` and `EXPLAIN AST optimize = 1` are allowed exactly where the real `SELECT` is, for an
explicit column, `SELECT *`, `count()`, and an `IN` subquery.
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too.

alexey-milovidov and others added 3 commits September 3, 2026 15:01
…s in the analyze-only planner

`InterpreterCreateQuery::getSampleBlock` analyzes the `SELECT` of `CREATE ... AS SELECT` without planning
subqueries or reading any storage, so the checks a real read performs only when the plan is built never ran
for it: `StorageView::readImpl` checks `SELECT` on the base tables of a `SQL SECURITY INVOKER` view, and
`StorageAlias::read` checks the target table of an `Alias`. A user with `SELECT` on the view or alias object
but not on the underlying table could `CREATE VIEW dst AS SELECT * FROM v_invoker` or
`... FROM (SELECT * FROM alias_t)` and learn the column names and types of a query whose real `SELECT` is
denied. The subquery helper also checked parameterized views and plain tables at table granularity only,
so a column-level grant that lets `SELECT y FROM pv(n = 1)` run was rejected inside a subquery.

Move the `EXPLAIN QUERY TREE` / `EXPLAIN SYNTAX` access helpers (`checkAccessRightsForQueryTree`,
`checkViewBaseTableAccess`, `resolveThenCheckAccessRights`) out of `InterpreterExplainQuery` into the shared
`Planner/checkAccessRightsForQueryTree` unit, and add `checkReadTimeAccessForTableExpression` for the
per-table follow-up (the `Alias` target check and the recursive view base-table pass). The planner's
`checkAccessRightsForSubquery` now runs `checkAccessRightsForQueryTree` on the subquery, which gives it the
column-aware per-table `SELECT` check of `prepareBuildQueryPlanForTableExpression` plus the view and `Alias`
follow-ups, and the top-level table expression under `only_analyze` with `check_subquery_table_access`
gets the same follow-up, since the identical leak existed for the view or alias as the table expression
itself. In the planner a view whose inner query cannot be resolved propagates that resolution error, as a
real read of it would, instead of skipping the check as the `EXPLAIN` fallback does.

The `include_table_functions` parameter of `extractAllTableReferences` is no longer needed and is reverted.

Test `05060_create_view_analyze_only_view_alias_read_time_access` pairs every shape (the real `SELECT`,
`CREATE VIEW` over the view or alias directly, in a subquery, and as `count()`) for an `INVOKER` view, an
`Alias`, a `DEFINER` view over-denial control, column-level base grants, and full grants.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…side an analyze-only subquery

Extend `05049_create_view_subquery_parameterized_view_access` with `GRANT SELECT(y) ON pv`: the granted
column must be allowed both as the top-level table expression and inside a `FROM` subquery, matching the
real `SELECT`, while the ungranted column and `SELECT *` stay denied in every shape.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate these job-level infra failures on d9a375f (none touches this PR's code; the fresh run on 35a1b8f reruns them) and provide a fix in a separate PR, or link it here if one is already in progress:

The fourth red, 03707_autopr_unsupported_cases in the old-analyzer stateless job, is the master-wide 2026-08-31 breakage fixed by #117364; this branch now has it through the master merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

This is very bad. Instead of duplicating the access check in such a wrong way, we should:

  • avoid showing column names in error messages if the user does not have the privilege to show columns;
  • check access in EXPLAIN QUERY TREE at the moment this query actually obtains the information that requires access.

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Answering per red.

1. AST fuzzer (amd_release, oracle). The boto3 line is not what failed this job. run-fuzzer.sh:93 runs logs_export_config under || echo "Failed to create log export config", and the log takes exactly that fallback, then proceeds to + fuzz and runs 18m29s. The red is the fuzzer's own verdict:

ERROR: AST fuzzer oracle mismatch
Reference query:   SELECT count() FROM tab3_mid__fuzz_1 STREAM BOUNDED CURSOR {'all': {'block_number': 10}}
Metamorphic query: SELECT countMerge(_s_0) FROM (... countState() ... WHERE coalesce(a, b, c) = 142
                   UNION ALL ... not(...) UNION ALL ... isNull(...))

That is the defect in #117188 (mine, open since 2026-08-30): the implicit min-max/count projection answers a bare count() from part metadata, so a streaming read reports the whole-table count and ignores the CURSOR bound, while the three countState() branches carry a WHERE and therefore honour it. count() is wrong, countIf(1) is correct. You asked me to investigate the same oracle class on #112968 and that PR is the result.

The boto3 failure is real but separate, and non-fatal: ci/praktika/secret.py now fetches SSM only through boto3 with no AWS CLI path left, while ci/docker/fuzzer installs awscli and not boto3. So log export is silently unconfigured on every AST fuzzer run. No PR owns that; a fix task is created and I will post the fixing-PR link here.

2. Bugfix validation, Could not find master builds in S3. Fixed by #117580 (fm4v, merged 2026-09-01T22:06:23Z), which repaired the master-build lookup for the new S3 prefix scheme. The new_tests_check.py drop in Finish Workflow is the same root cause, so one fix covers both.

3. Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6), Container memory budget exceeded (/docker). Two merged fixes: yours, #117412 (merged 2026-09-01T11:31:33Z), and #117564 (mine, merged 2026-09-03T13:07:47Z), which stopped three integration modules from holding their clusters open until session end. After #117412 the row was confined to 6/6 alone, which is the shard #117564 targets.

4. Agreed on 03707_autopr_unsupported_cases and #117364.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

The fix is up as #117996. It covers both defects on that path: clickhouse/fuzzer never carried
boto3, which is the traceback you saw, and separately the credentials do not survive the
two-process split between logs_export_config and logs_export_start, so the start step exited 0
having configured nothing. That second half was quietly costing the stress jobs their logs too.

The red on that job is unrelated to either, it is the AST fuzzer oracle mismatch tracked in #117188.

PedroTadim pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Sep 4, 2026
`EXPLAIN QUERY TREE` and `EXPLAIN SYNTAX` resolve the query and dump table
metadata (column names and types) without building a query plan, so the
`SELECT` access check the planner performs when the table is read was never
reached, and a user with no privileges could see the structure of any table.

Check access at the moment the analyzer obtains the table metadata, in
`IdentifierResolver::tryResolveTableIdentifierFromDatabaseCatalog`: the user
must be allowed to see at least one column of the table. Any grant on a column
implies `SHOW_COLUMNS` on it, so the check is weaker than every check the
planner performs later for the columns the query actually reads, and a query
that can be executed can always be analyzed. Table expressions constructed
programmatically (e.g. by `MutationsInterpreter`) do not pass through the
identifier resolution and keep their own access semantics.

A simpler reimplementation of ClickHouse#110180, as requested in
ClickHouse#110180 (comment)

Closes ClickHouse#78938

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Potential Issue: EXPLAIN QUERY TREE statement does not check permissions on the table

3 participants