Repository navigation
Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker - #117798
Conversation
…views without an invoker `getSQLSecurityOverriddenContext` called `Context::setUser` for the definer, which sets only `user_id` and leaves the `ClientInfo` user names untouched. When there is no invoker, such as a scheduled refresh of a refreshable materialized view, those names are empty, `RemoteQueryExecutor` sends them as-is, and a shard behind an interserver `<secret>` treats the empty `initial_user` as interserver mode: it skips authentication and runs the query with full access. Fill the empty `current_user`, `initial_user` and `authenticated_user` with the definer's name, and stop `createRefreshContext` from overwriting them with the identity-less copy. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Workflow [PR], commit [a680bdf] Summary: ✅
AI ReviewSummaryThe PR carries the definer identity from background views to remote shards and separates queued Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block pending a safe, explicit migration policy for pre-fix queued files and focused validation of that policy. The separate, pre-existing limitation for views invoked by a real user is accepted as outside this PR's stated scope; it is not repeated as a finding. |
| const bool initial_user_empty = new_client_info.initial_user.empty(); | ||
| const bool authenticated_user_empty = new_client_info.authenticated_user.empty(); | ||
|
|
||
| if (current_user_empty || initial_user_empty || authenticated_user_empty) |
There was a problem hiding this comment.
Only filling the empty ClientInfo names does not make the normal distributed SQL SECURITY DEFINER path correct. When the view is invoked by a real user, initial_user stays as that invoker, and that is still the only principal that crosses the interserver boundary: RemoteQueryExecutor hashes/sends initial_user, and TCPHandler authenticates the shard-side session as that initial_user. The local setUser(getDefinerID(context)) never reaches the remote shard.
That means an ordinary definer view over Distributed still runs remotely under the wrong identity. With push_external_roles_in_interserver_queries = 1 (the default), the shard can even end up with the invoker user plus the definer's current roles, so direct grants and row policies still come from the invoker while role-based access comes from the definer. The result then depends on whether the definer's privileges are encoded as direct grants or roles, which violates the documented SQL SECURITY DEFINER contract for distributed sources.
I think this needs a separate carrier for the effective SQL-security principal on secondary queries, or the remote identity needs to be rewritten to the definer and the invoker-visible currentUser() behavior preserved via a different field. As written, this helper only closes the empty-name scheduled-refresh case.
There was a problem hiding this comment.
🕵 Agreed that this is not covered here, but it is a separate, pre-existing limitation rather than something this PR introduces: when a real invoker runs a SQL SECURITY DEFINER view, the interserver leg is authenticated as initial_user (the invoker) on master as well. This PR only closes the case where initial_user was empty and the shard executed with full access (scheduled refreshes, streaming pushes, now also through the background insert queue). Carrying the effective SQL-security principal separately from initial_user needs a protocol-level design decision (a new ClientInfo field / interserver hash input and how currentUser should behave on the shard), so I am leaving this thread open for the maintainers to decide whether to do it in a follow-up.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units12 translation units recompiled, 53 s compile time in total, 12 of them have a recent master baseline. |
…s into Distributed `Kafka` and `RabbitMQ` push consumed batches only into their materialized views, from a copy of the global context that has no user. A view with `SQL SECURITY DEFINER` switches the push to the definer, but until the previous commit the definer's name did not reach a shard behind an interserver `<secret>`, which then executed the push with full access. The test builds `Kafka -> MV -> Distributed` and `RabbitMQ -> MV -> Distributed` pipelines with the same statements for a user with `INSERT` on the shard and for a tenant without it, and checks in the shard's `system.query_log` that the push ran under the definer's name: the rows arrive for the former and are rejected with `ACCESS_DENIED` for the latter. Co-Authored-By: Claude Fable 5.1 <[email protected]>
| auto view_metadata = getInMemoryMetadataPtr(getContext(), false); | ||
| auto refresh_context = view_metadata->getSQLSecurityOverriddenContext(table_context, &client_info); | ||
| refresh_context->setClientInfo(client_info); | ||
| /// For `SQL SECURITY DEFINER`, `getSQLSecurityOverriddenContext` fills the empty user names in |
There was a problem hiding this comment.
This still only fixes the no-user/background cases. StorageMaterializedView::write and readImpl both call getSQLSecurityOverriddenContext(local_context) with a real invoker (src/Storages/StorageMaterializedView.cpp:509-517 and :599-617), so after this change their ClientInfo keeps the non-empty initial_user / current_user from that invoker.
If the target or source is Distributed, the remote shard is therefore still authenticated as the invoker, and with push_external_roles_in_interserver_queries = 1 it can even receive the invoker user plus the definer's current roles (src/QueryPipeline/RemoteQueryExecutor.cpp:533-559, src/Interpreters/Session.cpp:784-805). That means an ordinary SQL SECURITY DEFINER materialized-view pipeline can still either fail under the invoker or leak the definer's role-based privileges; only the refresh / streaming paths are corrected here.
There was a problem hiding this comment.
🕵 Agreed that this is not covered here, but it is a separate, pre-existing limitation rather than something this PR introduces: when a real invoker runs a SQL SECURITY DEFINER view, the interserver leg is authenticated as initial_user (the invoker) on master as well. This PR only closes the case where initial_user was empty and the shard executed with full access (scheduled refreshes, streaming pushes, now also through the background insert queue). Carrying the effective SQL-security principal separately from initial_user needs a protocol-level design decision (a new ClientInfo field / interserver hash input and how currentUser should behave on the shard), so I am leaving this thread open for the maintainers to decide whether to do it in a follow-up.
# Conflicts: # src/Storages/StorageInMemoryMetadata.cpp
… streaming engines `Kafka` / `RabbitMQ` push into views from contexts with `query_kind = NO_QUERY`, for which `ClientInfo::write` stores only the kind. With the default `distributed_foreground_insert = 0` the queued insert was therefore replayed with an empty `initial_user`, which a shard accepting the interserver `<secret>` executes with full access. `DistributedSink` now persists such a `ClientInfo` as `SECONDARY_QUERY` (as `RemoteInserter` sends it anyway), so the definer's name survives the queue. The integration test now also runs the `Kafka` pipeline with `distributed_foreground_insert = 0`; the tenant's rows reached the shard without this change. The setting moved from the server profile to the users, because the settings of the context the push starts from override the definer's ones. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t users `DistributedAsyncInsertBatch::sendBatch` sends the whole batch with the `ClientInfo` of its first file, and over a cluster with an interserver `<secret>` the shard authenticates it as that file's `initial_user`. The batch key did not include `initial_user`, so with `background_insert_batch = 1` rows of a user without the remote grant could be delivered under another user's identity. Include `initial_user` in the batch key equality and hash. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test uses `test_cluster_interserver_secret`, and the interserver `<secret>` requires SSL, which the fast test build does not have, so the expected `ACCESS_DENIED` is never produced there. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117798&sha=latest&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t too, validate restored batches The shard authenticates a queued insert as `initial_user` from the host of `initial_address` (checked against the allowed hosts of the user), and the whole batch is sent with the `ClientInfo` of its first file. So the batch key now includes the originating host in addition to `initial_user`. A `current_batch.txt` left by an older server could also list files of different users or hosts; such a restored batch is no longer resent as a whole: it is dropped, and its files are batched again by identity. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 The only red job, |
`test_direct_insert` passes on the unfixed binary by design, so the bugfix validation jobs reported it as a failure of the validation, turning both `Bugfix validation (integration tests, ...)` jobs red although every other new test reproduced the bug. Run the control check at the start of `test_rabbitmq` instead, so each test in the module fails without the fix. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117798&sha=latest&name_0=PR&name_1=Bugfix%20validation%20(integration%20tests%2C%20amd64) PR: #117798 Co-Authored-By: Claude Opus 5.5 <[email protected]>
| total_bytes += header.bytes; | ||
| } | ||
|
|
||
| auto identity = getRemoteAuthenticationIdentity(header.client_info); |
There was a problem hiding this comment.
❌ Handle legacy queued inserts that have already lost the definer
This accepts an empty initial_user as a valid batch identity. Before this fix, both scheduled refreshes and streaming pushes could persist files with that field empty (NO_QUERY additionally discarded the whole identity). Those files survive an upgrade: DistributedAsyncInsertHeader::read only fills the initiator version, and RemoteInserter::initialize changes the query kind without supplying a user. TCPHandler::receiveQuery still executes the resulting empty-user interserver query with full access.
For example, stop distributed sends on the old version, let an unprivileged tenant's definer view queue an insert into a protected shard table, then upgrade and flush. A single-file recovered batch passes this check, and the tenant's row is delivered without its remote INSERT grant. The ordinary per-file replay path has the same problem; regrouping the files does not recover their missing identities.
Please handle these legacy files on the replay boundary as well, failing closed with an explicit administrator migration path when the originating definer cannot be recovered. Add an upgrade regression with a pre-fix queued file to prove that installing the fix cannot subsequently replay it with unrestricted access.
There was a problem hiding this comment.
🕵 I am not making this change in this PR. An empty initial_user in a queued file is not a sign that the definer was lost, and it is still written after this fix. Background flushes into a Distributed table have no user: Buffer flushes, materialized views with SQL SECURITY NONE fed by Kafka / RabbitMQ, and inserts that run on a shard in interserver mode. Before and after this PR, those inserts run with the server's own full access on purpose. When the replay code reads a file, it cannot tell such a file from a pre-fix file whose definer identity was dropped. The header has no field that records whether the insert went through a DEFINER view, and old binaries never wrote one. Rejecting every empty-user file at replay would fail closed, but it would also leave legitimate pending inserts stuck in the queue after an upgrade, and in this case that is the more serious breakage. The exposure is limited to files queued on an old binary while sends were stopped or failing, before the upgrade. Whether to add an explicit administrator migration (e.g. refusing to flush pre-fix files with an empty user unless a setting allows it) is a compatibility policy decision, so I am leaving this thread open for the maintainers.
Backport #117798 to 26.10: Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker
Cherry pick #117798 to 26.3: Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker
…from SQL SECURITY DEFINER views without an invoker
Cherry pick #117798 to 26.8: Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker
…from SQL SECURITY DEFINER views without an invoker
The loop in `DistributedAsyncInsertBatch::recoverBatch` read the header of `files.back()` on each iteration, so only the last file was validated and the mixed-identity check added by #117798 compared the last file with itself and never fired. On master this was fixed by #105281, which was not backported to 26.3. Related: #105281 PR: #128668 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #117798 to 26.9: Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker
…from SQL SECURITY DEFINER views without an invoker
Backport #117798 to 26.8: Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker
Backport #117798 to 26.9: Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker
…flush context On 26.3 `async_insert` is enabled by default, and the flush context of `AsynchronousInsertQueue` is built from the global context with only `Context::setUser`, so its `ClientInfo` user names are empty. A direct `INSERT` into a `Distributed` table over a cluster with an interserver `<secret>` was therefore flushed to the shard with an empty `initial_user`, which the shard executes in interserver mode with full access. This is the same hole that #117798 closes for the definer of `SQL SECURITY DEFINER` views, and `test_streaming_engines_definer_interserver_secret::test_rabbitmq[tenant]` caught it in its control case: the tenant's direct insert was accepted on the shard. Bring the fix from #107541 (merged to master in edb9295): capture `current_user`, `initial_user` and `authenticated_user` in the async insert queue key at push time and restore them on the flush context. The only conflict is in `InsertQuery::toTupleCmp`, where 26.3 already uses `query_str_with_secrets` instead of `query_str`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=128668&sha=0dc411340520ff9f52dfdb04638aa63196712372&name_0=BackportPR&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29 PR: #128668 Related: #107541 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The refresh of a `SQL SECURITY DEFINER` refreshable materialized view with parallel replicas no longer leaks rows on master: ClickHouse#117798 (merged 2026-11-01) stamps the definer into the empty `initial_user` of the refresh context, so a replica applies the definer's row policies. Bugfix validation passed this test on master from then on, while it reproduced on every earlier commit of this pull request.
Backport #117798 to 26.3: Send the definer identity to remote shards from SQL SECURITY DEFINER views without an invoker
…from SQL SECURITY DEFINER views without an invoker
The loop in `DistributedAsyncInsertBatch::recoverBatch` read the header of `files.back()` on each iteration, so only the last file was validated and the mixed-identity check added by #117798 compared the last file with itself and never fired. On master this was fixed by #105281, which was not backported to 26.3. Related: #105281 PR: #128668 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…flush context On 26.3 `async_insert` is enabled by default, and the flush context of `AsynchronousInsertQueue` is built from the global context with only `Context::setUser`, so its `ClientInfo` user names are empty. A direct `INSERT` into a `Distributed` table over a cluster with an interserver `<secret>` was therefore flushed to the shard with an empty `initial_user`, which the shard executes in interserver mode with full access. This is the same hole that #117798 closes for the definer of `SQL SECURITY DEFINER` views, and `test_streaming_engines_definer_interserver_secret::test_rabbitmq[tenant]` caught it in its control case: the tenant's direct insert was accepted on the shard. Bring the fix from #107541 (merged to master in edb9295): capture `current_user`, `initial_user` and `authenticated_user` in the async insert queue key at push time and restore them on the flush context. The only conflict is in `InsertQuery::toTupleCmp`, where 26.3 already uses `query_str_with_secrets` instead of `query_str`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=128668&sha=0dc411340520ff9f52dfdb04638aa63196712372&name_0=BackportPR&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29 PR: #128668 Related: #107541 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…from SQL SECURITY DEFINER views without an invoker
…from SQL SECURITY DEFINER views without an invoker
… from SQL SECURITY DEFINER views without an invoker
(Summary from claude:)
A scheduled refresh of a
SQL SECURITY DEFINERrefreshable materialized view sent its distributed sub-query to remote shards with emptyClientInfouser names.getSQLSecurityOverriddenContextestablishes the definer withContext::setUser, which sets onlyuser_id; theClientInfonames were inherited from the refresh context, which is built from the global context and so has no user. On a cluster configured with an interserver<secret>, the receiving shard treated the emptyinitial_useras interserver mode, skipped authentication and executed the query with full access. A user withCREATE TABLE,SELECTandINSERTon their own database could thus wrap any remote table in aDistributedtable, point a refreshable materialized view at it, and have the scheduler copy rows they have no grant on into a table they own.The fix fills empty
current_user,initial_userandauthenticated_userwith the definer's name ingetSQLSecurityOverriddenContext(asAsynchronousInsertQueueandInterpreterExecuteAsQueryalready do), and stopsStorageMaterializedView::createRefreshContextfrom overwriting them with the identity-less local copy. Non-empty names are left untouched, socurrentUserinside an ordinaryDEFINERview invoked by a user still returns the invoker. The refresh now fails withACCESS_DENIEDon the remote shard when the definer lacks the grant, and runs as the definer when it has it.The new integration test fails without the source changes (
SYSTEM WAIT VIEWsucceeds and the rows are copied) and passes with them.The same identity must also survive the background insert queue of
Distributed:DistributedSinknow persists aNO_QUERYClientInfo(streaming engines pushing into views) asSECONDARY_QUERY, so the definer is not lost when the queued insert is replayed, and queued files of differentinitial_users are no longer merged into one batch (the batch is sent with theClientInfoof its first file).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a privilege escalation where a scheduled refresh of a
SQL SECURITY DEFINERrefreshable materialized view reading from aDistributedtable over a cluster with an interserver<secret>was executed on remote shards without authentication, bypassing the definer's access rights. The remote query now runs as the definer.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/117798]
Version info
26.11.1.1027-master(included in26.11and later)