Skip to content

Read a SQL SECURITY DEFINER / NONE view through an opaque plan step - #122330

Merged
alexey-milovidov merged 29 commits into
masterfrom
sql-security-view-sealed-read
Oct 1, 2026
Merged

alexey-milovidov merged 29 commits into
masterfrom
sql-security-view-sealed-read

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Reimplementation of #112847 with the approach suggested in its review: wrap the view in a read step that no optimization can see through, instead of teaching every optimization to stop at a view.

A SQL SECURITY DEFINER / NONE view runs with privileges other than the invoker's and can hide rows. Its plan was spliced into the outer plan, so an outer WHERE was evaluated on the hidden rows and could reveal them: SELECT secret FROM v WHERE throwIf(secret = 'HIDDEN', 'LEAKED') = 0 throws LEAKED for a user granted only SELECT ON v. The outer filter also drove index analysis of the tables behind the view, so read_rows showed whether a hidden row matched.

Such a view is now sealed: its plan is optimized on its own as the child plan of a new ReadFromSealedViewStep, and the outer plan sees only an opaque source step. The paths that reach the view before a plan exists check StorageView::isSealed too: passing the outer filter for index analysis, analyzer_inline_views, the trivial-view pushdown to Distributed (which let NONE views through), parallel replicas, pushOrderByIntoView and the legacy InterpreterSelectQuery rewrite. With make_distributed_plan the view's plan is distributed on its own, like the child plans of ReadFromMerge, and the outer plan runs locally. With serialize_query_plan the shard builds the step itself.

A plain projection of a MergeTree table hides no rows and stays transparent, unless a row policy applies to the table in the view's context or to the view in the invoker's. Every other DEFINER / NONE view is sealed, so an outer filter no longer narrows what is read behind it; such queries can get slower.

The plan of a sealed view can hold values folded from data the invoker cannot read: a scalar subquery over a private table, a key computed on the other side of a JOIN (the DEFINER view scenario of https://github.com/ClickHouse/clickhouse-private/issues/72525). EXPLAIN shows it only to the definer, to a user who could have created the same view (SET DEFINER on the definer or ALLOW SQL SECURITY NONE, plus the global read privileges CREATE VIEW checks: SELECT, dictGet, READ, CREATE TEMPORARY TABLE, NAMED COLLECTION), or to a user who may display secrets. Everyone else sees the step alone, marked plan hidden. Optimizations still see the child plan.

Out of scope: a row policy on the view itself stays a Filter above the view, as for every storage without PREWHERE; EXPLAIN PIPELINE graph = 1 still draws the inner processors, which carry no folded values.

Related: #112847
Related: https://github.com/ClickHouse/clickhouse-private/issues/72525
Related: #120371

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

A view with SQL SECURITY DEFINER or SQL SECURITY NONE that can hide rows is now read as a whole and is opaque to the optimizations of the query that reads it; previously an expression of the outer query could be evaluated on the hidden rows and reveal them, for example through an exception message. EXPLAIN shows the plan of such a view only to users who could have created it or who may display secrets.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1211-master (included in 26.10 and later)

A view whose query runs with privileges other than the invoker's can hide rows
the invoker must not see. Its plan used to be spliced into the outer plan, so
the outer `WHERE` merged with the view's own filter, and an invoker expression
such as `throwIf` was evaluated on the hidden rows. The outer filter also drove
index analysis of the tables behind the view.

Such a view is now sealed: its plan is a child plan of the new
`ReadFromSealedViewStep` and is optimized on its own, so every optimization of
the outer query is blocked by construction instead of by a check in each of
them. The outer filter is not forwarded into the view, and the view is not
inlined by `analyzer_inline_views`, pushed down to `Distributed`, or read with
parallel replicas. A plain projection of a `MergeTree` table hides no rows, so
it stays transparent.

This is the approach suggested in the review of
#112847 (review)

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

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbdbc7f]

Summary: ✅


AI Review

Summary

This PR closes the main SQL SECURITY DEFINER / NONE view-transparency leaks by routing sealed views through ReadFromSealedView, hiding sealed child plans from EXPLAIN, and fixing the earlier AST / ORDER BY / cloning / distributed / profiling bypasses. I still see two RBAC blockers before it is merge-ready: one new hole around additional_table_filters, and one still-open show_plan privilege check.

Findings

❌ Blockers

  • [src/Storages/StorageView.cpp:654] isSealed only models row policies as late row-hiding filters. additional_table_filters can hide rows on the view or on its underlying table too, but those filters are attached later (PlannerJoinTree::buildAdditionalFiltersIfNeeded / InterpreterSelectQuery). A plain SQL SECURITY DEFINER / NONE projection view therefore still stays transparent under that setting, so the old leak paths remain: the caller's outer predicate is still forwarded into inner index analysis, and analyzer_inline_views / the legacy rewrite can still evaluate caller expressions on rows the additional filter should hide. Since the setting is explicitly documented as an access-control mechanism, this reopens read_rows / throwIf side channels whenever additional_table_filters is used. The sealing decision needs to fail closed when an additional filter matches the view or its trivial underlying table for the current query.
  • [src/Storages/StorageView.cpp:467] canSeeViewPlan still equates "SET DEFINER / ALLOW SQL SECURITY NONE plus broad read grants" with "the caller could have created the same view", but it never checks any view-creation right. A read-only user can therefore inspect a sealed plan (and any folded private constants) even if they cannot create either a regular view (CREATE_VIEW) or a temporary one (CREATE_TEMPORARY_VIEW) anywhere. That is not just a wording mismatch: if the user's own row policies would hide the underlying rows, direct SELECT is still narrower, so the disclosure is only available through this branch. Gate show_plan on an actual view-creation capability as well, or fall back to the definer / displaySecretsInShowAndSelect cases only.
Final Verdict

Changes requested. The main sealing design looks solid now, but the current fast paths are still too permissive for two access-control-sensitive surfaces: late additional_table_filters and the non-definer show_plan privilege test.

LLVM Coverage Report

Measured on commit bbdbc7f.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 165/183 (90.16%) · Uncovered code

Full report · Diff report

@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 Sep 25, 2026
Comment thread src/Storages/StorageView.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-view Logical (non-materialized) views. label Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bbdbc7f34 with master cdc0f1ab4 (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

77 object files changed (+61.70 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageView.cpp.o 441.63 KiB 501.99 KiB +60.36 KiB (+13.67%)

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

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +204.5 s (+4%) in total before that adjustment.

Job report

…y on the table

A `SQL SECURITY DEFINER` view `SELECT ... FROM t` over a `MergeTree` table was
treated as transparent, but a row policy of the definer on `t` is applied inside
the read, so the view still hides rows. The outer filter was forwarded into the
view for index analysis, and `read_rows` showed whether a hidden row matched it.
`isSealed` now checks the effective row policy in the view's context.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
aparajita31pandey pushed a commit to aparajita31pandey/ClickHouse that referenced this pull request Sep 27, 2026
…g_empty_parts_partition`

The test waited only for the mutation of `r1` to finish and then counted the rows
of `r2`. Each replica mutates its own parts, so `r2` could still be executing
its `MUTATE_PART` entry and returned the 30 rows the mutation deletes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122330&sha=e6ee9737d727f690f17b87266a98c6ffa20786c9&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
ClickHouse#122330

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits September 27, 2026 23:01
…ew itself

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…5257

Under a configuration where `users_without_row_policies_can_read_rows` is
false (Fast test), reading a table that has row policies none of which is
for the current user throws `ACCESS_DENIED`, so the `EXPLAIN` of
`view_policy_view` as the default user failed. The view is still checked for
the user that has the policy.

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

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits September 28, 2026 03:29
…rpreterSelectQuery`

`InterpreterSelectQuery::analyze` replaced a view with its body and stored the
rewritten body in `query_info.view_query`, so AST-level rewrites saw through a
sealed view before `StorageView::readImpl` wrapped it into `ReadFromSealedViewStep`.
Apply the same `isSealed` gate as `QueryAnalyzer::inlineViewSubqueryIfNeeded`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
The default `IQueryPlanStep::clone` throws, so a sealed view failed in every
path that clones plan fragments, e.g. a correlated subquery with
`correlated_subqueries_use_in_memory_buffer = 0` or local parallel replicas.
Deep-clone the already optimized view plan and keep its optimization settings.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
@rschu1ze

Copy link
Copy Markdown
Member

@vdimir Allow me to set you as assignee for this PR (you commented on #112847)

`pushOrderByIntoView` rewrote the inner query of a sealed view before
`StorageView::readImpl` wrapped it into `ReadFromSealedViewStep`, so an outer
`ORDER BY ... LIMIT` could drive an early-stopping read-in-order below the
security boundary and make `read_rows` depend on the rows the view hides.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
Comment on lines +596 to +606
if (getEffectiveRowPolicyFilter(*this, context))
return true;

const auto & inner_query = metadata.getSelectQuery().inner_query;
auto storage = tryGetTrivialViewUnderlyingStorage(inner_query, context);
if (!storage || !storage->isMergeTree()
|| inner_query->as<ASTSelectWithUnionQuery &>().list_of_selects->children.front()->as<ASTSelectQuery &>().where())
return true;

/// A row policy of the view's context on the table is applied inside the read, so the projection still hides rows.
return getEffectiveRowPolicyFilter(*storage, metadata.getSQLSecurityOverriddenContext(context)) != nullptr;

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.

Checks look fragile, especially the AST one, since the query may be more complex. Why not just consider all views with sql security sealed?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Sealing every DEFINER / NONE view would be simpler, but the price seems too high for the most common use of these views: a column-restricting wrapper such as CREATE VIEW v SQL SECURITY DEFINER AS SELECT a, b FROM t, where users get SELECT on the view but not on the table. A sealed view is opaque, so SELECT ... FROM v WHERE key = 42 would lose filter push-down and primary-key analysis and become a full scan. It would also lose read-in-order, trivial count and the other optimizations. Such a view hides no rows, so keeping it transparent leaks nothing the invoker cannot already read.

About fragility: the AST part is tryGetTrivialViewUnderlyingStorage, which already exists on master and is used for optimize_trivial_view_pushdown_to_distributed. It rejects anything that is not a single-table SELECT without WITH/PREWHERE/GROUP BY/HAVING/QUALIFY/ORDER BY/LIMIT/LIMIT BY/DISTINCT/ARRAY JOIN/SETTINGS, joins, subqueries, FINAL/SAMPLE, aggregates, window functions or asterisk transformers. On top of that, isSealed also seals a view with any WHERE, over a non-MergeTree table, with a definer's row policy on the table, or with the invoker's row policy on the view. So a more complex query only gets sealed. The weak point is that the helper lists clauses to reject, so a new row-filtering clause would have to be added there. If you prefer the strict rule anyway, it is a one-line change to isSealed and I will make it. Leaving this one to you.

Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
alexey-milovidov and others added 2 commits September 28, 2026 16:47
`ReadFromSealedViewStep` forced `make_distributed_plan = false` for the view's plan.
The outer plan cannot be distributed because the step is not serializable, but the
view's plan still can: decide it for the child plan with
`applyDistributedPlanFallbackToLocal` before optimizing it, as `ReadFromMerge` does
for its child plans. Parallel replicas stay disabled.

Extend `05257_sql_security_view_sealed` with a distributed query plan over a sealed
view, a parameterized `SQL SECURITY DEFINER` view, and reads through a `Distributed`
table over a sealed view and a sealed view over a `Distributed` table, with
`serialize_query_plan` = 0 and 1.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…n it themselves

The plan of a `SQL SECURITY DEFINER` or `NONE` view runs with the view's privileges and can hold
values folded from data the invoker cannot read: a scalar subquery over a private table, a key
decrypted on the other side of a JOIN. `EXPLAIN` printed them to any user with `SELECT` on the view.

`ReadFromSealedViewStep` is now opaque in `EXPLAIN` unless the user could have created the same view
(the definer, a user with `SET DEFINER` on the definer, a user with `ALLOW SQL SECURITY NONE` for a
`NONE` view) or may display secrets (the server setting `display_secrets_in_show_and_select`, the
format setting and the `displaySecretsInShowAndSelect` privilege). The child plan is hidden from the
plan and pipeline dumps only; the optimizations keep seeing it through `getChildPlans`. In the hidden
case the inner processors are attributed to the sealed step, so `EXPLAIN PIPELINE graph = 1` and
`system.processors_profile_log` do not show the inner steps either.

Related: ClickHouse/clickhouse-private#72525
Related: #120371

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
vdimir and others added 3 commits September 29, 2026 11:23
…he sealed one

A `SQL SECURITY DEFINER` view over a Memory table is sealed, so the legacy rewrite
behind `EXPLAIN AST optimize = 1` no longer inlines its body and the reference from
PR #120313 stopped matching. The test table becomes a `MergeTree`, which keeps the
view transparent and the masking of the inlined body under test, and a second view
with a WHERE pins that a sealed view is printed as a `TableIdentifier`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122330&sha=7d01b1f68237e134cc8ca7d650d4f2df49915d4b&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 5 commits October 1, 2026 02:34
…ealed-read

`StepWallClockRegistry.cpp` was removed on master; its plan walk moved to
`StepProfiler.cpp`, which now passes `for_explain = false` to `getChildPlans`.
… to the sealed step

`EXPLAIN PIPELINE graph = 1` and `system.processors_profile_log` name the plan step
each processor comes from and print its description, so they exposed the inner steps
of a sealed view whose plan `EXPLAIN PLAN` hides. When the plan is hidden,
`ReadFromSealedViewStep` now tags every processor of the view's pipeline with itself
and clears the processor descriptions. 05258 checks the graph output and the log.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…t stored columns

A transparent view is inlined into the invoker's plan, so `EXPLAIN` prints its
expressions. A view such as `SELECT concat(s, 'KEY') FROM mt` over a `MergeTree`
table without `WHERE` or row policies stayed transparent and showed the constants
of its definition to a reader with only `SELECT` on the view. The same applies to
an `ALIAS` column of the table, selected directly or through `*`.

`StorageView::isSealed` now keeps such a view transparent only when every element
of its projection is a stored column of the table, or `*` over a table without
`ALIAS` columns. Test 05315 covers both `EXPLAIN PLAN` and `EXPLAIN PIPELINE graph = 1`.

Addresses the review thread
#122330 (comment)
and the AI review "Request changes" verdict.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…Y INVOKER` view

A `SQL SECURITY DEFINER` view that computes `encrypt` over its table is sealed since
6112380, so `EXPLAIN AST optimize = 1` no longer inlines its body and the test lost
the case it was written for. The inlined view is now `SQL SECURITY INVOKER`, which is
never sealed, and the sealed view no longer needs a `WHERE` to be sealed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
@vdimir

vdimir commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

@alexey-milovidov do we plan to backport this PR?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

No, it is not for backport. A security hardening for a scenario that ought to be secure, but was not guaranteed.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
@alexey-milovidov alexey-milovidov removed the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 1, 2026
Merged via the queue into master with commit af61be7 Oct 1, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the sql-security-view-sealed-read branch October 1, 2026 21:07
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @vdimir — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Nov 11, 2026
…es it

Since ClickHouse#122330 every DEFINER / NONE view that can hide rows is read through
the opaque ReadFromSealedViewStep, so an outer ORDER BY ... LIMIT cannot read
in order through it and reads the whole table (ClickHouse#130316: 3,001,000 rows
instead of 43,688 on 26.8). The seal keeps the rows the view hides away from
the invoker, but it ignored who reads the view: a query that runs with the
definer's own identity can read every one of those rows anyway.

StorageView::isReadByDefiner holds when the query runs with exactly the
identity getSQLSecurityOverriddenContext gives the view's own query:
setUser(definer) means the definer by UUID (users of different storages may
share a name), its default roles and no authentication-method GRANTS limit.
A secondary query does not carry the initiator's credential limit (with a
cluster secret the shard re-authenticates the initial user by name), so only
an initial query qualifies. A row policy on the view itself restricts even
the definer, so it keeps the view sealed. readImpl's seal decision and
pushOrderByIntoView use it; the parallel-replicas carrier, the Distributed
pushdown and analyzer_inline_views keep the structural isSealed (the inlined
path drops view-keyed additional_table_filters).

canSeeViewPlan's definer shortcut compared only the user name, so a session
of the definer limited by the GRANTS of its authentication method saw the
hidden plan; it now uses the same predicate and falls back to the regular
grant checks otherwise.

Tests: new 05616 (each of the six conditions is caught by a build without
it). 05257 runs its Distributed loop as a non-definer and its remote() line
with prefer_localhost_replica = 0 (a local replica runs the plan as the
initiator, the definer); 05407 uses SQL SECURITY NONE; 05331 gains a NONE
twin. Performance test added.

Closes ClickHouse#130316

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

comp-view Logical (non-materialized) views. pr-critical-bugfix 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.

5 participants