Skip to content

Check ALTER TABLE ... MODIFY QUERY bodies the same way as CREATE - #123063

Draft
CheSema wants to merge 4 commits into
masterfrom
alter-modify-query-body-checks
Draft

CheSema wants to merge 4 commits into
masterfrom
alter-modify-query-body-checks

Conversation

@CheSema

@CheSema CheSema commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

ALTER TABLE <view> MODIFY QUERY checked its new body less strictly than CREATE ... VIEW does:

  • tables read only inside a subquery, CTE, join operand or UNION leg were not checked against the user. Since Check table access when the analyzer resolves a table identifier #117979 a table with no visible column is refused anyway, but with a grant on some columns the body could still read the others;
  • the subquery check refused a valid column grant one level deeper than it is accepted, on the CREATE path as well;
  • ON CLUSTER and Replicated databases skipped the body check completely, because the hosts and replicas apply the entry without the user. The initiator now applies every MODIFY QUERY of the statement to a copy of the view's metadata, as the user and in the view's database, before it dispatches or enqueues the entry.

Related: #121629

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

ALTER TABLE ... MODIFY QUERY now checks the new body the same way CREATE ... VIEW does: SELECT on every table it reads, including inside subqueries, also with ON CLUSTER and in a Replicated database. A column grant is no longer refused when the column is read inside a subquery.

🤖 Generated with Claude Code


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

The new body of `ALTER TABLE ... MODIFY QUERY` is now checked against the
user for every table it reads, including inside subqueries, and also on an
`ON CLUSTER` initiator and before a `Replicated` database enqueues the entry,
where the hosts and replicas apply it without the user. The subquery check no
longer refuses a valid column grant, which affected `CREATE` as well.
CheSema added a commit that referenced this pull request Sep 30, 2026
…equest

This pull request keeps only the SQL security gate. The body checks that
match `CREATE` move to #123063.
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [46a07dc]

Summary: ✅


AI Review

Summary

This PR tightens ALTER TABLE ... MODIFY QUERY so it revalidates the new view body like CREATE ... VIEW does, including nested subqueries and replicated execution paths. The direction is correct, but the current head still leaves one cloud-only authorization bypass in place, still regresses valid non-local ON CLUSTER alters, and still over-checks one alias-grant case inside parameterized-view subqueries.

Findings

❌ Blockers

  • src/Interpreters/InterpreterAlterQuery.cpp:525-527 / src/Storages/AlterCommands.cpp:1270-1279 MODIFY QUERY still bypasses the new author-side body check on the shared-catalog path. InterpreterAlterQuery forwards straight to SharedDatabaseCatalog::tryExecuteDDLQuery, while secondary apply in AlterCommand::apply returns before getSampleBlock, so in CLICKHOUSE_CLOUD the initiator can still persist a view body it cannot SELECT.
    Suggested fix: run checkAccessForModifyQuery before tryExecuteDDLQuery, or otherwise guarantee that the initial shared-catalog execution performs the same author-context analysis as the replicated and ON CLUSTER paths.

⚠️ Majors

  • src/Interpreters/InterpreterAlterQuery.cpp:498-499 / src/Interpreters/InterpreterAlterQuery.cpp:673-675 The new initiator-side check turns valid non-local ALTER ... ON CLUSTER into UNKNOWN_TABLE. tryResolveStorageID keeps the explicit db.table name even when that database exists only on remote cluster nodes, so table_id stays non-empty while table is null locally; checkAccessForModifyQuery now throws instead of forwarding the DDL. That regresses the existing supported dispatcher path for cluster-local objects that are absent on the initiator.
    Suggested fix: skip the new local body re-analysis when the target storage is intentionally non-local, and preserve the previous forwarding behavior for that ON CLUSTER case.

  • src/Planner/PlannerJoinTree.cpp:408-409 The new subquery collector still descends into alias expressions for parameterized-view TableFunctionNodes. Everywhere else, alias columns from non-join sources are treated uniformly, but here only TableNode aliases short-circuit. As a result, a valid grant on an alias exposed by a parameterized view can still be rejected inside a nested subquery because the walk reaches the underlying source columns instead of stopping at the alias name.
    Suggested fix: short-circuit TableFunctionNode aliases too, or reuse the existing alias-column predicate from CollectTableExpressionData.

Tests
  • ⚠️ The new stateless coverage exercises direct table alias grants and parameterized views separately, but it still misses alias-column grants through parameterized-view subqueries, which is the new planner gap above.
  • ⚠️ The cloud-only shared-catalog routing path has no regression coverage in this PR, so the remaining authorization bypass is not exercised anywhere here.
Final Verdict

Request changes.

LLVM Coverage Report

Measured on commit 46a07dc.

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: 63/66 (95.45%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Sep 30, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
A `SQL SECURITY DEFINER` parameterized view nested in a subquery skipped the
`SELECT` check on the view itself, on the `CREATE` path as well.
/// The hosts run the entry without the user, unless `distributed_ddl_use_initial_user_and_roles` is on,
/// so the new body is authorized here.
if (modify_query)
checkAccessForModifyQuery(table, table_id);

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 initiator-side check now makes ALTER ... ON CLUSTER depend on having the target view locally. Context::tryResolveStorageID keeps table_id non-empty even when the specified database exists only on cluster peers, so table can still be null on a valid dispatcher node. In that case checkAccessForModifyQuery falls into the new UNKNOWN_TABLE throw at 673-675 instead of forwarding the DDL, which regresses the supported non-local ON CLUSTER path. Please preserve that path here instead of unconditionally requiring a local StoragePtr.

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 intended. With the default distributed_ddl_use_initial_user_and_roles = 0 the hosts apply the entry without the user, so the initiator is the only place where the body can be checked, and that needs the view's metadata. A node without the view usually lacks the source tables as well, which the check needs anyway. Each worker reads that setting from its own server settings, so its value on the initiator cannot relax the check either. The statement works when it runs on a host that has the view.

{
/// Every replica, this one included, applies the entry without the user.
if (modify_query)
checkAccessForModifyQuery(table, table_id);

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.

MODIFY QUERY still skips the same authorization on the shared-catalog path. The new DatabaseReplicated branch calls checkAccessForModifyQuery, but SharedDatabaseCatalog::shouldReplicateQuery at 525-527 forwards immediately, while AlterCommand::apply on shared-catalog secondaries explicitly returns before getSampleBlock / access analysis (AlterCommands.cpp:1266-1270). So in CLICKHOUSE_CLOUD the initiator can still persist a body it cannot SELECT, which is the same privilege hole this PR is fixing for ON CLUSTER and Replicated. The same pre-check needs to run before tryExecuteDDLQuery.

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.

On the shared-catalog path the initiator executes the statement again as the user, and that execution counts as the initial query. So the early return in AlterCommand::apply does not apply there, and the body is analysed with checkSubqueryTableAccess against the user. Only the secondaries skip the analysis, and they apply what the initiator has already authorized.

The subquery check also walked the expression of an `ALIAS` column, so a
grant on the alias alone was refused one level deeper than at the top level.
result[column_source.get()].insert(column_node->getColumnName());

/// A grant on an `ALIAS` column is enough to read it, as at the top level, so its expression is not walked.
if (column_node->hasExpression() && column_source && column_source->as<TableNode>())

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.

collectReferencedColumnsPerTableExpression only stops descending through alias columns when the source is a TableNode. Parameterized views in subqueries are resolved as TableFunctionNodes, and the rest of the analyzer treats their output aliases the same way as table aliases (see CollectTableExpressionData::isAliasColumn). With the current check, SELECT alias_col FROM (SELECT alias_col FROM pv(x = 1)) will still walk the alias expression and can reintroduce ACCESS_DENIED on the underlying columns even when the user has a valid grant on the alias itself. Please short-circuit alias expressions for parameterized-view TableFunctionNodes as well, or reuse the existing alias-column predicate here.

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.

A parameterized view never gives an alias expression to walk. Its columns are the output columns of the view, so a view body that selects a table's ALIAS column hands it out as a plain column. EXPLAIN QUERY TREE SELECT s FROM (SELECT secret_alias AS s FROM pv(x = 1)) shows COLUMN secret_alias with source TABLE_FUNCTION pv and no EXPRESSION child. A view that declares an ALIAS column in its column list does not expose it: SELECT secret_alias FROM pv(x = 1) fails with UNKNOWN_IDENTIFIER. So the walk cannot reach the underlying columns under a parameterized view, and the stop condition only matters for tables.

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 46a07dc26 with master f05f2a72a (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.

Object file sizes

4 object files changed (+65.16 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterAlterQuery.cpp.o 384.28 KiB 432.09 KiB +47.82 KiB (+12.44%)
src/CMakeFiles/dbms.dir/Planner/PlannerJoinTree.cpp.o 847.23 KiB 864.54 KiB +17.30 KiB (+2.04%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

This branch has not been deployed

No deployments
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant