Skip to content

Fix access checks in PREWHERE and indexHint() that used aliases - #120516

Merged
vdimir merged 9 commits into
ClickHouse:masterfrom
shankar-iyer:fix_prewhere_alias_access_check
Oct 1, 2026
Merged

vdimir merged 9 commits into
ClickHouse:masterfrom
shankar-iyer:fix_prewhere_alias_access_check

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Enforce column-level SELECT grants for columns that the planner resolves away before the access check runs: ALIAS columns inlined into PREWHERE, and columns used only as indexHint() arguments. User will require the grant on the alias name itself.

Changelog category

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

Changelog entry

Column-level SELECT privileges are now enforced for columns used only inside indexHint and for ALIAS columns referenced in PREWHERE. As in WHERE, referencing an ALIAS column in PREWHERE requires the grant on the alias name; a grant on its source columns is no longer sufficient. A metadata-only ALTER that changes a subcolumn read by a MATERIALIZED column through an ALIAS is now refused like a direct reference.


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

Version info

  • Merged into: 26.10.1.1151-master (included in 26.10 and later)
  • Backported to: 26.9.8.9, 26.8.15.22, 26.7.20.22, 26.3.40.11

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9743109]

Summary: ✅


AI Review

Summary

This PR correctly tightens most of the planner-time SELECT checks for PREWHERE aliases, indexHint() arguments, and the metadata-only named-tuple ALTER guard, but it still leaves one RBAC hole open on ENGINE = Alias and it does not add coverage for one of the new ALTER ... DROP COLUMN side effects. I would not merge it yet.

Findings

❌ Blockers

  • [src/Planner/PlannerJoinTree.cpp:779] [dismissed by author -- https://github.com/Fix access checks in PREWHERE and indexHint() that used aliases #120516#discussion_r4033928284] checkAccessRightsForColumnsResolvedAway still routes ENGINE = Alias through the non-empty checkAccessRights path, and that path only checks the alias table itself. Because StorageAlias::read re-checks only the columns that are actually read, an indexHint() / PREWHERE column that was resolved away before planning still never gets checked on the target table. That means a user who has the alias-table grant plus target grants on the selected/read columns can still use indexHint(secret_alias ...) (and the analogous resolved-away alias cases) as an oracle over a target-table column they are not allowed to SELECT. Suggested fix: make the non-empty checkAccessRights path mirror StorageAlias::filterColumnsGrantedThroughChain, or explicitly re-check the resolved-away column set against the alias target chain.
Tests
  • ⚠️ Add one focused stateless ENGINE = Alias regression that covers the blocker above (for example a count()/indexHint() case and a PREWHERE alias case where the user is granted the alias table plus only the actually read target columns). Right now the surviving hole is untested.
  • ⚠️ Add a dependent-view DROP COLUMN regression for the new collectSelectedColumnsFromTable behavior. This PR now changes ALTER TABLE ... DROP COLUMN semantics when a dependent view mentions a source column only inside indexHint(), via IStorage::getDependentViewsByColumn, but the new tests cover only planning-time access checks and the metadata-only named-tuple ALTER guard.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: fix the unresolved ENGINE = Alias RBAC hole for resolved-away columns, add a regression for that path, and add a focused dependent-view DROP COLUMN test for the new indexHint() dependency tracking.

LLVM Coverage Report

Measured on commit 9743109.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 72/74 (97.30%) · 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 17, 2026
if (column_names.empty())
return;

checkAccessRights(

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.

checkAccessRights() only consults the StorageAlias target table in its empty-column fallback path. For ordinary reads that is masked by StorageAlias::read(), which re-checks the target with the actual column_names, but the whole point of getAccessCheckedColumnsNames() is that these columns never reach column_names.

That leaves the indexHint() half of this fix incomplete on ENGINE = Alias: SELECT pub FROM alias_mt WHERE indexHint(secret_alias >= 500) now passes as soon as the user has SELECT(pub, secret_alias) on alias_mt, even if they have no SELECT(secret_alias) on the target table. The same reference is denied once it is actually read. This helper needs to mirror the StorageAlias target-column check, or checkAccessRights() needs to enforce it for non-empty column lists too. An Alias-engine regression test here would also be useful.

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.

Separate isue

@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9743109d1 with master dc5b03033 (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

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

Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +39.7 s (+8%) in total before that adjustment.

Job report

@Ergus Ergus self-assigned this Sep 22, 2026
Ergus
Ergus previously requested changes Sep 22, 2026
const TableNode & table_node, const TableExpressionData & table_expression_data, const ContextPtr & query_context)
{
const auto & column_names = table_expression_data.getAccessCheckedColumnsNames();
if (column_names.empty())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In spite of this, it routes into the column_names.empty() branch of checkAccessRights so it does not make the helper a no-op. Is that intended??

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.

Intended — empty list means trivial query.

@vdimir vdimir self-assigned this Sep 29, 2026
vdimir and others added 5 commits September 29, 2026 14:22
`expressionSourceColumns` collects with ALIAS columns inlined and read the
selected names, which relied on the children walk after inlining selecting
the source columns. It wants the physical dependencies, so read the
physical column list; that also covers a plain `x ALIAS y`, whose source
was never selected.

Also document why the resolved-away columns are checked separately from
the selected ones.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Record the names PREWHERE references at the PREWHERE site, with the same
traversal the filter access check uses, instead of marking inside the
visitor: the inline mode also serves row policies, additional filters,
the ALTER guards and mutations, where no check is wanted. Keep the
replacement in `enterImpl` and stop the children walk from selecting the
sources of the inlined expression, which the nested visitor has already
collected.

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

@vdimir vdimir left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Pushed four commits on top, keeping your structure:

  1. expressionSourceColumns now returns getColumnNames (physical read list). The selected list lost the sources of inlined aliases, which broke 05076_json_lazy_type_hints_projection_safety; the physical list also covers plain x ALIAS y, which master missed.
  2. PREWHERE names are recorded at the PREWHERE site via collectReferencedColumnNames (shared with the filter access check) instead of inside the visitor, which also serves row policies and the ALTER guards. Inlining stays in enterImpl; the walk into the inlined expression is blocked in needChildVisit, replacing the leaveImpl deferral.
  3. Tests: 05293 (indexHint under JOIN, subquery, PREWHERE) and 05294 (ALTER guard through an ALIAS).

Your 05218 and the existing indexHint, PREWHERE-alias and metadata-only ALTER tests pass unchanged.

Changelog should mention both directions: an ALIAS in PREWHERE now requires the grant on the alias name, as in WHERE; a grant on its source column is no longer enough.

@vdimir
vdimir requested a review from Ergus September 29, 2026 15:07
@vdimir

vdimir commented Sep 29, 2026

Copy link
Copy Markdown
Member

Summary of all behaviour changes in this PR (as of fd835e7), each verified locally against a pre-PR master build.

Access checks

1. PREWHERE over an ALIAS column requires the grant on the alias name, exactly like WHERE.

CREATE TABLE t (secret Int32, pub Int32, secret_alias ALIAS secret, secret_fn ALIAS secret * 2)
ENGINE = MergeTree ORDER BY secret;
user's grant query before after
pub only SELECT pub FROM t PREWHERE secret_alias = 200 returned rows ACCESS_DENIED
pub only SELECT count() FROM t PREWHERE secret_alias = 200 returned count ACCESS_DENIED
pub, secret (source, not alias) SELECT pub FROM t PREWHERE secret_alias = 200 returned rows ACCESS_DENIED
pub, secret (source, not alias) SELECT pub FROM t PREWHERE secret_fn = 400 returned rows ACCESS_DENIED
pub, secret_fn (alias, not source) SELECT pub FROM t PREWHERE secret_fn = 400 ACCESS_DENIED returned rows

Before, a plain alias (a ALIAS secret) in PREWHERE was not access checked at all, and an alias with an expression (a ALIAS secret * 2) required grants on its physical source columns instead of on the alias. Now the grant on the alias name is required and sufficient, and grants on the source columns are neither required nor sufficient. The same WHERE queries behave identically before and after, so the change only aligns PREWHERE with WHERE.

2. Columns used only as indexHint arguments over MergeTree require SELECT.

user's grant query before after
pub only SELECT count() FROM t WHERE pub = 5 AND indexHint(secret < 500) 0 (granule pruned, so secret >= 500 is revealed) ACCESS_DENIED
pub only SELECT count() FROM t WHERE indexHint(secret_alias >= 500) returned count ACCESS_DENIED
pub, secret SELECT count() FROM t WHERE indexHint(secret < 500) returned count unchanged

Applies to WHERE, PREWHERE, subqueries, both JOIN sides, and the pushdown of a view over a Distributed table (which checks grants via collectSelectedColumnsFromTable).

3. Unchanged on purpose: row policies and additional filters may still reference an ALIAS the user cannot read (05218 covers a row policy), and query plans are byte-identical to master (EXPLAIN header = 1, actions = 1 diffed for PREWHERE alias and indexHint queries). The alias source columns are still read from disk to compute the alias; only the grant check moved.

ALTER

4. ALTER TABLE ... DROP COLUMN is refused when a materialized view references the column only inside indexHint.

CREATE TABLE src (k UInt64, c UInt64, v String) ENGINE = MergeTree ORDER BY k;
CREATE MATERIALIZED VIEW mv ENGINE = MergeTree ORDER BY k AS SELECT k, v FROM src WHERE indexHint(c = 1);
ALTER TABLE src DROP COLUMN c;
-- before: succeeds; the next INSERT INTO src fails with UNKNOWN_IDENTIFIER "while pushing to view"
-- after:  ALTER_OF_COLUMN_IS_FORBIDDEN "referenced by materialized view ['mv']"

This is a side effect of collectSelectedColumnsFromTable no longer skipping indexHint arguments; it feeds getDependentViewsByColumn, used by MergeTree, Merge, Null, Buffer and Distributed for DROP COLUMN. The skip only ever applied to MergeTree sources, so other engines already behaved this way. Not covered by a test yet.

5. The metadata-only named-tuple ALTER guard follows a plain ALIAS.

CREATE TABLE g (t Tuple(a Int64), t_alias ALIAS t, m String MATERIALIZED toString(t_alias))
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO g (t) VALUES ((1));
ALTER TABLE g MODIFY COLUMN t Tuple(a Int64, b String) SETTINGS allow_metadata_only_named_tuple_alter = 1;
-- before: succeeds and nothing recomputes m; the row reads back as t = (1,''), m = '(1)'
-- after:  ALTER_OF_COLUMN_IS_FORBIDDEN "subcolumn used by the MATERIALIZED column 'm'"

Same for projection keys and TTL expressions, which go through the same expressionSourceColumns helper. The function-alias case (s ALIAS toString(t), m MATERIALIZED s) was already refused and is unchanged. Covered by 05294.

@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

This PR shows no performance changes on clickbench or tpch_adapted_1_official. The only flagged rows are clickbench Q33 (-5.2%) and Q34 (-6.2%). Both fall inside master's current range and both have flat CPU time, so the lower wall-clock times are variation rather than less work. That fits the diff: it only adds planning-time SELECT-privilege checks for columns used in explicit PREWHERE ALIAS references and indexHint arguments, and shares the column-name collection with the existing filter check. None of this sits on the execution path of ClickBench's GROUP BY queries, which also have no explicit PREWHERE or indexHint. All three source runs (the clickbench run and both TPC-H runs) were on the same node, which makes small speedups like these less trustworthy, but it does not change the result.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f3d50817-6b21-4251-9f4f-2f42885580bd
  • MIRAI run: c81897ce-b73d-4b5b-9757-6b1b593bda59
  • PR check IDs:
    • clickbench_2422964_1790701634
    • clickbench_2422970_1790701634
    • clickbench_2422976_1790701634
    • tpch_adapted_1_official_2422987_1790701634
    • tpch_adapted_1_official_2422998_1790701634
    • tpch_adapted_1_official_2423034_1790701634

if (is_inside_index_hint_function && source_table->getStorage()->isMergeTree())
return;

/// Note that arguments of the "indexHint" function need to be checked for SELECT privilege

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.

collectSelectedColumnsFromTable() also feeds IStorage::getDependentViewsByColumn(), so this change is doing more than the new SELECT-privilege checks: it now makes ALTER TABLE src DROP COLUMN c reject a dependent view that mentions c only inside indexHint(). That looks like the right outcome, but I do not see a regression test for that path in this PR. The new tests cover direct query planning and the metadata-only named-tuple ALTER, not the dependent-view DROP COLUMN guard, so this can regress silently.

@vdimir

vdimir commented Sep 30, 2026

Copy link
Copy Markdown
Member

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
05293_index_hint_column_access FAIL cidb

@groeneai why test failed with parallel replicas? Is it safe just exclude it from this run or there underlying issue or bug?

@groeneai

Copy link
Copy Markdown
Collaborator

It is a pre-existing difference in index analysis between the local and the parallel-replicas path, not an access-check issue, so the tag is safe. It reproduces on master without this PR and without any grants:

CREATE TABLE t (id UInt64, secret UInt64, secret_alias ALIAS secret)
ENGINE = MergeTree ORDER BY secret SETTINGS index_granularity = 1;
INSERT INTO t SELECT number, number * 1000 FROM numbers(10);
SELECT count() FROM t WHERE id = 3 AND indexHint(secret_alias > 5000);
-- 1 locally, 0 with enable_parallel_replicas = 1, parallel_replicas_for_non_replicated_merge_tree = 1

The parallel-replicas shipping paths inline ALIAS columns before building the replica query (1, 2), so the replicas receive indexHint(__table1.secret > 5000) (seen in their query_log) and prune by the primary key. Locally secret_alias stays a column inside the indexHint arguments and index analysis does not see through it: EXPLAIN indexes = 1 shows Condition: true, Granules: 10/10, while the same predicate in plain WHERE gives secret in [5001, +Inf). indexHint only affects which granules are read, so this is a missed optimization in the local path, not a wrong result.

The access checks hold with parallel replicas: in the failing runs every ACCESS_DENIED line matched the reference, only this last line differed. With parallel replicas the grant on the source column is also required (on master, an alias-only grantee is denied until SELECT(secret) is granted), which is the case the 05218 tag comment describes. That is stricter, not a leak: a source-only grantee is denied the alias in both modes.

@vdimir
vdimir enabled auto-merge October 1, 2026 08:41
@vdimir
vdimir added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit 6b93b76 Oct 1, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 1, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 1, 2026
Backport #120516 to 26.9: Fix access checks in PREWHERE and indexHint() that used aliases
clickhouse-gh Bot added a commit that referenced this pull request Oct 1, 2026
Backport #120516 to 26.8: Fix access checks in PREWHERE and indexHint() that used aliases
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 1, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
PedroTadim added a commit that referenced this pull request Oct 2, 2026
Cherry pick #120516 to 26.3: Fix access checks in PREWHERE and indexHint() that used aliases
PedroTadim added a commit that referenced this pull request Oct 2, 2026
Cherry pick #120516 to 26.7: Fix access checks in PREWHERE and indexHint() that used aliases
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #120516 to 26.7: Fix access checks in PREWHERE and indexHint() that used aliases
PedroTadim added a commit that referenced this pull request Oct 2, 2026
Backport #120516 to 26.3: Fix access checks in PREWHERE and indexHint() that used aliases
@rschu1ze

Copy link
Copy Markdown
Member

@shankar-iyer Unfortunately, this PR will need to be backported to 26.2 but there are merge conflicts. Would you resolve them so the fix can land in 26.2? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. 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.

8 participants