Skip to content

Fix SQL SECURITY DEFINER / NONE views and refreshable materialized views read with parallel replicas as the wrong user - #123729

Merged
fm4v merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-sql-security-view-parallel-replicas-principal
Nov 3, 2026
Merged

fm4v merged 18 commits into
ClickHouse:masterfrom
groeneai:fix-sql-security-view-parallel-replicas-principal

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #74411
Related: #122330
Related: https://github.com/ClickHouse/clickhouse-private/issues/79501

Changelog category (leave one):

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

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

Fixed reading a SQL SECURITY DEFINER or NONE view with enable_parallel_replicas = 1: the replicas ran the view's query as the cluster user with the invoker's row policies instead of as the definer, so the read could return the rows the definer's row policy hides, or fail with ACCESS_DENIED on a cluster with an interserver secret. Queries reading DEFINER / NONE views no longer use query-tree parallel replicas; plan-based parallel replicas (parallel_replicas_plan_based = 1) still apply.

Description

On 26.9.8.3, a user granted only a SQL SECURITY DEFINER view gets the rows the definer's row policy hides if the view's SETTINGS enable custom-key parallel replicas, or if the user reads it with enable_parallel_replicas = 1 and parallel_replicas_local_plan = 0; with an interserver <secret> that read fails with Not enough privileges (#74411). In CI, 05257_sql_security_view_sealed failed with ACCESS_DENIED in the ParallelReplicas job (report).

Root cause: the context getSQLSecurityOverriddenContext builds for such a query has the definer's user but the invoker's ClientInfo, and nothing kept it from initiating parallel replicas. A replica cannot run the shipped read as the definer: it runs as the cluster user plus the row policies of initial_user, or, with a secret, as the invoker.

Change: that context gets a server-only flag (copied into derived contexts, not a setting, so a view's SETTINGS or a definer profile cannot undo it). With it, Context::canUseParallelReplicasOnInitiator is false unless parallel replicas are plan-based, a Distributed shard is not spread over replicas, no custom-key read is started, and a url(), object-storage or data-lake read does not become its -Cluster variant. A DEFINER / NONE view is not inlined while the outer query can ship it. Followers are unaffected.

Price: these queries lose query-tree parallel replicas; a transparent view keeps them via the outer query (parallel_replicas_allow_view_over_mergetree = 1).

The refresh of a DEFINER refreshable materialized view is not affected on master: it has no invoker, and since #117798 (merged 2026-11-01, backported to 26.8, 26.9 and 26.10) its context carries the definer as initial_user, so a replica applies the definer's row policies. It uses the same context, so this change also reads it without query-tree parallel replicas.

02884_create_view_with_sql_security_option is removed from tests/parallel_replicas_blacklist.txt: on master it fails in the ParallelReplicas job in about one run of five with has row policies, but none of them are for the current user from a replica, and it passes in every run of this PR.

Tests: 05257 (deterministic local_plan = 0, custom-key, Distributed and interserver-secret url() arms), new 05406 and 05452, 04545 and 05288 adjusted. New 05330 is a regression test for the refresh: it passes on master since #117798.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1176-master (included in 26.11 and later)

groeneai and others added 3 commits October 3, 2026 14:21
…llel replicas

The query of a `SQL SECURITY DEFINER` / `NONE` view runs in the context built by
`getSQLSecurityOverriddenContext`: the definer's user (or no user for `NONE`), but the
invoker's `ClientInfo`. Nothing kept that context from initiating task-based parallel
replicas, so the planner of the view's query shipped its read as SQL to the replicas. A
replica cannot run it as the definer: it authenticates as the cluster user and applies
the row policies of `initial_user` (the invoker), or with an interserver secret runs as
the invoker. So the definer's row policy is dropped: with the default
`throw_on_unmatched_row_policies = false` the replica returns the rows the policy hides,
with an interserver secret an invoker granted only the view gets ACCESS_DENIED. The same
holds for the refresh of a refreshable materialized view, which runs in the same kind of
context. In CI the test config sets `throw_on_unmatched_row_policies = true`, so
`05257_sql_security_view_sealed` failed with ACCESS_DENIED in the new arm_binary
ParallelReplicas job whenever a remote replica's read was not cancelled first.

The context built for such a query is now marked with a server-only flag, copied into
every context derived from it, and `Context::canUseParallelReplicasOnInitiator` returns
false for it unless plan-based parallel replicas are used (the plan of a sealed view is
already local there). It is a context field rather than a setting, so neither a
`SETTINGS` clause in the view's query nor a settings profile of the definer can turn it
back. Followers are unaffected, and a transparent view can still be read with parallel
replicas through the outer query (`parallel_replicas_allow_view_over_mergetree = 1`),
where each replica expands the view itself. The analyzer no longer inlines a
`DEFINER` / `NONE` view while the outer query may ship it to parallel replicas, since the
shipped outer query would carry the view's query text.

Tests: 05257 gets deterministic parallel-replicas arms (`parallel_replicas_local_plan = 0`,
a `NONE` view with an invoker row policy, inlining on and off, a view that asks for
parallel replicas in its own `SETTINGS`, and a liveness control). 05330 covers the
refreshable materialized view. 04545 asserted that the parameterized DEFINER view was
read with parallel replicas (it then ran as the cluster user); it now asserts the
opposite, with a liveness control. 05288 reads its `NONE` view through the outer query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…RITY DEFINER / NONE query

With `parallel_replicas_for_cluster_engines` (on by default), `url()`, the object-storage
table functions and data-lake catalog tables were still converted to a `-Cluster` storage in
the query of a `SQL SECURITY DEFINER` / `NONE` view, because that check ignored the flag of
such a query, so the read ran on the replicas with the invoker as `initial_user` (with an
interserver secret: ACCESS_DENIED for an invoker granted only the view). The conversion branch
at the three sites now also requires the context not to be such a query, leaving the shared
`can_use_parallel_replicas` value, which the data-lake follower path reuses, unchanged.

05257 gains a `url()` view arm on `test_cluster_interserver_secret`, with a direct `url()`
read by the definer as the positive control that the same settings do distribute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…FINER / NONE query

`getSQLSecurityOverriddenContext` drops only the invoker's `parallel_replicas_custom_key`, so a
custom key enabled by the view's own `SETTINGS` or by the definer's profile still made the
planner of the view's query ship its read as SQL to `cluster_for_parallel_replicas`, where a
replica runs it as the cluster user with the invoker's row policies (on production defaults it
returns the rows the definer's row policy hides). The custom-key initiation in
`buildQueryPlanForTableExpression` now also requires the context not to be such a query; the
follower-side custom-key filter and the invoker-key drop keep reading the unchanged
`canUseParallelReplicasCustomKey`.

05257 gains a custom-key view arm, with a direct read by the definer as the positive control
that the same settings do distribute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 rounds: 1, 1 and 0 findings) plus my own cold review (3 rounds).

# Sev Finding Verdict Evidence / action
1 ❌ The automatic -Cluster conversion (parallel_replicas_for_cluster_engines) of url(), object-storage table functions and data-lake catalog tables inside a DEFINER / NONE query ignored the new flag, so their read still ran on the replicas as another user AGREE, fixed conversion branches gated on the flag; url() arm on an interserver-secret cluster + positive control in 05257
2 ❌ Custom-key parallel replicas turned on by the view's own SETTINGS or the definer's profile still shipped the body's read (only the invoker's key was dropped) AGREE, fixed custom-key initiation gated on the flag; custom-key arm + positive control in 05257
3 💡 The Context.h comment and the changelog said "without parallel replicas" while plan-based parallel replicas stay allowed AGREE, fixed wording
4 💡 InterpreterInsertQuery no longer clears the parallel-replicas settings for a flagged refresh INSERT DROPPED initiation stays impossible downstream (the flag is inherited)
5 💡 Only the url() conversion site has a stateless arm; the object-storage and data-lake sites are the same one-term edit, checked ad hoc (icebergLocal) noted, not blocking no MinIO in Fast test, catalogs are integration-only
6 💡 The changelog's "unless parallel_replicas_plan_based" holds for task-based reads only; a custom-key or -Cluster read stays local in plan-based mode too noted, not blocking stricter than the entry says

Scope: explicit Distributed, remote() and *Cluster reads written inside such a body are not changed by this PR.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261003-171000

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With parallel_replicas_local_plan = 0 every replica is remote: the new 05257 arms (including url() and custom-key), 04545 and 05330 fail on every run without the fix (20/20 randomized each); unchanged master 05257 in the ParallelReplicas-job configuration fails 9/40 with the CI signature.
b Root cause explained? getSQLSecurityOverriddenContext gives a DEFINER / NONE query the definer's user but the invoker's ClientInfo, and that context could initiate parallel replicas; a replica runs the shipped read as the cluster user with the invoker's row policies (or, with an interserver secret, as the invoker), so the definer's row policy is dropped.
c Fix matches root cause? Yes. That context gets a server-only flag (not a setting, so neither the view's SETTINGS nor a definer profile can undo it): Context::canUseParallelReplicasOnInitiator is false for it (plan-based excluded), custom-key initiation and the automatic -Cluster conversion are skipped, and the analyzer does not inline such a view while the outer query can ship it.
d Test intent preserved / new tests added? Yes. 05257: DEFINER view with a definer policy, NONE view with an invoker policy, parallel replicas and custom key requested in the view's own SETTINGS, a url() view on an interserver-secret cluster, definer direct reads as positive controls, liveness. New 05330 (refreshable materialized view). 04545 now asserts no parallel replicas; 05288's NONE arm reads through the outer query.
e Both directions demonstrated? Yes. Without the fix every new arm fails; with it the four tests pass 400/400 (50x each, default and ParallelReplicas configs). Mutations (20/20 randomized each): flag ignored, every arm red; inlining guard removed, only inline = 1; settings switch instead of the flag, the SETTINGS arm and 05330; url() or custom-key check removed, only that arm.
f Fix is general across code paths? Yes. Every such context comes from getSQLSecurityOverriddenContext (view reads incl. parameterized, inlined and nested views, materialized view refresh and insert); the flag is checked in the single initiator gate, the three initiator-side -Cluster conversion sites and the single initiator-side custom-key site. Follower paths are untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes: DEFINER / NONE, sealed and transparent, inline 0/1, allow_view_over_mergetree 0/1, parameterized and nested views, parallel replicas from the query, the view's SETTINGS or a definer profile, local_plan 0 and default, read_tasks and custom-key, with and without an interserver secret.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; such queries only lose query-tree parallel replicas (transparent views keep them through the outer query with parallel_replicas_allow_view_over_mergetree = 1).
i Invariants and contracts preserved? Yes. Unflagged contexts, followers (canUseParallelReplicasOnFollower), the initiator's local plan, plan-based mode and canUseParallelReplicasCustomKey (follower filter, invoker-key drop) are unchanged; a flagged context takes the existing non-cluster branch at the conversion sites.

Session id: cron:clickhouse-impl-slot-6:20261003-120800, cron:clickhouse-impl-slot-7:20261003-150028, cron:clickhouse-impl-slot-5:20261003-163900

@groeneai
groeneai requested review from devcrafter and pufit October 3, 2026 17:37
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [354ab1a]

Summary: ✅


AI Review

Summary

The PR prevents query-based parallel replicas from executing SQL SECURITY DEFINER / NONE view bodies under the wrong identity, while retaining plan-based execution and sampling followers' assigned slices. The earlier findings are addressed in the current code. No new actionable findings at 354ab1ad80d9f2651ca1b72f6dc9b0090ab56a82.

Final Verdict

Status: ✅ Approve.

The url() arm reads through test_cluster_interserver_secret, and an
interserver secret needs SSL, which the Fast test build does not have:
`Code: 344 ... Inter-server secret support is disabled, because ClickHouse
was built without SSL library. (SUPPORT_IS_DISABLED)`. Tag the test
`no-fasttest`, like the other tests that use this cluster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 354ab1ad8 with master f83293657 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

139 object files changed (+105.34 KiB total), 0 added.

Object file Master PR Δ
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionObjectStorage.cpp.o 2.67 MiB 2.69 MiB +26.43 KiB (+0.97%)
src/CMakeFiles/dbms.dir/Analyzer/QueryTreeBuilder.cpp.o 396.86 KiB 416.79 KiB +19.92 KiB (+5.02%)
src/CMakeFiles/dbms.dir/Interpreters/ClusterProxy/executeQuery.cpp.o 558.37 KiB 577.55 KiB +19.18 KiB (+3.44%)
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionURL.cpp.o 237.19 KiB 255.70 KiB +18.51 KiB (+7.80%)
src/CMakeFiles/dbms.dir/Databases/DataLake/DatabaseDataLake.cpp.o 1.72 MiB 1.74 MiB +17.30 KiB (+0.98%)

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

Compile time of recompiled translation units

1328 translation units recompiled, 8640 s compile time in total, 1327 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.4 s

Job report

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
# Conflicts:
#	tests/queries/0_stateless/05257_sql_security_view_sealed.sh
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7a08b64

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) not from this PR: the job ran into its time limit after 2 h 31 min, at test 1177 of 1180, so it reported no test results. The same job errored on 171 PRs and 26 master runs in the last 14 days #123849 (mine, open), which splits this job into 2 batches
PR praktika rollup of the row above #123849 (mine, open)

Session id: cron:our-pr-ci-monitor:20261010-060011

alexey-milovidov and others added 2 commits October 17, 2026 10:42
# Conflicts:
#	src/Interpreters/ClusterProxy/executeQuery.cpp
…` / `NONE` body in every mode

- `getSQLSecurityOverriddenContext` clears `allow_experimental_parallel_reading_from_replicas` (and
  `parallel_replicas_custom_key`) in the body of an initiator after the definer's profile is applied,
  unless plan-based task parallel replicas are used. The checks for what parallel replicas do not support
  (`FINAL`, `JOIN` with a custom key, ...) no longer reject a body that is read locally anyway, and a
  custom key coming from the definer's profile no longer survives.
- `updateSettingsAndClientInfoForCluster` clears parallel replicas for any cluster hop of such a body,
  not only in the `read_tasks` mode, so `ReadFromRemote` does not fan the shard query out with
  `canUseOffsetParallelReplicas`.
- `inlineViewSubqueryIfNeeded` does not inline such a view when the query uses offset or custom-key
  parallel replicas, which ship the query text.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123729&sha=7a08b64999946a926eeed1d2532c3f4f4b844bfd&name_0=PR&name_1=Stateless%20tests%20(arm_asan_ubsan%2C%20azure%2C%20sequential) and provide a fix in a separate PR. If the fix is already in progress, link it here. The job hit its 9000 s timeout at test 1177 / 1180 with every test passing, so it does not look related to this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The fix is already merged: #123849 split this job into 2 batches (merged 2026-10-14, after the run on 7a08b64). Your master merge c2a715d brings it onto this branch, and the CI now running on fa1014a uses the split jobs.

Since the merge, the two halves ran about 2,100 times on PRs and master with no timeout (longest run 7,118 s against the 9,000 s limit). In the week before it, the single job timed out 206 times.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fa1014a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) / 03821_drop_workload_during_query_race flaky, not from this PR (it changes SQL SECURITY views and parallel replicas, not the workload scheduler): having exception in stdout, the stack of RequestQueue::enqueueRequest under CPULeaseAllocation from a query racing DROP WORKLOAD; 2 of 61 reruns failed; seen on 47 other PRs and on master in the last 3 days #126345 (mine, open)
Mergeable Check, PR praktika rollups, red only because of the row above #126345 (the owner of the row above)

All check runs completed and Finish Workflow is green. CIDB has no other FAIL or ERROR row on this head except the Bugfix validation rows, which are the expected inverted pass.

Session id: cron:our-pr-ci-monitor:20261018-020007

alexey-milovidov and others added 7 commits October 26, 2026 03:22
Resolved conflicts: `Context::positional_arguments_already_resolved` was dropped on master, kept only `is_sql_security_overridden_body`; in 05288 kept both `parallel_replicas_allow_view_over_mergetree = 1` and master's `parallel_replicas_plan_based = 0`.
…er its own `SETTINGS`, keep `sampling_key` followers' slice

The restriction of parallel replicas in the body of a `SQL SECURITY DEFINER` / `NONE` view moves to
`Context::restrictParallelReplicasInSQLSecurityOverriddenBody`. It is applied in
`getSQLSecurityOverriddenContext` as before, and also after each `SETTINGS` clause inside the body
(`applyQueryLevelSettings`), so a body that turns parallel replicas on in its own `SETTINGS` no longer
fails with `FINAL modifier is not supported with parallel replicas` / `JOINs are not supported with parallel replicas`.

A `sampling_key` follower (a secondary query with `parallel_replicas_count > 1`) keeps parallel replicas
enabled, so that it reads only the slice assigned by `parallel_replica_offset` instead of the whole table,
which multiplied the result of a `Distributed` table over such a view by the number of replicas.
The body still cannot fan out by itself: `updateSettingsAndClientInfoForCluster` turns parallel replicas off for its shards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…NER` / `NONE` view body across cluster hops

The body of such a view cleared `allow_experimental_parallel_reading_from_replicas` for the shards
it reads, so when the view reads a `Distributed` table, a `sampling_key` follower lost its slice on
the next hop and `MergeTreeDataSelectExecutor::getSampling` read the whole table, multiplying the
result by the number of replicas. Keep the setting for a `sampling_key` follower, and prevent the new
fan-out with `disableOffsetParallelReplicas` instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…as again

The `ParallelReplicas` job ran it as a blacklisted test that is expected to fail (ClickHouse#74411). On master it fails there in about one run of five with `Table ... has row policies, but none of them are for the current user. (ACCESS_DENIED)`: a replica runs the body of the `DEFINER` view as the cluster user `default`. With this change the body of a `DEFINER` / `NONE` view is not read with query-tree parallel replicas (`Context::canUseParallelReplicasOnInitiator`), and all five runs of this pull request reported `NOT_FAILED`.
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.

@fm4v fm4v left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed the full diff and all review threads. The new flag only restricts (server-local, never sent over the wire), so I found no privilege escalation, with or without an interserver secret. SQL SECURITY NONE, nested views and INSERT SELECT with parallel_distributed_insert_select = 2 are covered, and plan-based parallel replicas stays allowed because it ships the definer's row-policy filter as an explicit step. There is no protocol change, so no spec update or revision gate is needed.

Follow-ups pushed to the branch: 02884_create_view_with_sql_security_option is removed from tests/parallel_replicas_blacklist.txt, and the refreshable materialized view claim is dropped from the changelog, because #117798 already fixed that path on master.

The two red fuzzer jobs (AST fuzzer (amd_release, oracle), a -0. float TLP mismatch, and La Casa Del Dolor (amd_debug)) also fail on master and other PRs, and are unrelated.

@fm4v
fm4v added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit e6c0a8e Nov 3, 2026
353 of 355 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
alexey-milovidov pushed a commit that referenced this pull request Nov 14, 2026
26.10 does not include Formats/FormatSettings.h in StorageView.cpp, and
does not have the GRANTs of #123729 in 05257_sql_security_view_sealed.sh,
so only this PR's lines are added there. The test
05331_short_circuit_constant_false_join_totals (#124134) is not on 26.10,
so this PR's change to it is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Views SQL SECURITY doesn't work with Parallel replicas

4 participants