Skip to content

Check SHOW COLUMNS before EXPLAIN SYNTAX inlines a parameterized view definition - #129074

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:explain-syntax-parameterized-view-show-columns
Nov 4, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:explain-syntax-parameterized-view-show-columns

Conversation

@groeneai

@groeneai groeneai commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128992 (comment)
Related: #129106

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 EXPLAIN SYNTAX and EXPLAIN AST optimize = 1 showing the definition of a parameterized view to a user without the SHOW COLUMNS privilege on the view, which SHOW CREATE requires. For such a user the view call is now printed as written.

Description

On 26.8.34.13 and 26.10.2.103, a user refused SHOW CREATE on a parameterized view still gets its whole definition, literals included, from EXPLAIN SYNTAX SELECT * FROM db.pv(p = 1). Reported by @ PedroTadim in the review of #128992.

ExpandParameterizedViewsMatcher::tryExpandTableExpression replaces the call with the view's stored query before any analysis and checks no access. With the default run_query_tree_passes = 0 nothing checks access afterwards; with run_query_tree_passes = 1 or EXPLAIN AST optimize = 1 only the tables behind the view are checked.

The definition is now read only if the user has SHOW COLUMNS on the view, the privilege SHOW CREATE, system.tables.create_table_query and DESCRIBE pv(...) require. Otherwise the call is left as written, as for a SQL SECURITY DEFINER view, so by default an inaccessible view prints like an unknown name. The check uses the resolved storage, not the parsed name. A user with only column-level grants on the view no longer sees the expansion, which matches SHOW CREATE.

The analyzer's resolution of the call comes from other code and is not changed here: it still exposes the view's column list (for example in EXPLAIN QUERY TREE for a SQL SECURITY DEFINER view) and, when analyzing the definition fails, the definition in the error message, also for a plain SELECT. #129106 fixes both for a user with no grant on the view.

The new test covers EXPLAIN SYNTAX with and without the database name, run_query_tree_passes = 1 and EXPLAIN AST optimize = 1 for a user without SHOW COLUMNS, a user with only SELECT(x) on the view, and the expansion with SHOW COLUMNS or SELECT on the view. The six checks without SHOW COLUMNS fail on master and pass with the fix (50/50 randomized runs).


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

Version info

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

… definition

`ExpandParameterizedViewsMatcher::tryExpandTableExpression` replaced a
parameterized view call with the view's stored query before any analysis and
without any access check. A user refused `SHOW CREATE` on the view (no
`SHOW COLUMNS`) therefore read the whole definition, literals included, from
`EXPLAIN SYNTAX` or `EXPLAIN AST optimize = 1`. With the default
`run_query_tree_passes = 0` nothing checks access afterwards; with
`run_query_tree_passes = 1` only the tables behind the view are checked.

Require `SHOW COLUMNS` on the view at the point the definition is read, the
privilege `SHOW CREATE`, `system.tables.create_table_query` and
`DESCRIBE pv(...)` already require, and otherwise leave the call as written,
like the existing `SQL SECURITY DEFINER` branch. Not throwing keeps an
inaccessible view printing like an unknown name in the default mode, as
`DESCRIBE` does. The check is keyed on the resolved storage rather than the
parsed name.

Reported by PedroTadim in the review of ClickHouse#128992.

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

groeneai commented Nov 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; 2 findings) plus my own review (2 findings);
bounded: 1 full pass + 1 fix round + 1 delta recheck (0 new findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test's no-SHOW COLUMNS checks only counted the definition literal, so they also passed when the statement threw AGREE, fixed @ 9c8bf19 each check now requires success and asserts the call is printed; all five fail on master
2 💡 Critical Bug Fix suggested as the category DISAGREE that category is used on a maintainer's request; Bug Fix holds, the disclosure reproduces on 26.8.34.13 and 26.10.2.103
3 💡 Commit message said an inaccessible view is indistinguishable from an unknown name AGREE, fixed @ 9c8bf19 qualified to the default mode: with run_query_tree_passes = 1 the analyzer still resolves the view
4 💡 The analyzer's resolution of the call still exposes the view's column list noted other code and another kind of information; not changed here, stated in the description

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261103-182000

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. As a user with no grants, EXPLAIN SYNTAX oneline = 1 SELECT * FROM pv(n = 3) prints the view body with its literal every time: master, 26.8.34.13 and 26.10.2.103.
b Root cause explained? ExpandParameterizedViewsMatcher::tryExpandTableExpression splices the view's stored query into the explained AST with no access check; nothing after it checks the view (default) or checks only the tables behind it (run_query_tree_passes = 1, EXPLAIN AST optimize = 1).
c Fix matches root cause? Yes. SHOW COLUMNS on the view is required at the point the definition is read, the same privilege as SHOW CREATE; no whole-query check.
d Test intent preserved / new tests added? New test: four shapes for a user without SHOW COLUMNS, each of which must succeed and print the call, not the definition, plus a positive control that the expansion happens once it is granted.
e Both directions demonstrated? Yes. On master every no-grant line prints the definition and no call; with the fix the test passes, 50/50 randomized runs.
f Fix is general across code paths? Yes. This is the only place EXPLAIN reads a parameterized view definition; checked INSERT ... SELECT, JOIN, IN, CTE, alias and nested views on both binaries. SHOW CREATE, DESCRIBE pv(...) and system.tables already use the same check.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for names (plain, qualified, backquoted, aliased) and grants (table, column, database level). Data types: N/A, the check does not depend on them.
h Backward compatible? (maintainer-approved exception only) Yes. No setting. Users with SHOW COLUMNS see the same output; others see the call as written, as for a SQL SECURITY DEFINER view. Column-level-only grants lose the expansion, matching SHOW CREATE.
i Invariants and contracts preserved? Yes. The early return leaves the table expression untouched, like the three existing ones; isGranted does not throw and changes no state.

Session id: cron:clickhouse-impl-slot-5:20261103-180900

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @pufit @vdimir, could you review this and add the can be tested label so CI runs? EXPLAIN SYNTAX inlined a parameterized view's definition with no access check; now tryExpandTableExpression reads the definition only if the user has SHOW COLUMNS on the view, the privilege SHOW CREATE needs, and otherwise leaves the call as written.

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5351082]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, 2/4) FAIL
test_read_temporary_tables_on_failure/test.py::test_different_versions FAIL cidb IGNORED

AI Review

Summary

This PR adds a SHOW COLUMNS gate before EXPLAIN SYNTAX / EXPLAIN AST optimize = 1 inline a parameterized view body, and the new stateless test covers the successful no-grant / grant cases. The main disclosure is still reachable, though: once those entrypoints continue into the analyzer (run_query_tree_passes = 1 and the optimize = 1 path), they can still resolve the parameterized view through Context::buildParameterizedViewStorage and expose the stored definition in analysis exceptions, so I cannot approve it yet.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterExplainQuery.cpp:215, src/Analyzer/Resolve/QueryAnalyzer.cpp:5549, src/Interpreters/Context.cpp:3836] The new SHOW COLUMNS check only protects the AST-side pre-analysis rewrite. EXPLAIN SYNTAX run_query_tree_passes = 1 and EXPLAIN AST optimize = 1 still enter QueryAnalyzer::resolveTableFunction, which calls Context::buildParameterizedViewStorage, clones the hidden view definition, and analyzes it via getSampleBlock without any equivalent privilege gate. If that analysis throws (for example an invalid Identifier parameter in the view body), the exception still prints the full inlined definition, so the exact disclosure this PR claims to fix remains reachable.
    Suggested fix: enforce the same SHOW_COLUMNS check in the analyzer path before buildParameterizedViewStorage reads or analyzes the view definition, and fail closed so these entrypoints leave the call opaque to unauthorized users. Then add a regression case that exercises EXPLAIN SYNTAX run_query_tree_passes = 1 and EXPLAIN AST optimize = 1 with an invalid Identifier parameter and asserts the error no longer contains the view body.
Tests
  • ⚠️ The new stateless test covers only successful analysis. Add the smallest negative case above to prove the exception path is closed, because the remaining leak is specifically in the analyzer failure path.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: close the analyzer-side buildParameterizedViewStorage bypass for unauthorized users, and add one regression test that proves run_query_tree_passes = 1 / optimize = 1 errors no longer disclose the parameterized view definition.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. can be tested Allows running workflows for external contributors labels Nov 3, 2026
Comment on lines +217 to +218
if (!query_context->getAccess()->isGranted(AccessType::SHOW_COLUMNS, view_id.getDatabaseName(), view_id.getTableName()))
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ [P1] Protect the definition when the analyzer throws

Returning here leaves the call for subsequent analysis. With run_query_tree_passes = 1 or EXPLAIN AST optimize = 1, QueryAnalyzer::resolveTableFunction still reaches Context::buildParameterizedViewStorage, which clones the hidden definition and analyzes it through getSampleBlock without this privilege check. An analysis exception can therefore disclose the entire query, including its literals.

Reproduced on this head's Fast test binary: extend this test's view with ORDER BY {sort:Identifier}, keep only SELECT on base for the user, and execute:

EXPLAIN SYNTAX run_query_tree_passes = 1
SELECT * FROM pv(n = 3, sort = 'missing');

Although SHOW CREATE TABLE pv is denied, the exception includes Unknown expression identifier followed by In scope SELECT x, s FROM default.review_base WHERE (x < _CAST(3, 'UInt32')) AND (s != 'definition_marker') ORDER BY missing ASC (the probe used review_base as the base table). EXPLAIN AST optimize = 1 leaks the same definition.

Please protect the subsequent inner-analysis path as well, so an inaccessible view's definition cannot appear in exceptions, and add a negative test for both modes with an invalid Identifier parameter.

@PedroTadim PedroTadim Nov 4, 2026 •

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.

@groeneai should you look into this in another PR?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, it is in my #129106, which checks access to the view in Context::buildParameterizedViewStorage before the definition is analyzed. Measured on a build with both PRs, for this repro (SELECT on the base table only, sort = 'missing'): EXPLAIN SYNTAX run_query_tree_passes = 1 and EXPLAIN AST optimize = 1 return ACCESS_DENIED, while master quotes the definition in both.

These two modes need both PRs, since without this one the body is inlined before the analyzer reaches the check. So after this PR is merged, I'll add this case for both modes to the #129106 test, together with the 05493 reference update it then needs (the two base-table-only arms for these modes become ACCESS_DENIED).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 6bd2b0a: 05497 now runs this repro (ORDER BY {secret_sort:Identifier}, secret_sort = 'missing', SELECT on the base table only) under EXPLAIN SYNTAX run_query_tree_passes = 1 and EXPLAIN AST optimize = 1, and both return ACCESS_DENIED; the two 05493 base-table-only arms for these modes now expect ACCESS_DENIED too.

@PedroTadim PedroTadim self-assigned this Nov 3, 2026
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai

Thanks for following up on this. The fix is in the right place and I think it is complete for this path:

  • Same check as its siblings. SHOW CREATE checks SHOW_COLUMNS on the table, and InterpreterDescribeQuery uses the same isGranted(SHOW_COLUMNS, ...) before it substitutes a parameterized view's query.
  • Nothing is derived before the check. Each earlier return in tryExpandTableExpression, for an unknown name, a table that is not a parameterized view, or a DEFINER view, leaves the call as written, just like the new one. So the output does not tell a user without the grant whether the view exists or what its security type is.
  • Both callers are covered. EXPLAIN SYNTAX and EXPLAIN AST optimize = 1 both go through this visitor. Secrets inside an expanded body are still hidden by canDisplaySecrets on both.
  • Users who can query the view are not affected. SHOW_COLUMNS is implied by any column-level flag, so a user with SELECT on the view still sees the expansion.

One request for the test. The positive case grants SHOW COLUMNS directly, but the usual way to get access to a view is GRANT SELECT ON db.pv. Could you add that case, which should still expand, and GRANT SELECT(x) ON db.pv, which should not, as the description says? Then the test pins both sides of the implied grant, not only the explicit privilege.

tryExpandTableExpression is also changed by #128992, which adds the dotted-name fallback lookup. Whichever lands second needs a small merge, and the check has to stay after the final tryGetTable.

The AST fuzzer (amd_debug, targeted, old_compatibility) failure is the Inconsistent AST formatting round-trip check in executeQuery, on an EXPLAIN SYNTAX with an APPLY transformer. That check runs before the interpreter, so it is not from this PR.

@clickhouse-gh

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 535108291 with master 81120655d (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 014fdaa27; 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.

Compile time of recompiled translation units

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

Job report

`SELECT` on the view implies `SHOW COLUMNS` on it, so the definition is
still expanded. A column-level `SELECT(x)` does not, so the call is
left as written, as for `SHOW CREATE`.

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

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Added both in 4420898: with GRANT SELECT ON db.pv the definition is expanded, and with only GRANT SELECT(x) ON db.pv the call stays as written. The SELECT(x) case fails on master like the other cases without SHOW COLUMNS; 50/50 randomized runs pass with the fix.

Noted for #128992: whichever PR lands second gets the merge, with the check kept after the final tryGetTable.

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4420898

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
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this PR (it changes only how EXPLAIN SYNTAX expands a parameterized view): all 100 <Error> lines are retries of one mutation failing with Unexpected const virtual column: _table, the deliberately failing mutation of 04510_mutation_query_plan_only_virtual_columns. Its table was still detached when the stress phase ended, so the kill step did not see the mutation and the upgraded server retried it. The same error appeared on 3 PRs in 30 days #124532 (mine, open)
Mergeable Check, PR praktika rollups of the row above #124532 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261104-003004

return;

/// The inlined body is the view definition, which needs `SHOW COLUMNS` on the view, as `SHOW CREATE` does.
const auto view_id = storage->getStorageID();

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.

@groeneai does other EXPLAIN statements have similar issues?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yes. Anything that goes through the analyzer still shares the unresolved path: EXPLAIN QUERY TREE via src/Interpreters/InterpreterExplainQuery.cpp:1187, EXPLAIN PLAN via src/Interpreters/InterpreterExplainQuery.cpp:1239, EXPLAIN PIPELINE via src/Interpreters/InterpreterExplainQuery.cpp:1321, and EXPLAIN ESTIMATE via src/Interpreters/InterpreterExplainQuery.cpp:1389. They all end up in QueryAnalyzer::resolveTableFunction (src/Analyzer/Resolve/QueryAnalyzer.cpp:5549) -> Context::buildParameterizedViewStorage (src/Interpreters/Context.cpp:3836), so this patch only closes the AST-side pre-analysis rewrite.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, on the analyzer side. Measured on master (4f752f7) for a user without SHOW COLUMNS on the view (no grants, or SELECT on the table it reads):

  • EXPLAIN SYNTAX and EXPLAIN AST optimize = 1 print the definition of an INVOKER view. This PR.
  • EXPLAIN QUERY TREE, EXPLAIN SYNTAX run_query_tree_passes = 1 and EXPLAIN AST optimize = 1 print the columns of a DEFINER view to a user with no grants at all.
  • EXPLAIN QUERY TREE, PLAN, PIPELINE, ESTIMATE and a plain SELECT quote the definition in the error when its analysis fails. For example, ORDER BY {sort:Identifier} called with sort = 'missing' gives UNKNOWN_IDENTIFIER with In scope SELECT x, s FROM db.base WHERE ... ORDER BY missing ASC. For an INVOKER view, the ACCESS_DENIED of a user with no grants names the table the view reads.

All of these come from the analyzer building the view in Context::buildParameterizedViewStorage without checking access to the view. My #129106 adds that check, plus the #117979 column check in QueryAnalyzer::resolveTableFunction. On a build with both PRs, every case above returns ACCESS_DENIED or prints the call as written.

One case remains. A user with only a column grant, such as SELECT(x) ON db.pv, can run the view, and a failing analysis still quotes the definition, in a plain SELECT too. The description of #129106 states this. Ordinary views and EXPLAIN AST without optimize show nothing.

@clickhouse-gh clickhouse-gh Bot added comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

The CI failure is unrelated

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 4, 2026
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5351082

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
Integration tests (arm_binary, 2/4) / test_read_temporary_tables_on_failure/test.py::test_different_versions not from this PR (it changes only how EXPLAIN SYNTAX expands a parameterized view): DID NOT RAISE QueryRuntimeException. The test killed the client of the query holding the only max_concurrent_queries_for_user slot, and the server now cancels such a query, so the slot was free too early. It failed 105 times on master between 2026-11-03 22:57 and 2026-11-04 12:49 UTC and on 42 other PRs. #129151 fixed the test at 12:34 UTC and master has passed it since; the tested merge commit predates that fix #129151 (mine, merged)
PR praktika rollup of the row above #129151 (mine, merged)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261104-190006

Merged via the queue into ClickHouse:master with commit 086c23e Nov 4, 2026
183 of 185 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 5, 2026
… and update 05493

With `ORDER BY {sort:Identifier}` and `sort = 'missing'`, the analysis error under
`EXPLAIN SYNTAX run_query_tree_passes = 1` and `EXPLAIN AST optimize = 1` quoted the view
definition to a user with SELECT on the base table only. Since ClickHouse#129074 these modes no longer
inline the view for such a user and reach the check in `buildParameterizedViewStorage`, so the
two base-table-only analyzer arms of 05493 now get ACCESS_DENIED.

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

can be tested Allows running workflows for external contributors comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. 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.

3 participants