Repository navigation
Require SELECT access on columns read by UPDATE/DELETE mutations (WHERE and SET) - #107486
tiandiwonder wants to merge 49 commits into
Conversation
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]>
|
Workflow [PR], commit [7787147] Summary: ❌
|
…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]>
…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.
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]>
|
🕵 The blocker of the A
8/8 relevant stateless tests pass locally, including The remaining finding - a table function inside a mutation subquery - is the documented gap dismissed earlier: its privilege comes from an |
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.
|
🕵 The blocker of the An object name that the query scope can answer is not one object.
8/8 relevant stateless tests pass locally, |
…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]>
|
🕵 All three findings of the A table function in a mutation expression is a read with no object to grant on. 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
|
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]>
|
🕵 The The red was the test's control statement, not the check. Reproduced locally with |
… 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]>
|
🕵 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:
|
…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]>
|
🕵 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 Locally on the merged head: The integration red on aeb6c3f is unrelated: |
… 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]>
|
🕵 Pushed 9193f48 (on top of a clean merge of master, c5b1900):
|
| /// 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)); |
There was a problem hiding this comment.
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.* / *.*.
There was a problem hiding this comment.
🕵 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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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 withContext::getRowPolicyFilterwhen the table does not exist yet, sovalidate_mutation_query = 0does not open the gap) →ACCESS_DENIEDwith 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(SELECTper matched table),MaterializedView/Buffer(target),Distributed(remote table),system.*(theirSHOWprivileges) - or apply their row policies (aView). Only engines reading their own data are accepted (isMergeTree,Memory,Logfamily,Set,Join,Null,KeeperMap,Dictionary,system.numbers/one/zeros); everything else is refused withBAD_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]>
|
🕵 Pushed 7787147, adopting both of today's AI-review blockers (2026-09-22 15:00):
New test |
Closes: #105614
Closes: #107588
Problem
ALTER TABLE ... UPDATE/DELETE, lightweightDELETE FROM, and lightweightUPDATEonly checked the mutation privilege (ALTER_UPDATE/ALTER_DELETE, plus the assigned columns forUPDATE). They did not requireSELECTon the columns read by the mutation — neither theWHEREpredicate nor the right-hand side ofUPDATEassignments.A user without read access to a column could therefore read it indirectly:
WHERE— probe a predicate and observe how many rows were updated/deleted (ALTER TABLE t DELETE WHERE secret = 42);SETright-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
SELECTon it (a plainSELECT ... WHERE secret = 42is denied).Root cause
Required access for a mutation was computed up front from the command shape only.
InterpreterAlterQuery::getRequiredAccessForCommand(and the access checks inInterpreterDeleteQuery/InterpreterUpdateQuery) addedALTER_UPDATE/ALTER_DELETE(and the assigned columns), but never inspected theWHEREpredicate or the assignment expressions, so noSELECTrequirement was produced for the columns they read.Fix
Require
SELECTon the columns read by a mutation — both theWHEREpredicate and theUPDATEassignment right-hand sides — at all entry points:ALTER ... UPDATE/DELETE, lightweightDELETE FROM, and lightweightUPDATE.The check runs in the execution paths (
InterpreterAlterQuery::executeToTable,InterpreterDeleteQuery,InterpreterUpdateQuery), where the storage is resolved, so that:_part,_row_exists, …) are excluded from theSELECTrequirement usingstorage_snapshot->metadata->virtuals, exactly as a plainSELECTquery treats them (otherwise a column-level grant holder referencing a virtual column in a predicate would be falsely denied);getRequiredAccessForCommandstays free of read requirements, soKILL MUTATION(which reuses it) needs only the mutation privilege — notSELECTon the killed mutation's predicate columns — and theON CLUSTERpre-check is unchanged. ForON CLUSTER/ replicated mutations each node enforces the read access when it executes locally.A small shared helper
addExpressionColumnsSelectAccessextracts the columns from an expression withRequiredSourceColumnsVisitor, stripstable./db.table.qualification so column-level grants match, skips virtual columns, and appends theSELECTelement.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 ofIN, the columnjoinGetnames, and the dictionary of thedictGetfamily. These cannot be left to the submission-time validation, which is whatvalidate_mutation_queryturns 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-tableSELECT, a superset that never under-requires.WITHnames and session temporary tables are skipped. On the right ofIN, a name that is a column of the mutated table (... WHERE 1 IN arr) or aWITHname 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
InterpreterAlterQuerydoes: 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
INor in theFROMof 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 withBAD_ARGUMENTS, for every user: no set of grants would preserve the meaning it was checked with.mergeis modelled: it requiresSELECTon every table of the database it names (of every database for aREGEXPone), and every table it matches at submission is checked as a table read of its own.A table read is reduced to a
SELECTgrant only when that grant is all that decides what the read returns. A table on which the user has a row policy is refused withACCESS_DENIED: a plainSELECTapplies 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, asystemtable other thannumbers/one/zeros, ...) is refused withBAD_ARGUMENTSfor every user, since a background read passes those checks with full access; theMergeTreefamily and the other engines reading their own data (Memory, theLogfamily,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 bydictGet/joinGet, however the name is carried, and its binding in the stored mutation),05239_mutation_table_function_read_access.sh(table functions,mergeincluded, 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) and05241_mutation_row_policy_and_engine_read_access.sh(a row policy on a table read, directly, throughmergeor before the table exists; the refused and the accepted engines) cover every indirect carrier on every entry point withvalidate_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.shcovers the sameON 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.shcovers all entry points with a user that can readnamebut notid: readingidviaWHEREor theSETright-hand side is denied; reading onlynameis allowed; a virtual column in the predicate needs no grant; and everything is allowed onceSELECT(id)is granted. Verified closed-loop (the unfixed binary returnsOKfor every denied case; each clause — WHERE, SET, virtual filtering — is independently load-bearing). The existing04077_lwd_alter_delete_privilege.shstill passes.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a security issue where
ALTER TABLE ... UPDATE/DELETE, lightweightDELETE FROMand lightweightUPDATEdid not requireSELECTaccess on what they read: the columns of theirWHEREclause and ofUPDATEassignment expressions, the tables a subquery in those expressions reads, a table on the right ofIN, the table of ajoinGet, the dictionary of adictGet, 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 withvalidate_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
Workflow [PR]
Sync PR [sync-upstream/pr/107486]