Repository navigation
Check access rights in EXPLAIN QUERY TREE and EXPLAIN SYNTAX - #110180
alexey-milovidov wants to merge 92 commits into
Conversation
`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]>
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]>
`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.
|
Addressed the AI-review Major (per-scope access check for inlined Out of scope, but flagging a pre-existing issue found while testing this: with
|
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]>
…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`.
…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).
|
🕵 @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 — For the record, the |
|
Not caused by this PR. In CIDB over 30 days The root cause is established, and written up at #109722 (comment). Briefly: There is no fix PR yet. I stopped short of one on 2026-08-05 for two reasons, and both have since changed:
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 ( 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 |
|
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
That closes the routes I can see. Waiting longer is out: the stuck consumer already had 16.15 s of 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 |
… 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.
|
@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too. |
…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]>
|
🕵 @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, |
|
This is very bad. Instead of duplicating the access check in such a wrong way, we should:
|
|
Answering per red. 1. AST fuzzer (amd_release, oracle). The That is the defect in #117188 (mine, open since 2026-08-30): the implicit min-max/count projection answers a bare The 2. Bugfix validation, 3. Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6), 4. Agreed on |
|
The fix is up as #117996. It covers both defects on that path: The red on that job is unrelated to either, it is the AST fuzzer oracle mismatch tracked in #117188. |
`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]>
Closes: #78938
EXPLAIN QUERY TREEandEXPLAIN SYNTAX(in the analyzer) resolve the query and dump table metadata such as column names and types, but unlikeEXPLAIN PLANthey do not build a query plan. TheSELECTaccess check that the planner performs inprepareBuildQueryPlanForTableExpressionwas therefore skipped, so a user with no privileges could read the column names and data types (includingEnumelement lists) of tables they are not allowed to access, whileSELECT,EXPLAIN PLANandEXPLAIN PIPELINEare correctly rejected.This adds a
SELECTaccess check for every table referenced anywhere in the query tree (including tables inside subqueries in expressions such asWHERE 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 plainSELECT(EXPLAIN QUERY TREE SELECT granted_col FROM tis allowed,... other_col ...is denied).buildQueryTreeonly 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: onquery_treedirectly 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
EXPLAIN QUERY TREEandEXPLAIN SYNTAXnot 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
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/110180]