Skip to content

Check table access when the analyzer resolves a table identifier - #117979

Merged
alexey-milovidov merged 2 commits into
masterfrom
explain-access-check-analyzer
Sep 4, 2026
Merged

alexey-milovidov merged 2 commits into
masterfrom
explain-access-check-analyzer

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Closes: #78938
Related: #110180
Related: #91067

EXPLAIN QUERY TREE and EXPLAIN SYNTAX run_query_tree_passes = 1 resolve the query and dump table metadata (column names and types), but do not build a query plan, so the SELECT access check the planner performs when a table is read was never reached, and a user with no privileges could see the structure of any table.

A simpler reimplementation of #110180, which duplicated the planner's access checks in InterpreterExplainQuery and grew unmanageable, as requested in #110180 (comment). Of the two things requested there, hiding column names from the error messages was already done by #91067, and this change covers the second one: the access check happens at the moment the query actually obtains the information that requires access — when the analyzer resolves a table identifier through the database catalog (IdentifierResolver::tryResolveTableIdentifierFromDatabaseCatalog) and binds the table's metadata into the query tree. The user must be allowed to see at least one column of the table; otherwise the resolution fails through the standard Context::checkAccess, which produces the same sanitized it's necessary to have the grant SELECT ON db.table message a plain SELECT produces and populates missing_privileges of the query log — now without naming columns the user may not see (the raw column list leaked there before).

Any grant on a column implies SHOW_COLUMNS on it, so the new check is weaker than every check the planner performs later for the columns the query actually reads: a query that can be executed can always be analyzed, and no executable query changes behavior. Table expressions constructed programmatically (MutationsInterpreter, StorageMerge, the materialized-view push path, query-plan deserialization) do not go through identifier resolution and keep their access semantics. Views work naturally: the view object itself is resolved through the catalog and checked, and when a view is inlined its base tables resolve under the view's SQL SECURITY context.

Verified by comparing an access-focused behavior matrix (mutations by ALTER-only users, materialized view chains by INSERT-only users, Merge tables, joinGet, parameterized views, SQL SECURITY DEFINER/INVOKER views, partial column grants, trivial count(), row policies, system tables) between a master build and this branch: the only differences are the intended ones. Besides the EXPLAIN leak, the check also closes two smaller metadata oracles for users with no access to a table: the error kind no longer reveals whether a column exists (UNKNOWN_IDENTIFIER vs ACCESS_DENIED), and joinGet with a mismatched key type no longer reveals the key type (TYPE_MISMATCH before the access check).

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 exposing column names and types of tables the user has no privileges for: the analyzer now checks that the user may see at least one column of the table at the moment a table identifier is resolved. The check also makes the error kind independent of whether the queried column exists and stops recording column names the user may not see into missing_privileges of the query log. Closes #78938.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.9.1.687 (included in 26.9 and later)
  • Backported to: 26.8.3.33, 26.7.7.29, 26.6.5.53, 26.3.32.9

alexey-milovidov and others added 2 commits September 3, 2026 19:25
`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 #110180, as requested in
#110180 (comment)

Closes #78938

Co-Authored-By: Claude Fable 5 <[email protected]>
Probe the visibility of the table's columns on the raw access rights, so the
probing does not pollute `used_privileges` of the query log, and `SELECT` is
checked in addition to `SHOW_COLUMNS` because the implicit `SELECT` on the
`system` and `information_schema` databases is granted after implications are
derived. When not a single column is visible, report the denial through the
standard `Context::checkAccess`: the user gets the same sanitized message a
plain `SELECT` produces (`grant SELECT ON db.table`, no column names), and
`missing_privileges` of the query log is populated - without naming columns
the user may not see (they leaked there before).

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [09a5315]

Summary: ✅


AI Review

Summary

This PR moves the table-metadata visibility check into analyzer-time identifier resolution so EXPLAIN QUERY TREE / EXPLAIN SYNTAX run_query_tree_passes = 1 stop dumping schemas for inaccessible tables, and it updates the access-rights tests around that behavior. The main leak for plain table identifiers is addressed, but two access-control completeness gaps remain, so the change is not ready to merge as-is.

Findings

❌ Blockers

  • [src/Analyzer/Resolve/IdentifierResolver.cpp:405] The new metadata gate treats every TableNode as if its schema belonged only to storage_id, but ENGINE = Alias exposes the target table's schema through StorageAlias::getInMemoryMetadataPtr. Existing metadata surfaces already require target visibility as well (InterpreterDescribeQuery.cpp, hasColumnInTable.cpp, 05055_has_column_in_table_alias_access_check.sh). As written, a user with SHOW COLUMNS or SELECT on the alias name but none on the target can still use EXPLAIN QUERY TREE to dump the target schema.
    Suggested fix: if the resolved storage is an Alias, require visibility on the target metadata too, reusing the same target-grant logic the existing alias metadata checks already use.

  • [src/Analyzer/Resolve/IdentifierResolver.cpp:420] The new guard only covers table names carried as unresolved identifiers. joinGet can still reach StorageJoin::joinGetCheckAndGetReturnType through the documented const-string form (or any expression that resolves to a const string) before FunctionJoinGet::prepare finally checks SELECT. That means joinGet('db.join_table', 'secret', bad_key) still discloses TYPE_MISMATCH / NO_SUCH_COLUMN_IN_TABLE to a user with no access, so the PR's claimed joinGet oracle closure is incomplete.
    Suggested fix: move the pre-typecheck access validation into the const-string joinGet path (FunctionJoinGet::getJoin / buildImpl) or route that carrier through the same checked resolver before calling joinGetCheckAndGetReturnType.

Tests
  • ⚠️ Add focused negative coverage for EXPLAIN QUERY TREE / EXPLAIN SYNTAX run_query_tree_passes = 1 on an Alias table with grants only on the alias, and for joinGet('db.join_table', ...) with no SELECT plus a mismatched key or missing attribute. The new test only covers plain tables and views, so these two carriers are currently unproven.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Close the Alias metadata bypass so analyzer-time schema visibility matches the existing alias metadata surfaces.
  2. Close the remaining joinGet const-string carrier before joinGetCheckAndGetReturnType runs.
  3. Add focused regression coverage for both paths.

LLVM Coverage Report

Measured on commit 09a5315.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 15/16 (93.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 4, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good.

@alexey-milovidov alexey-milovidov self-assigned this Sep 4, 2026
const auto access_rights = context->getAccess()->getAccessRightsWithImplicit();
for (const auto & column : table_node.getStorageSnapshot()->metadata->getColumns())
{
if (access_rights->isGranted(AccessType::SELECT, storage_id.database_name, storage_id.table_name, column.name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TableNode metadata is not always about storage_id itself. For ENGINE = Alias, getStorageSnapshot()->metadata comes from the target table (StorageAlias::getInMemoryMetadataPtr), and the existing metadata surfaces already treat that as protected by the target grant too (InterpreterDescribeQuery.cpp:255-257, hasColumnInTable.cpp:109-117, 05055_has_column_in_table_alias_access_check.sh).

With this loop, a user who has SHOW COLUMNS or SELECT on the alias name but none on the target now passes the new guard and EXPLAIN QUERY TREE can dump the target schema again. The metadata-visibility check needs to mirror the alias-target check as well, not only the outer table name.

{
if (auto result = tryResolveTableIdentifier(table_identifier, context))
{
checkAccessToTableMetadata(*result, context);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only closes the IdentifierNode carrier. joinGet can still name the StorageJoin through the documented const-string form (or a WITH alias that resolves to one), and that path never calls tryResolveTableIdentifierFromDatabaseCatalog: FunctionJoinGet::buildImpl resolves the table in getJoin and calls joinGetCheckAndGetReturnType before prepare finally does checkAccess (FunctionJoinGet.cpp:149-205).

So joinGet('db.join_table', 'secret', bad_key) can still leak TYPE_MISMATCH or NO_SUCH_COLUMN_IN_TABLE to a user with no SELECT. The pre-typecheck guard needs to live in the joinGet const-string path as well, not only in identifier resolution.

@zlareb1

zlareb1 commented Sep 4, 2026

Copy link
Copy Markdown
Member

One sibling gap the resolution-site check structurally misses, and one description inaccuracy.

Parameterized views bypass the new check entirely, because they never go through tryResolveTableIdentifierFromDatabaseCatalog: pv(p = ...) resolves through QueryAnalyzer::resolveTableFunction into Context::buildParameterizedViewStorage, which does DatabaseCatalog::tryGetTable with no access check, computes the sample block under the view's getSQLSecurityOverriddenContext, and binds the columns into the TableFunctionNode. The only access check for parameterized views today is the plan-time special case in PlannerJoinTree.cpp — which EXPLAIN QUERY TREE never reaches, exactly like the table case this PR fixes. Verified on a current master build: a user with zero grants gets ACCESS_DENIED for SELECT on the table, an ordinary view, and the parameterized view, but EXPLAIN QUERY TREE SELECT * FROM db.pv(p = 1) over a SQL SECURITY DEFINER parameterized view succeeds and prints the view's inner column names and result types. This PR closes the table and ordinary-view legs of #78938 but leaves this leg open; extending buildParameterizedViewStorage with the same at-least-one-column check on the view (before computing the sample block) would close it in the same spirit — the check runs "at the moment the metadata is obtained".

The description inaccuracy: "the materialized-view push path does not go through identifier resolution" is not quite right. The MV push analyzes the select query with the passes, and replaceStorageInQueryTree runs after them, so the source table is catalog-resolved and the new check does fire on that path — under the SQL-security-overridden select context. It is harmless today only because the planner-time checkAccessRights already runs unconditionally on that path (SelectQueryOptions::ignore_access_check is honored only by the old interpreter), and the new check is strictly weaker than the planner's. Worth a note in the description, plus a tripwire for the future: if ignore_access_check is ever wired into the Planner, the resolution-time check added here would silently remain as the blocking check on the MV push path.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 09a531585 with master d57d35266 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 11 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 4, 2026
Merged via the queue into master with commit 4a01f41 Sep 4, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the explain-access-check-analyzer branch September 4, 2026 11:14
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 4, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 4, 2026
Backport #117979 to 26.8: Check table access when the analyzer resolves a table identifier
robot-clickhouse-ci-1 added a commit that referenced this pull request Sep 4, 2026
Cherry pick #117979 to 26.6: Check table access when the analyzer resolves a table identifier
robot-clickhouse added a commit that referenced this pull request Sep 4, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 4, 2026
Cherry pick #117979 to 26.7: Check table access when the analyzer resolves a table identifier
robot-clickhouse added a commit that referenced this pull request Sep 4, 2026
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
Resolve the conflict in `04510_select_access_rights_rewrite.lib`: the file does not exist on 26.3
(its test was never backported), so the hunk from #117979 touching it is dropped. All other hunks
of #117979 apply cleanly; the APIs used (`getAccessRightsWithImplicit`, `TableNode::getStorageSnapshot`,
`Context::checkAccess` with `StorageID`) exist on 26.3.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
robot-clickhouse added a commit that referenced this pull request Sep 5, 2026
Cherry pick #117979 to 26.3: Check table access when the analyzer resolves a table identifier
robot-clickhouse added a commit that referenced this pull request Sep 5, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 5, 2026
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
…access check

On master this integration test was already rewritten as the functional
`04510_select_access_rights_rewrite.lib`, which #117979 updated, so the
backport had nothing to change there. On 26.7 the integration test still
exists and expected the column-level message
`SELECT for at least one column` for `SELECT count() FROM table1` without
any grant. With the analyzer checking table access while resolving the
identifier, the error is now `SELECT ON default.table1`, exactly as the
master test expects. Pin `enable_analyzer=1` for these assertions so the
result does not depend on the analyzer mode of the CI job.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=118179&sha=b7bfce27db5ca4f47c17b1768587ef9de2ec3715&name_0=BackportPR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%202%2F6%29
PR: #118179
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
…access check

On master this integration test was already rewritten as the functional
`04510_select_access_rights_rewrite.lib`, which #117979 updated, so the
backport had nothing to change there. On 26.6 the integration test still
exists and expected the column-level message
`SELECT for at least one column` for `SELECT count() FROM table1` without
any grant. With the analyzer checking table access while resolving the
identifier, the error is now `SELECT ON default.table1`, exactly as the
master test expects. Pin `enable_analyzer=1` for these assertions so the
result does not depend on the analyzer mode of the CI job.

Same fix as c7d1f4b in the 26.7 backport (#118179).

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=118169&sha=2bc6581ff7d9eb1d276ec947c28162e4108455c4&name_0=BackportPR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%203%2F6%29
PR: #118169
clickhouse-gh Bot added a commit that referenced this pull request Sep 5, 2026
Backport #117979 to 26.7: Check table access when the analyzer resolves a table identifier
clickhouse-gh Bot added a commit that referenced this pull request Sep 5, 2026
Backport #117979 to 26.6: Check table access when the analyzer resolves a table identifier
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
…access check

On master this integration test was already rewritten as the functional
`04510_select_access_rights_rewrite.lib`, which #117979 updated, so the
backport had nothing to change there. On 26.7 the integration test still
exists and expected the column-level message
`SELECT for at least one column` for `SELECT count() FROM table1` without
any grant. With the analyzer checking table access while resolving the
identifier, the error is now `SELECT ON default.table1`, exactly as the
master test expects. Pin `enable_analyzer=1` for these assertions so the
result does not depend on the analyzer mode of the CI job.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=118179&sha=b7bfce27db5ca4f47c17b1768587ef9de2ec3715&name_0=BackportPR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%202%2F6%29
PR: #118179
(cherry picked from commit c7d1f4b)
alexey-milovidov added a commit that referenced this pull request Sep 5, 2026
Backport #117979 to 26.3: Check table access when the analyzer resolves a table identifier
fm4v added a commit to BoloniniD/ClickHouse that referenced this pull request Sep 26, 2026
…tries`

Since ClickHouse#117979 the analyzer denies a query unless at least one top-level column of the table is visible to the user, so the cases granting only a subcolumn name were denied before the column check ran. Grant `id` in every case so the test exercises the subcolumn semantics.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=103402&sha=85c65e7a00a91cce1f2603c5ece735522f15342b&name_0=PR&name_1=Fast%20test
fm4v added a commit to BoloniniD/ClickHouse that referenced this pull request Sep 27, 2026
`checkAccessToTableMetadata` (from ClickHouse#117979) denies a query unless the user may see at least one top-level column of the table. A user whose only grant is on the exact name of a subcolumn, such as ``GRANT SELECT(`json.a`)``, was therefore denied before the `SELECT` check that honors that grant ran.

Also accept the table when a column `c` has an explicit grant of `SELECT` or `SHOW_COLUMNS` on some name starting with `c.`, found by the new `AccessRights::hasExplicitGrantOnColumnsWithPrefix`. A grant counts only where it gives flags that the name does not inherit, consistent with `ColumnsDescription::getColumnNamesForSelectAccessCheck`, so a table grant with every column revoked still hides the table.

Remove the `SELECT(id)` workaround from `05257_grant_select_subcolumn_explicit_entries` and add a case without grants.

Addresses review: ClickHouse#103402 (comment)
cherepasshka pushed a commit to cherepasshka/ClickHouse that referenced this pull request Nov 6, 2026
A parameterized view call is resolved as a table function, so the
metadata check that ClickHouse#117979 added to table identifier resolution never
runs for it. A user with no grant on a SQL SECURITY DEFINER
parameterized view therefore got its column names and types from
EXPLAIN QUERY TREE and EXPLAIN SYNTAX run_query_tree_passes = 1, and
every user got errors that named the view's parameters, its columns
(UNKNOWN_IDENTIFIER vs ACCESS_DENIED) or, for an INVOKER view, the
tables behind it, because the parameters are substituted and the body
is analyzed before anything checks the view.

Check the view where each piece of information is obtained:
- Context::buildParameterizedViewStorage: without implicit SHOW TABLES
  on the view (which any grant on the view or on one of its columns
  implies), report the standard SELECT denial before substituting the
  parameters or analyzing the body.
- QueryAnalyzer::resolveTableFunction: once the columns are known, run
  the ClickHouse#117979 check (at least one column must be visible). The helper
  becomes a public static member of IdentifierResolver; the
  temporary-table exemption moves to its identifier-resolution caller.

Executing a call needs SELECT on at least one of its columns, which
passes both checks, so no executable query changes.

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

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

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

4 participants