Skip to content

Require SELECT access on columns read by UPDATE/DELETE mutations (WHERE and SET) - #107486

Closed
tiandiwonder wants to merge 49 commits into
ClickHouse:masterfrom
tiandiwonder:fix-alter-where-column-access
Closed

tiandiwonder wants to merge 49 commits into
ClickHouse:masterfrom
tiandiwonder:fix-alter-where-column-access

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #105614
Closes: #107588

Problem

ALTER TABLE ... UPDATE/DELETE, lightweight DELETE FROM, and lightweight UPDATE only checked the mutation privilege (ALTER_UPDATE / ALTER_DELETE, plus the assigned columns for UPDATE). They did not require SELECT on the columns read by the mutation — neither the WHERE predicate nor the right-hand side of UPDATE assignments.

A user without read access to a column could therefore read it indirectly:

  • via WHERE — probe a predicate and observe how many rows were updated/deleted (ALTER TABLE t DELETE WHERE secret = 42);
  • via the SET right-hand side — copy an unreadable column into a readable one (ALTER TABLE t UPDATE visible = secret).

This contradicts the usual model where evaluating an expression over a column requires SELECT on it (a plain SELECT ... WHERE secret = 42 is denied).

Root cause

Required access for a mutation was computed up front from the command shape only. InterpreterAlterQuery::getRequiredAccessForCommand (and the access checks in InterpreterDeleteQuery / InterpreterUpdateQuery) added ALTER_UPDATE / ALTER_DELETE (and the assigned columns), but never inspected the WHERE predicate or the assignment expressions, so no SELECT requirement was produced for the columns they read.

Fix

Require SELECT on the columns read by a mutation — both the WHERE predicate and the UPDATE assignment right-hand sides — at all entry points: ALTER ... UPDATE/DELETE, lightweight DELETE FROM, and lightweight UPDATE.

The check runs in the execution paths (InterpreterAlterQuery::executeToTable, InterpreterDeleteQuery, InterpreterUpdateQuery), where the storage is resolved, so that:

  • virtual columns (_part, _row_exists, …) are excluded from the SELECT requirement using storage_snapshot->metadata->virtuals, exactly as a plain SELECT query treats them (otherwise a column-level grant holder referencing a virtual column in a predicate would be falsely denied);
  • getRequiredAccessForCommand stays free of read requirements, so KILL MUTATION (which reuses it) needs only the mutation privilege — not SELECT on the killed mutation's predicate columns — and the ON CLUSTER pre-check is unchanged. For ON CLUSTER / replicated mutations each node enforces the read access when it executes locally.

A small shared helper addExpressionColumnsSelectAccess extracts the columns from an expression with RequiredSourceColumnsVisitor, strips table. / db.table. qualification so column-level grants match, skips virtual columns, and appends the SELECT element.

Reads a mutation performs indirectly are required too, by addExpressionIndirectReadsAccess: the tables a subquery reads (... WHERE id IN (SELECT secret FROM other), ... UPDATE visible = (SELECT secret FROM other)), a table on the right of IN, the column joinGet names, and the dictionary of the dictGet family. These cannot be left to the submission-time validation, which is what validate_mutation_query turns off: it is an ordinary session setting, the caller picks its value per query, and a background mutation then runs with no user and therefore full access (#107588). The requirements are derived from names alone, without resolving or analyzing anything, so they also hold when validation is deferred because the objects do not exist yet.

Column-level requirements are produced for a subquery level that reads a single plain table and whose references all attribute to it; a join, several tables, a nested subquery or table function in FROM, an asterisk, or a name that is still dotted after stripping the qualification falls back to whole-table SELECT, a superset that never under-requires. WITH names and session temporary tables are skipped. On the right of IN, a name that is a column of the mutated table (... WHERE 1 IN arr) or a WITH name is left alone, since a table name, a set name and an array column are the same identifier in the AST.

The two lightweight entry points also inline SQL UDFs before extracting the read columns, as InterpreterAlterQuery does: a UDF body may reference a column that is not one of its parameters, so the call site alone does not show the read, and on those paths nothing checks access later.

A table function - on the right of IN or in the FROM of a subquery - requires the access a call of it requires (ITableFunction::getRequiredAccessForRead: the source of its engine, TABLE ENGINE, CREATE TEMPORARY TABLE), since the instance that would check it is otherwise built only by the background mutation. A query among its arguments (view(SELECT ...)) is analyzed like a subquery. A table function whose reads depend on the grants of the current user (viewIfPermitted, mergeTreeTextIndex) or that reads objects of the server under checks made only when it is read (dictionary, loop, mergeTreeIndex, mergeTreeProjection, ...) is refused with BAD_ARGUMENTS, for every user: no set of grants would preserve the meaning it was checked with. merge is modelled: it requires SELECT on every table of the database it names (of every database for a REGEXP one), and every table it matches at submission is checked as a table read of its own.

A table read is reduced to a SELECT grant only when that grant is all that decides what the read returns. A table on which the user has a row policy is refused with ACCESS_DENIED: a plain SELECT applies the policy and the background mutation, reading for no user, would not, and so would act on the hidden rows and tell them apart. A table whose engine reads other objects of the server and checks the reading user's access to them, or applies their row policies, only when it is read (Merge, View, MaterializedView, Buffer, Distributed, a system table other than numbers / one / zeros, ...) is refused with BAD_ARGUMENTS for every user, since a background read passes those checks with full access; the MergeTree family and the other engines reading their own data (Memory, the Log family, Set, Join, Null, KeeperMap, Dictionary) are accepted.

04612_mutation_indirect_read_access.sh (subqueries, IN, UDF bodies, aliases), 05238_mutation_dict_get_join_get_object_access.sh (the object named by dictGet / joinGet, however the name is carried, and its binding in the stored mutation), 05239_mutation_table_function_read_access.sh (table functions, merge included, and the refused server-object ones), 05240_mutation_cross_database_read_access.sh (the binding of an unqualified name to the mutated table's database) and 05241_mutation_row_policy_and_engine_read_access.sh (a row policy on a table read, directly, through merge or before the table exists; the refused and the accepted engines) cover every indirect carrier on every entry point with validate_mutation_query = 0, each asserted denied without the grant and allowed with it (the allowed cases keep their predicates false, and the test ends by asserting the secret never reached a readable column); 04613_mutation_on_cluster_indirect_read_access.sh covers the same ON CLUSTER, where the DDL worker does not run as the initiating user. Verified against an unpatched server that every one of those cases is accepted today.

Regression test 04327_alter_where_column_access.sh covers all entry points with a user that can read name but not id: reading id via WHERE or the SET right-hand side is denied; reading only name is allowed; a virtual column in the predicate needs no grant; and everything is allowed once SELECT(id) is granted. Verified closed-loop (the unfixed binary returns OK for every denied case; each clause — WHERE, SET, virtual filtering — is independently load-bearing). The existing 04077_lwd_alter_delete_privilege.sh still passes.

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):

Fixed a security issue where ALTER TABLE ... UPDATE/DELETE, lightweight DELETE FROM and lightweight UPDATE did not require SELECT access on what they read: the columns of their WHERE clause and of UPDATE assignment expressions, the tables a subquery in those expressions reads, a table on the right of IN, the table of a joinGet, the dictionary of a dictGet, the source a table function reads, and the columns a SQL UDF body reads. A user could infer or copy values they cannot read; for the indirect reads it was enough to submit the mutation with validate_mutation_query = 0. A mutation that reads a table under a row policy of the submitting user, or through an engine or table function whose access is checked for the reading user only when it is read (View, Merge, Distributed, dictionary, ...), is refused, since the background mutation would perform that read with full access.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

ALTER TABLE ... UPDATE/DELETE, lightweight DELETE FROM, and lightweight
UPDATE only checked ALTER_UPDATE / ALTER_DELETE (plus the assigned columns
for UPDATE). They never required SELECT access on the columns read by the
WHERE predicate, so a user without read access to a column could infer its
contents by probing predicates and observing how many rows were touched.

Add a shared helper addPredicateColumnsSelectAccess that extracts the
columns referenced in a mutation WHERE predicate via
RequiredSourceColumnsVisitor, strips any table./db.table. qualification so
column-level grants match, and appends a SELECT access requirement. It is
called from InterpreterAlterQuery::getRequiredAccessForCommand (UPDATE and
DELETE cases), InterpreterDeleteQuery, and InterpreterUpdateQuery.

Closes: ClickHouse#105614

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

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7787147]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
01162_strange_mutations FAIL cidb
02436_system_zookeeper_context FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

@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 Jun 15, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label Jun 15, 2026
…ip virtuals

Refine the mutation read-access check:

- Also require SELECT on the columns read by the right-hand side of UPDATE
  assignments (the SET expressions), not just the WHERE predicate. Reading
  another column there (e.g. `UPDATE visible = secret`) is the same indirect
  read as in WHERE.

- Move the check out of the static getRequiredAccessForCommand into the
  execution paths (InterpreterAlterQuery::executeToTable, InterpreterDeleteQuery,
  InterpreterUpdateQuery), where the resolved storage is available. This lets us
  exclude virtual columns (e.g. _part, _row_exists) from the SELECT requirement,
  matching how a plain SELECT query treats them, and avoids over-restricting
  KILL MUTATION (which reuses getRequiredAccessForCommand and should need only
  the mutation privilege, not SELECT on the predicate columns). For ON CLUSTER /
  replicated mutations each node enforces the read access when it executes locally.

Other access dimensions of mutation expressions (dictGet, subqueries on other
tables) are already enforced at submission by the validate_mutation_query path
under the user context, so they are not recomputed here.

Closes: ClickHouse#105614

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@tiandiwonder tiandiwonder changed the title Require SELECT access on columns in ALTER UPDATE/DELETE WHERE clause Require SELECT access on columns read by UPDATE/DELETE mutations (WHERE and SET) Jun 15, 2026
tiandiwonder and others added 2 commits June 15, 2026 12:19
…ated enqueue

Codex review of the mutation read-access check found three issues, all fixed:

- Virtual-column shadowing: a real column whose name matches a virtual one
  (e.g. `_part`) was skipped via a bare `virtuals.has`, letting it be read in a
  mutation predicate without SELECT. Resolve against the schema instead, the
  same way a plain SELECT does: require SELECT on real columns
  (StorageInMemoryMetadata::columns.has) and skip only non-shadowed virtuals
  (isVirtualColumn = !columns.has && virtuals.has).

- Real dotted/quoted column names: the string prefix stripping turned a real
  column `` `t.id` `` into `id`. Now a name that is a real column requires SELECT
  as-is; qualification is stripped only when the result is not itself a real column.

- DatabaseReplicated ALTER bypass: the check ran after
  `tryEnqueueReplicatedDDL` (which, unlike ON CLUSTER, does not preserve the
  initiator user), so the initiator never enforced it. Moved the check before
  the replicated/cloud DDL enqueue in executeToTable.

Regression test extended with a real column shadowing `_part`.

Closes: ClickHouse#105614

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

- Cover SELECT enforcement on the lightweight `UPDATE` assignment right-hand
  side (`UPDATE ... SET name = toString(id) ... SETTINGS enable_lightweight_update = 1`).
- New 04329_replicated_db_mutation_where_access.sh: on a Replicated database an
  ALTER UPDATE/DELETE is denied on the initiator before the DDL is enqueued
  unless the user has SELECT on the WHERE-predicate columns.
- Drop tab_shadow during test setup so reruns after a failure are clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up to "Require SELECT access on columns read by UPDATE/DELETE mutations":
the per-column SELECT requirement was checked late in `execute()`, after the
ON CLUSTER early return, so `ALTER ... UPDATE/DELETE ON CLUSTER`, lightweight
`UPDATE ... ON CLUSTER` and `DELETE FROM ... ON CLUSTER` bypassed it. The remote
DDL worker does not run as the initiator unless
`distributed_ddl_use_initial_user_and_roles` is enabled, so the initiating user's
read access was never enforced for ON CLUSTER mutations.

Compute the read (SELECT) access requirements before any dispatch and:
- append them to `DDLQueryOnClusterParams::access_to_check`, so
  `executeDDLQueryOnCluster` enforces them on the initiator before enqueueing;
- keep enforcing them on the local/replicated path (the old late check is removed
  in favour of the single early computation).

`InterpreterAlterQuery` resolves the table before the ON CLUSTER branch already;
`InterpreterUpdateQuery` now resolves it non-throwingly for the same purpose.
`DELETE FROM ... ON CLUSTER` is rewritten to UPDATE/ALTER ON CLUSTER and is thus
covered transitively. When the table is not present locally (ON CLUSTER issued
from a node without it) the columns cannot be resolved, so it fails closed by
requiring SELECT on the whole table.

Adds `04339_alter_where_column_access_on_cluster` covering the ON CLUSTER deny
(no SELECT) and allow (with SELECT) paths for all three forms.

Verified locally against a single-node cluster with embedded Keeper.
Addresses a review finding: InterpreterUpdateQuery built the SELECT read-access
requirements against the initiator-resolved database but did not qualify the
dispatched query, so an unqualified `UPDATE tab ON CLUSTER c ...` could be
checked against the initiator's database while the remote query bound to each
host's default database (under-enforcing SELECT on clusters with per-host
default databases).

Resolve the table and call `setDatabase(resolved_id.database_name)` before
building the access requirements (mirroring InterpreterAlterQuery, which already
qualifies the query before the ON CLUSTER branch). The ALTER_UPDATE and SELECT
requirements and the dispatched query now all refer to the same database.
When ALTER ... UPDATE/DELETE ON CLUSTER (or the UPDATE statement) is submitted
without a current database, tryResolveStorageID returns an empty table_id, so
the predicate/SET SELECT requirement was not added. But executeDDLQueryOnCluster
expands empty-database access elements to each host's default database (and the
DDL worker rewrites the table there), so ALTER_UPDATE/ALTER_DELETE was still
enforced while the read (SELECT) check was silently dropped.

Add a fail-closed table-level SELECT element using the AST table name with an
empty database in that unresolved case, so it is expanded together with
ALTER_UPDATE/ALTER_DELETE under the same cluster-default expansion.
After merging master, StorageMetadataHandle::operator* is deleted on a
temporary, so dereferencing the getInMemoryMetadataPtr result inline no longer
compiles. Bind it to a local first.
ON CLUSTER is disallowed in replicated-database stateless runs, so the test
needs no-replicated-database. no-parallel was weakly justified (only the shared
DDL queue) and the test uses per-database-unique user/table names, so it can run
in parallel like other ON CLUSTER tests.
tiandiwonder and others added 7 commits June 23, 2026 03:25
Same merge-induced break as InterpreterUpdateQuery: after merging master,
StorageMetadataHandle::operator* is deleted on a temporary, so the inline
deref of getInMemoryMetadataPtr in the DELETE read-access check no longer
compiles (Fast test Build ClickHouse failure). Bind it to a local first.
The test creates a Replicated database (needs Keeper), so it must be tagged
zookeeper for --no-zookeeper and cloud filtering to skip it correctly.
# Conflicts:
#	src/Interpreters/InterpreterAlterQuery.cpp
#	src/Interpreters/InterpreterUpdateQuery.cpp
…is disabled

Address review on ClickHouse#107486: `RequiredSourceColumnsVisitor` (used by
`addExpressionColumnsSelectAccess`) does not descend into subqueries, so a column
read only inside a subquery of a mutation predicate/assignment produced no
`SELECT` requirement. With `validate_mutation_query = 0` that left a bypass, e.g.
`ALTER TABLE t DELETE WHERE 1 IN (SELECT 1 FROM other WHERE secret = 42) SETTINGS validate_mutation_query = 0`
passed the read-access check without `SELECT(secret)`, because the validation
path that would build an `InterpreterSelectQuery` is skipped.

Add `rejectMutationSubqueryWhenValidationDisabled`: when validation is disabled and
a mutation `WHERE`/`SET` expression contains a subquery, fail closed (the security
fix must not depend on `validate_mutation_query` being enabled). Wired into all
entry points (`ALTER ... UPDATE/DELETE`, lightweight `DELETE`/`UPDATE`).
`04327_alter_where_column_access` covers the rejected cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address codex review: rejectMutationSubqueryWhenValidationDisabled was only called
inside the metadata-resolved branches, so ALTER/UPDATE ON CLUSTER issued from a
node without the table locally fell through to the fail-closed whole-table SELECT
without rejecting a subquery when validate_mutation_query=0. The rejection needs
no metadata, so move it out of the metadata_ptr / resolved_table branches to run
on every entry path before enqueue.

Also cover the SET right-hand-side subquery and the lightweight UPDATE subquery
cases in 04327.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The blocker of the Request changes verdict on 6e3f508d is addressed in 0d178252cdff.

A dictGet / joinGet object that is not one name is now every object. The first argument is resolved as an expression identifier first (resolveFunction.cpp) and the runtime takes the name from any constant String expression, so dictGet(concat('db', '.secret_dict'), ...) and an ordinary query alias are valid carriers. The helper recognized neither and asked for no access at all, which under validate_mutation_query = 0 left the object readable by the background mutation. It now proves only a string literal and an identifier that is not an in-scope alias, follows an alias (scalar WITH or an expression alias of the SELECT level) to the string literal it stands for, and fails closed on everything else - the requirement becomes dictGet / SELECT on every object rather than a skipped read.

04612_mutation_indirect_read_access gained both shapes: the concat(...) ones stay denied even with the grants on the object, and the query-alias ones are denied before the grants and allowed after - the grants are never on an object of the alias' own name, so they pass only because the alias is followed to the real object.

8/8 relevant stateless tests pass locally, including 02384_analyzer_dict_get_join_get.

The remaining finding - a table function inside a mutation subquery - is the documented gap dismissed earlier: its privilege comes from an ITableFunction instance that only validation builds.

Address review: `resolveFunction.cpp` resolves the first argument of `dictGet`
and `joinGet` through the expression scope of the query, so an identifier there
may read a value instead of naming the object: a column a subquery below
projects (`FROM (SELECT 'db.secret_dict' AS d) s`, read as `d` or `s.d`), a column
of the mutated table, or an alias of an enclosing `SELECT` level. Such a name
was taken for the object itself, so a grant on an unrelated object of that name
let a mutation with `validate_mutation_query = 0` read the real one.

`mayResolveToColumn` now answers whether the expression scope can answer the
name where it appears, and the object is left unknown when it can, which
requires `dictGet` / `SELECT` on every object. `visibleColumns` returns nothing
instead of an empty set for a level whose columns cannot be looked up, so that
such a level is told apart from one that simply has no columns.
Each new carrier is named after an object the user is granted on further down -
a column a subquery projects as `dict` / `join_tab`, a column of the mutated
table named `dict` - so the case is denied under those grants only because the
name is not taken for the object. Verified against a probe server: every carrier
now requires `dictGet ON *.*` / `SELECT ON *.*`, where the name read off the AST
would have been satisfied by the grant on the object of that name, while an
object named by a string literal still requires only the grant on that object.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The blocker of the Request changes verdict on 0d178252 is addressed in 6c1f6f458109, and the branch is merged with master (1669830d4244).

An object name that the query scope can answer is not one object. resolveFunction.cpp resolves the first argument of dictGet / joinGet through the expression scope, so a column a subquery below projects (FROM (SELECT 'db.secret_dict' AS d) s, read as d or s.d), a column of the mutated table, or an alias of an enclosing level carries the name just as well as a literal. Such an identifier was checked as an object of its own name, so a grant on an unrelated object of that name let a mutation with validate_mutation_query = 0 read the real dictionary or Join table.

mayResolveToColumn now answers whether the scope can answer the name where it appears, and the object is left unknown when it can - the requirement becomes dictGet / SELECT on every object. visibleColumns returns nothing instead of an empty set for a level whose columns cannot be looked up, so a level with a subquery among its table expressions is told apart from a level that simply has no columns.

04612_mutation_indirect_read_access gained the two carriers from the finding, a joinGet one and a column of the mutated table. Each is named after an object the user is granted on further down, so it is denied under that grant only because the name is not taken for the object - measured on a probe server, each now requires dictGet ON *.* / SELECT ON *.* where the name read off the AST was satisfied by dictGet ON db.dict / SELECT ON db.join_tab, while an object named by a string literal still requires only the grant on that object.

8/8 relevant stateless tests pass locally, 02384_analyzer_dict_get_join_get included. The remaining finding - a table function inside a mutation subquery - is the documented gap dismissed earlier.

…tation

Two carriers of a mutation read were still grant-free.

A table function contributed no requirement at all. `IN file(...)`, `url(...)`,
`remote(...)` and a table function in the `FROM` of a mutation subquery name the
data they read in their arguments rather than naming an object to grant on, and
the instance of `ITableFunction` that checks the source access is built only when
the set is built - for a mutation, in the background, under full access. With
`validate_mutation_query = 0` nothing was checked at submission either. Such a
read now requires the access a call of that function requires, collected by the
new `ITableFunction::getRequiredAccessForRead`: the source of its engine, the
`TABLE ENGINE` grant of the engines that require one, and `CREATE TEMPORARY
TABLE` unless the function is allowed in readonly mode - the three checks
`ITableFunction::execute` performs. The call's arguments are not parsed here, so
the source is required on every object of that source; a read-only function with
no source of its own, such as `numbers`, still requires nothing.

A name that the submitting session answers with a temporary or external table was
exempted like in a plain `SELECT`. A mutation is not executed in that session:
the stored expression is replayed by a background mutation, which has neither
those tables nor a current database, and `AddDefaultDatabaseVisitor` leaves such
a name unqualified. Shadowing `secret_set` with a session-only table was
therefore enough to enqueue `ALTER TABLE t DELETE WHERE id IN secret_set` with no
read requirement. The exemption is now only for `WITH` names, so the name is
required as the permanent table it can only be read as there.

`04612_mutation_indirect_read_access` covers both: a table function on the right
of `IN` and in a subquery's `FROM`, denied and then accepted once the source is
granted, `IN numbers(2)` which needs nothing, and a session temporary table that
the session may itself create and read but that does not make the mutation's read
grant-free.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 All three findings of the Request changes verdict on 362df076 are addressed in c323e547f99a, including the older table-function-in-a-subquery one that had been left out of scope.

A table function in a mutation expression is a read with no object to grant on. IN file(...) / url(...) / remote(...), and a table function in the FROM of a mutation subquery, named the data they read in their arguments and contributed no requirement at all; the ITableFunction instance that checks the source access is built only when the set is built, which for a mutation is in the background, under full access, and with validate_mutation_query = 0 nothing was checked at submission either. Such a read now requires the access a call of that function requires, collected by the new ITableFunction::getRequiredAccessForRead: the source of its engine, the TABLE ENGINE grant of the engines that require one, and CREATE TEMPORARY TABLE unless the function is allowed in readonly mode - the same three checks ITableFunction::execute performs. The arguments are not parsed here, so the source is required on the whole source rather than narrowed by the URI: a mutation reading a source the user may read through one URI only is refused, rather than one reading a source the user may not read at all being accepted. A read-only function with no source of its own, such as numbers, still requires nothing, so IN numbers(2) keeps working.

A session temporary or external table no longer makes a name grant-free. The mutation is replayed by a background mutation with none of that session's tables and no current database, and AddDefaultDatabaseVisitor leaves such a bare name unqualified, so the only thing it can be read as there is a permanent table of that name. needsNoGrant now exempts WITH names only.

04612_mutation_indirect_read_access grows both shapes: a table function on the right of IN and in a subquery's FROM, ACCESS_DENIED before GRANT READ ON FILE and accepted after; IN numbers(2), which needs nothing; and a session that creates and reads TEMPORARY TABLE secret_set (OK) whose mutation on that name is still ACCESS_DENIED. 9/9 relevant stateless tests pass locally, and a sweep of the 219 tests matching mutation shows no new failure (the 14 reds are the bare local config: transactions disabled, user_files path, replicated/Keeper).

alexey-milovidov and others added 2 commits September 21, 2026 19:48
The CI test config enables `table_engines_require_grant`, under which
`CREATE TEMPORARY TABLE` needs a grant on the `Memory` engine, so the
control statement of the session-temporary-table case in
`04612_mutation_indirect_read_access` was refused for the engine before
the mutation was ever checked, and the case measured nothing:

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107486&sha=c323e547f99a8f885fcafdf3feddef3ebd3641ee&name_0=PR&name_1=Fast%20test
ClickHouse#107486

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

Copy link
Copy Markdown
Member

🕵 The Fast test red on c323e547f99a is fixed in c7c10f2c80ec, and the branch is merged with master (d3dabfae3e4e).

The red was the test's control statement, not the check. 04612_mutation_indirect_read_access first lets the user create and read a session TEMPORARY TABLE secret_set (OK), so that the ACCESS_DENIED of the mutation on that name is attributable to the mutation. The CI test config enables table_engines_require_grant, under which CREATE TEMPORARY TABLE also needs TABLE ENGINE ON Memory, so the control was refused for the engine (grant TABLE ENGINE ON Memory in the server log) before the mutation was ever checked. The user is now granted that too; the mutation on the temporary table's name stays ACCESS_DENIED.

Reproduced locally with enable_access_control_improvements.xml in the server config: without the grant the temporary table is refused exactly as in CI, and with it 10/10 relevant stateless tests pass on the merged head, including 04612, 04613, 04339, 02384_analyzer_dict_get_join_get and 04909_mutation_partition_pruning_deferred_sets.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107486&sha=c323e547f99a8f885fcafdf3feddef3ebd3641ee&name_0=PR&name_1=Fast%20test

… functions in mutations

Two gaps in the table-function path of `addExpressionIndirectReadsAccess`:

1. `view(SELECT ...)` carries its query as a bare `ASTSelectWithUnionQuery` argument rather
   than as a parenthesised `ASTSubquery`, and `visitExpression` treated only the latter as a
   query. The inner `SELECT` was walked as generic children, so with
   `validate_mutation_query = 0` a mutation like
   `... WHERE id IN (SELECT secret FROM view(SELECT secret FROM secret_tab))` required no
   `SELECT` on `secret_tab`, and the background mutation read it under full access. A bare
   `ASTSelectQuery` / `ASTSelectWithUnionQuery` is now routed through `visitSelectOrUnion`.

2. A table function whose reads depend on the grants of the current user
   (`ITableFunction::dependsOnCurrentUserGrants`: `viewIfPermitted`, `mergeTreeTextIndex`)
   was given the static requirement of `getRequiredAccessForRead`, but a stored mutation
   rebuilds it later, in the background, for no user, so no requirement preserves the meaning
   the submitting user was checked with. Such a function is now refused in a mutation
   expression with `BAD_ARGUMENTS` for every user and at any depth, as it is in a persisted
   `CREATE TABLE ... AS`.

Test `04612_mutation_indirect_read_access` covers both: the `view(...)` carriers denied
without and accepted with `SELECT` on the table its query reads, and the `viewIfPermitted` /
`mergeTreeTextIndex` carriers refused directly in a subquery, nested in `view(...)`, on the
lightweight `DELETE` path, with validation on and for a user with every grant, while the same
query through a plain `view(...)` is accepted for that user. On the previous head every one of
these carriers was accepted for the user without the grant.

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

Copy link
Copy Markdown
Member

🕵 The two blockers of the 2026-09-21 21:00 AI review are adopted in aeb6c3f, both control-proved against the previous head on a local build:

  1. Query-bearing table functions. view(SELECT ...) carries its query as a bare ASTSelectWithUnionQuery argument and visitExpression only treated an ASTSubquery as a query, so ... IN (SELECT secret FROM view(SELECT secret FROM secret_tab)) required nothing on secret_tab under validate_mutation_query = 0 (accepted on the old head, ACCESS_DENIED now, accepted again with the grant). A bare ASTSelectQuery / ASTSelectWithUnionQuery is now routed through visitSelectOrUnion.
  2. User-dependent table functions. A table function with dependsOnCurrentUserGrants() (viewIfPermitted, mergeTreeTextIndex) is now refused in a mutation expression with BAD_ARGUMENTS for every user and at any depth, mirroring the veto for a persisted CREATE TABLE ... AS: a stored mutation rebuilds the function in the background for no user, so no static requirement preserves the meaning the submitter was checked with.

04612_mutation_indirect_read_access covers both (denied / refused / accepted-with-grant / accepted-as-plain-view for the full-access user). 9/9 related stateless tests pass locally on the new head with the CI access-control config (table_engines_require_grant on).

alexey-milovidov and others added 2 commits September 22, 2026 07:32
…mutated table's database

The access check of a mutation (`MutationPredicateColumnsAccess`) requires the
dictionary of an unqualified `dictGet` and the table of an unqualified `joinGet`
under the database of the mutated table, but the text that was stored did not
match: `InterpreterAlterQuery` and `InterpreterUpdateQuery` run the full
traversal of `AddDefaultDatabaseVisitor`, whose `visit(ASTFunction &)` qualified
`dictGet` against the current database of the session context and left `joinGet`
alone, and `InterpreterDeleteQuery` qualified nothing at all. So a session on
`db2` mutating `db1.t` was checked for `dictGet ON db1.dict` while the stored
mutation read `db2.dict` when a dictionary of that name existed there, and a
bare `joinGet('join_tab', ...)` failed in the background with `Default database
is not selected` (control on an unfixed binary: the stored command was
`dictGet('db2.dict', ...)`, `joinGet('join_tab', ...)`).

`AddDefaultDatabaseVisitor` gets a `qualify_function_table_names_with_database_name`
mode in which the full traversal qualifies both names with `database_name`, the
way `visitTableExpressions` already does (the two blocks are factored out into
`qualifyJoinGetTableName` and `qualifyDictGetDictionaryName`). Every mutation
path - `ALTER ... UPDATE / DELETE`, the lightweight `UPDATE` and `DELETE FROM` -
runs the visitor in that mode before the command is stored, so the object that
is checked and the object that is read are the same one.

`04612_mutation_indirect_read_access` now holds a dictionary and a `Join` table
of the same names, with other values, in the session's database, grants the
user the mutated table's database's ones, and asserts through the values that
all four paths read those and none reads the session's.

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

Copy link
Copy Markdown
Member

🕵 The blocker of the 2026-09-22 AI review is adopted in bf9111a, and the branch is merged with master (3a6cebf).

The check and the stored mutation now name the same object. The mutation paths ran the full traversal of AddDefaultDatabaseVisitor, whose visit(ASTFunction &) bound an unqualified dictGet to the session's current database and left joinGet unqualified, while the access check required both under the mutated table's database; DELETE FROM qualified nothing. On an unfixed binary a session on db2 mutating db1.t stored dictGet('db2.dict', ...) and a bare joinGet('join_tab', ...) that failed in the background with Default database is not selected. The visitor gets a mode that qualifies both names with the mutated table's database in the full traversal, and ALTER ... UPDATE / DELETE, lightweight UPDATE and DELETE FROM all run it before the command is stored. 04612_mutation_indirect_read_access asserts through the resulting rows that all four paths read the mutated table's database's dictionary and Join table when the session's database holds same-named ones with other values.

Locally on the merged head: 04612, 02384_analyzer_dict_get_join_get and nine more related stateless tests pass (with the CI access-control config, table_engines_require_grant on).

The integration red on aeb6c3f is unrelated: test_max_bytes_ratio_before_external_distinct[server] is the fleet-wide failure introduced by #121096 and reverted in #121477, which the master merge pulls in.
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107486&sha=aeb6c3fd7b557f9224ab60fbedb62bbe8ec9adba&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%201%2F8%29

alexey-milovidov and others added 2 commits September 22, 2026 13:44
… closed on table functions over the server's tables

Two more gaps in the access check of what a mutation reads, and a test split.

1. `AddDefaultDatabaseVisitor::qualifyDictGetDictionaryName` qualified every one-part identifier
   with the mutated table's database, but the analyzer resolves the first argument of `dictGet`
   through the expression scope first, so `dictGet(d, ...)` with `'db.dict' AS d` in scope reads
   `db.dict`. The access check followed the alias to `db.dict`, while the stored mutation was
   rewritten to `dictGet(db.d, ...)` - a dictionary `d` of that database, read under full access.
   An alias of the select query is now left alone, as `qualifyJoinGetTableName` already did.

2. `ITableFunction::getRequiredAccessForRead` is not the whole read contract of a table function
   over the server's own tables: `merge('db', '^secret$')` requires nothing of its own, and
   `StorageMerge::read` checks `SELECT` on the matched tables only when they are read - for a
   mutation, in the background. Such a function is now taken for a read of every table its
   arguments can name: `SELECT` on the database when `merge` names it by a literal, `SELECT ON *.*`
   otherwise (`merge` with a computed or regular-expression database, `mergeTreeIndex`,
   `dictionary`, `loop`, `eval`, and any table function added later). Functions reading a source
   of their own (`file`, `s3`, `remote`, ...) are covered by their source grant, and the ones known
   to read no table (`numbers`, `values`, `generateRandom`, `view` - whose query is walked - ...)
   are exempt, so `04909_mutation_partition_pruning_deferred_sets` (`d IN numbers(2)`) is unaffected.

The test `04612_mutation_indirect_read_access` ran for more than 180 s in the ASan flaky check
(about a hundred client invocations), so it is split by subject: `04612` keeps the subquery, `IN`,
UDF and alias cases, `05238_mutation_dict_get_join_get_object_access` the object named by
`dictGet` / `joinGet` (plus the new alias-binding case, which checks the value the stored mutation
wrote on all three entry points), `05239_mutation_table_function_read_access` the table functions
(plus `merge` over a literal and a computed database), and `05240_mutation_cross_database_read_access`
the binding of an unqualified name to the mutated table's database.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107486&sha=bf9111a7ea6ccb130218f1e444b7a6836f07b4d7&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20flaky%20check)
PR: ClickHouse#107486

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

Copy link
Copy Markdown
Member

🕵 Pushed 9193f48 (on top of a clean merge of master, c5b1900):

  • Both new review findings adopted - the dictGet alias rebinding in AddDefaultDatabaseVisitor and the fail-closed rule for table functions over the server's tables (merge, ...). Details and the discriminating test for each are in the thread replies.
  • The only red on the previous head was 04612_mutation_indirect_read_access exceeding 180 s in the ASan flaky check (report) - about a hundred client invocations in one test. It is now split by subject into 04612 (subqueries, IN, UDFs, aliases), 05238 (dictGet / joinGet objects), 05239 (table functions) and 05240 (cross-database binding); each runs in about 3 s on a release build here.
  • 10 related stateless tests pass locally on the new head, including 04909_mutation_partition_pruning_deferred_sets and 02384_analyzer_dict_get_join_get.

/// of the others only the ones known to read no table, or only the tables of a query
/// walked here, are exempt.
if (!reads_a_source && !readsNoTableOfItsOwn(table_function->getName()))
required_access.emplace_back(wrapperTableFunctionReadAccess(table_function->getName(), function));

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 fallback is still too weak for server-object table functions that do not read an external source. dictionary('dict') is the clearest carrier: TableFunctionDictionary builds StorageDictionary, and StorageDictionary::read later enforces dictGet/SELECT on the dictionary object itself, not SELECT on server tables. mergeTreeIndex, mergeTreeProjection, and loop(table) also do extra user-dependent checks at read time (SHOW COLUMNS, row-policy enforcement, etc.). With validate_mutation_query = 0, a mutation subquery can therefore pass this initiator pre-check on unrelated table grants and then build the function in the background under full access. Please either reject these functions in mutation expressions or model each function's exact runtime read contract here instead of collapsing them to SELECT on db.* / *.*.

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.

🕵 Confirmed and adopted in 7787147. The fallback is gone: a table function without a source of its own that is not in the reads-nothing list is now refused with BAD_ARGUMENTS for every user, at any depth (dictionary, loop, mergeTreeIndex, mergeTreeProjection, eval, and whatever is added later) - the same veto as for viewIfPermitted. Their runtime contracts (dictGet on the dictionary, SHOW COLUMNS, SELECT under the source table's row policies) are not a set of grants that can be required at submission, so rejection is the fail-closed choice you suggested.

merge alone is kept, because master's 04693_merge_table_function_in_mutation relies on it working in mutations, and its read contract can be modelled exactly: StorageMerge::read checks SELECT on each matched table for the reader. The collector now requires SELECT on every table of the database it names (of every database for a REGEXP one) - the only requirement that also covers a table created between the check and the read - and additionally runs every table matched at submission through the same per-table check as a subquery table (row policy → ACCESS_DENIED, non-plain engine → BAD_ARGUMENTS). The database argument is evaluated with the mutated table's database as the current one, which is what AddDefaultDatabaseVisitor substitutes for currentDatabase() and for the one-argument form before the mutation is stored.

Tests: 05239 now asserts dictionary / loop / mergeTreeIndex refused for the user and for the admin, merge denied without SELECT ON db.* (including the one-argument, currentDatabase() and REGEXP spellings) and accepted with it; 05241 covers merge matching a table under a row policy and matching a View.

{
if (auto columns = tryAttributeColumns(expressions, tables.front(), aliases.front()))
{
required_access.emplace_back(

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 reduces a subquery read to static SELECT grants on the referenced table/columns, but it still drops row policies on that table. A background mutation executes the subquery later with no query user, so ALTER TABLE dst DELETE WHERE id IN (SELECT secret FROM secret_tab) will pass here for a user who has SELECT on secret_tab but a row policy hiding some rows, and the mutation can still act on those hidden rows under full access. The same issue exists in the x IN other path above. To fully close the security hole, these indirect table reads need either user-preserving execution or a fail-closed rejection when the referenced table has user-dependent filters; AccessType::SELECT alone is not enough.

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.

🕵 Confirmed and adopted in 7787147, as a fail-closed rejection (user-preserving execution is not available to a background mutation: the entries are persisted as text, for ReplicatedMergeTree in ZooKeeper, and replayed with no user).

Every table read collected here - a subquery table (column-attributed or whole-table), a table on the right of IN, and now each table a merge matches - goes through one check before its SELECT requirement is added:

  • row policy: getEffectiveRowPolicyFilter(storage, context) for the submitting user (the policy looked up by name with Context::getRowPolicyFilter when the table does not exist yet, so validate_mutation_query = 0 does not open the gap) → ACCESS_DENIED with a message saying the policy would not apply to the background read;
  • engine: the same class of problem exists for engines that check the reading user's access to other objects only when read - Merge (SELECT per matched table), MaterializedView / Buffer (target), Distributed (remote table), system.* (their SHOW privileges) - or apply their row policies (a View). Only engines reading their own data are accepted (isMergeTree, Memory, Log family, Set, Join, Null, KeeperMap, Dictionary, system.numbers / one / zeros); everything else is refused with BAD_ARGUMENTS, for every user.

05241_mutation_row_policy_and_engine_read_access covers: the policy hiding a row from the user's own SELECT; every entry point refused (ALTER ... DELETE / UPDATE, DELETE FROM, IN table, validate_mutation_query = 0, through view(...), through merge, and for a not-yet-existing table); a table without a policy and a user the policy does not target still accepted; the same mutations accepted once the policy is dropped; View / MaterializedView / Merge / Buffer / Distributed / system.users refused for the user and the admin; Memory / StripeLog / Dictionary / system.numbers / system.one accepted; and a final row count proving nothing was mutated. 01049_join_low_card_bug_long, 02950_dictionary_ssd_cache_short_circuit, 04693 and the rest of the mutation test family pass locally.

…t decide

The reads a mutation expression performs indirectly were reduced to a
`SELECT` grant on the table read, but that grant is not all that decides
what a plain `SELECT` returns for the submitting user, while the
background mutation reads for no user and so under full access:

- a row policy of the user on the table hides rows from a plain `SELECT`
  and is not applied by the mutation, so `... WHERE id IN (SELECT secret
  FROM other)` acted on the hidden rows and told them apart. Such a read
  is now refused with `ACCESS_DENIED` (`getEffectiveRowPolicyFilter` on
  the storage, or the policy looked up by name when the table does not
  exist yet);
- an engine that reads other objects of the server checks the reading
  user's access to them only when it is read (`Merge`, `MaterializedView`,
  `Buffer`, `Distributed`, a `system` table) or applies their row
  policies (a `View`). Only engines reading their own data (the
  `MergeTree` family, `Memory`, the `Log` family, `Set`, `Join`, `Null`,
  `KeeperMap`, `Dictionary`, `system.numbers` / `one` / `zeros`) are
  accepted now; anything else is refused with `BAD_ARGUMENTS`;
- the generic fallback for a table function without a source of its own
  (`SELECT` on `db.*` / `*.*`) was not the read contract of `dictionary`
  (`dictGet` on the dictionary), `loop` (`SHOW COLUMNS`), `mergeTreeIndex`
  / `mergeTreeProjection` (`SELECT` on the source table under its row
  policies). Such functions are now refused with `BAD_ARGUMENTS`. `merge`
  alone is modelled: `SELECT` on every table of the database it names (of
  every database for a `REGEXP` one), the database argument evaluated
  with the mutated table's database as the current one, as the stored
  mutation reads it, and every table matched at submission checked as a
  table read of its own.

New test `05241_mutation_row_policy_and_engine_read_access`; the `merge`
and server-object cases of `05239_mutation_table_function_read_access`
reworked accordingly.

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

Copy link
Copy Markdown
Member

🕵 Pushed 7787147, adopting both of today's AI-review blockers (2026-09-22 15:00):

  1. Row policies - every table a mutation expression reads (subquery table, IN table, and each table a merge matches) is now refused with ACCESS_DENIED when the submitting user has a row policy on it (getEffectiveRowPolicyFilter; looked up by name when the table does not exist yet), since the background read would not apply it. Engines whose read checks the reading user's access to other objects, or applies their row policies, only when read (View, MaterializedView, Merge, Buffer, Distributed, system.* except numbers / one / zeros) are refused with BAD_ARGUMENTS for every user; the MergeTree family, Memory, the Log family, Set, Join, Null, KeeperMap and Dictionary stay accepted.
  2. Server-object table functions - the SELECT ON db.* fallback is gone; dictionary, loop, mergeTreeIndex, mergeTreeProjection and any other no-source function outside the reads-nothing list are refused with BAD_ARGUMENTS. merge is modelled exactly instead (master's 04693_merge_table_function_in_mutation depends on it): SELECT on every table of the database it names (*.* for REGEXP), the database argument evaluated as the stored mutation reads it, plus the per-table check above on every table matched at submission.

New test 05241_mutation_row_policy_and_engine_read_access; 05239 reworked. The 16 related stateless tests pass locally (incl. 04693, 04303, 04305, 04757, which read merge / system.one in mutations). PR description updated accordingly. CI on the previous head 9193f4841022 had 0 failures (40 passed, integration jobs still running at the time of this pass).

@alexey-milovidov alexey-milovidov added hold Skip for auto-updating. close in a month if not active This will be closed in case of no information labels Sep 22, 2026
@alexey-milovidov alexey-milovidov removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors close in a month if not active This will be closed in case of no information comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. hold Skip for auto-updating.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RBAC: mutations with subqueries bypass SELECT checks when validate_mutation_query=0 ALTER TABLE do not check WHERE columns rights

4 participants