Skip to content

Substitute query parameters in row policy filters and reject unsubstituted Identifier parameters - #122688

Merged
PedroTadim merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-unsubstituted-identifier-query-parameters
Oct 22, 2026
Merged

PedroTadim merged 9 commits into
ClickHouse:masterfrom
groeneai:fix-unsubstituted-identifier-query-parameters

Conversation

@groeneai

@groeneai groeneai commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix query parameters in the filter of CREATE ROW POLICY and ALTER ROW POLICY being stored unsubstituted: a {db:Identifier} table qualifier was resolved in the current database of the query reading the table, and a value parameter made every read of the table fail. The parameters are now substituted when the policy is created, and an Identifier query parameter that reaches a filter unsubstituted (for example in additional_table_filters) fails with UNKNOWN_QUERY_PARAMETER.

Description

On 26.8, CREATE ROW POLICY p ON t USING k IN (SELECT k FROM {db:Identifier}.keys) with param_db set stores the
placeholder, so each reader's current database decides which keys filters the rows, and
ALTER ROW POLICY p ON t USING k > {v:UInt64} makes every read of t fail with UNKNOWN_QUERY_PARAMETER.

Found by Stress test (amd_msan): the AST fuzzer put {fuzz_param_0:Identifier} into the row policy of
05257_memory_prewhere_global_in_sets_built_in_place, and the next read aborted with
Logical error: '!part.empty()' (STID 2508-3010): report.

Two defects:

  • ASTCreateRowPolicyQuery keeps its filters outside children, and ReplaceQueryParameterVisitor had no case for
    them. They are now visited explicitly there and in QueryParameterVisitor (parameter discovery of HTTP handlers).
    They stay out of children on purpose: a filter is evaluated later, in the reading query's context, and the generic
    DDL walkers would rewrite it (ON CLUSTER replaces currentDatabase() with the initiator's
    database).
  • QueryTreeBuilder dropped the parameter of an unsubstituted {x:Identifier} and built an identifier with an empty
    part. Text that never meets the visitor (stored policies, additional_table_filters, additional_result_filter)
    reached it, and converting the node back to AST aborted debug builds. It now throws UNKNOWN_QUERY_PARAMETER, as it
    already did for value parameters.

CREATE MASKING POLICY keeps its UPDATE and WHERE expressions outside children too, and both visitors now visit
them. It runs only in ClickHouse Cloud: the tests check the error for an unset parameter and the handler binding.

A policy stored by an older version with a parameter in its filter still loads (the load-time check of access entities does not look into policy expressions) and fails on read with UNKNOWN_QUERY_PARAMETER; recreate it with the parameter set.

Tests: 05291 (policies, filter settings) and 05292 (HTTP handler binding) fail on master.


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

Version info

  • Merged into: 26.11.1.505-master (included in 26.11 and later)
  • Backported to: 26.10.2.76, 26.9.25.13, 26.8.34.11

groeneai and others added 2 commits September 28, 2026 12:59
ASTCreateRowPolicyQuery keeps its filters outside `children`, and
ReplaceQueryParameterVisitor had no case for them, so CREATE / ALTER ROW
POLICY neither substituted nor rejected a query parameter in a USING
clause and stored the placeholder. A stored `{db:Identifier}.keys` then
read `keys` from the reader's current database, a value parameter made
every read of the table fail with UNKNOWN_QUERY_PARAMETER, and an unset
parameter was accepted.

Visit the filters explicitly in ReplaceQueryParameterVisitor, writing a
replaced top-level parameter back into `filters`, and in
QueryParameterVisitor, so an HTTP handler whose query is CREATE / ALTER
ROW POLICY also discovers and binds the filter parameters.

The filters stay out of `children` on purpose: a filter is evaluated when
a table is read, in the reading query's context. Registering them as
children exposes a stored filter to the generic DDL rewriters, e.g.
AddDefaultDatabaseVisitor::visitDDL of ON CLUSTER, which replaces
`currentDatabase()` with the initiator's database, and the create-time
normalizers of executeQuery (construction settings, UNION / EXCEPT modes,
WITH propagation).

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

Text parsed outside executeQuery never meets ReplaceQueryParameterVisitor:
row policy filters stored by an older version or defined in users.xml,
additional_table_filters, additional_result_filter,
parallel_replicas_custom_key. An `{x:Identifier}` there reached
QueryTreeBuilder, which dropped the parameter and built a name with an
empty part. Resolution then read a table from the current database or
failed with a misleading error, and any error message that converted the
node back to AST hit the `!part.empty()` assertion of ASTIdentifier, so
debug and sanitizer builds aborted (Stress test (amd_msan), STID 2508-3010).

Throw UNKNOWN_QUERY_PARAMETER, like the builder already does for an
unsubstituted value parameter, wherever it turns an identifier that a
parameter-capable parser produces into an analyzer name.

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 Sep 28, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 finding) and my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A top-level AS {a:Identifier} in a row policy filter passes the top-level alias check, gets resolved by the new traversal and is persisted as a top-level alias that reload rejects DISAGREE The filter is parsed by ParserExpression, whose top layer accepts no alias (ExpressionLayer is Layer(false, false)), so USING k AS {a:Identifier} is a syntax error. A parenthesized alias goes through Layer::insertAlias, which never sets parametrised_alias; only ParserWithOptionalAlias does, for nested list elements. Stored and fuzzed text is formatted first, and formatting drops parametrised aliases.
2 💡 An unsubstituted parametrised alias inside a filter setting is still ignored by QueryTreeBuilder noted No empty identifier is built, nothing aborts, and stored policy text cannot carry one. Not changed.
3 💡 Two of the ten builder sites (ASTTableIdentifier in buildExpression, the list of a qualified COLUMNS(...)) have no test line noted Same helper as the eight tested sites.
4 💡 CREATE MASKING POLICY keeps its expressions outside children too noted Not executable in this build, so not reproducible here; mentioned in the description.

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

Session id: cron:clickhouse-review-slot-11:20260928-134400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master, one clickhouse local file per case: a row policy USING k IN (SELECT k FROM keys LEFT ARRAY JOIN 'abc', {x:Identifier}) then SELECT * FROM t, or one SELECT with that text in additional_table_filters / additional_result_filter / COLUMNS({x:Identifier}), aborts with Logical error: '!part.empty()' on every run. SET param_db = 'db_a'; CREATE ROW POLICY ... {db:Identifier}.keys reads keys from the reader's current database on every run, also on 26.8.10.6 and 26.3.33.24.
b Root cause explained? ASTCreateRowPolicyQuery keeps its filters outside children, so ReplaceQueryParameterVisitor never substituted them and CREATE / ALTER ROW POLICY stored the placeholder. When stored text (or a filter setting) is parsed again, {x:Identifier} is an ASTIdentifier with an empty name part and the parameter as a child; QueryTreeBuilder read only the name parts and built an empty-part identifier, whose conversion back to AST trips the ASTIdentifier assertion.
c Fix matches root cause? Yes. The filters are substituted where every DDL substitutes its parameters (the visitor), and discovered for HTTP handlers in QueryParameterVisitor; the query tree builder rejects an unsubstituted Identifier parameter with UNKNOWN_QUERY_PARAMETER, as it already did for value parameters. No guard at the assertion, no setting.
d Test intent preserved / new tests added? New 05291 (policy substitution incl. a whole-filter parameter and ALTER, unset parameters rejected, nine filter-setting placements rejected) and 05292 (an HTTP handler whose query is CREATE ROW POLICY binds the filter parameter). Both fail on master.
e Both directions demonstrated? Yes, Build-ID-checked binaries: master fails both tests; the fix passes both, 100/100 in 50 randomized runs each. Without the builder change 05291 aborts on its first filter-setting line; without the visitor change it fails at the first policy read; passing a copy of the filter pointer to the visitor reddens only the whole-filter line; removing the discovery reddens only the handler test.
f Fix is general across code paths? All 10 builder sites fed by parameter-capable parsers are covered. Registering the filters as children instead was implemented and measured: ON CLUSTER then stored currentDatabase() as the initiator's database (wrong rows for other readers) and four create-time normalizers rewrote stored filters. With the explicit visits the stored text of those cases is byte-identical to master.
g Fix generalizes across inputs (params/datatypes/wrappers)? Value and Identifier parameters; a parameter as the whole filter; table qualifier, table, column, lambda argument, COLUMNS, qualified matchers, EXCEPT, ARRAY JOIN; set and unset; CREATE, ALTER, ON CLUSTER and HTTP handler.
h Backward compatible? (maintainer-approved exception only) No setting, format or storage change. CREATE / ALTER ROW POLICY with an unset parameter now fails instead of storing an unusable policy. A policy stored by an older version with a parameter in its filter now fails on read with UNKNOWN_QUERY_PARAMETER (measured); recreating it with the parameter set fixes it.
i Invariants and contracts preserved? The filters stay out of children, so the parser, clone(), SHOW CREATE, the fuzzer and every DDL walker see what they see on master; a replaced top-level parameter is written back through the entry's own pointer; the stored filter differs from master only by the substitution.

Session id: cron:clickhouse-impl-slot-5:20260928-124800

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2a51350]

Summary: ✅


AI Review

Summary

This PR substitutes query parameters in row-policy filters and masking-policy expressions, discovers them for HTTP handlers, and rejects unsubstituted Identifier parameters during query-tree construction while preserving legacy policy loading. The earlier review findings are addressed in the current code; no new actionable findings remain.

Final Verdict

Status: ✅ Approve. Both added regression tests passed in the PR's Fast test report. No further changes are required by this review.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 28, 2026
@groeneai
groeneai requested review from novikd and vitlibar September 28, 2026 14:56
@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 28, 2026
ASTCreateMaskingPolicyQuery keeps its UPDATE assignments and WHERE
condition outside `children`, like the row policy filters, so
ReplaceQueryParameterVisitor and QueryParameterVisitor skipped them: a
query parameter there reached the interpreter unsubstituted
(`UPDATE k = {v:UInt64}` with `param_v` set), and an HTTP handler whose
query is CREATE MASKING POLICY did not bind it from the request.

Visit both members explicitly in both visitors, as for the row policy
filters. Masking policies are executable only in ClickHouse Cloud, so the
tests check what this build can observe: an unset parameter in UPDATE or
WHERE now fails with UNKNOWN_QUERY_PARAMETER instead of
SUPPORT_IS_DISABLED, and a handler binds the parameter (a value that does
not parse fails with BAD_QUERY_PARAMETER).

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

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 2a51350610a04596f8e560385e52bc45a64b6b11 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

The same unsubstituted placeholder aborted two more Stress test runs today on unrelated PRs, through a reader the description does not mention: a row policy on a Merge child, analyzed by ReadFromMerge::RowPolicyData (TreeRewriter -> scalar subquery -> QueryTreeBuilder).

I checked this route with the amd_debug build of beaf1238 and a master debug build, reading a Merge table whose child has USING x <= (SELECT max(v) FROM lim ANY INNER JOIN remote('127.0.0.1', view(SELECT 1 AS d FROM {x:Identifier} AS l)) AS r ON 1):

  • master: Logical error: '!part.empty()', the same frames as the amd_tsan run.
  • this PR: the CREATE ROW POLICY fails with UNKNOWN_QUERY_PARAMETER, and when the policy was stored by the master build first, the read fails with UNKNOWN_QUERY_PARAMETER instead of aborting.

Comment thread src/Parsers/QueryParameterVisitor.cpp Resolved
The load-time check `checkAccessEntityHasNoQueryParameters` uses
`analyzeReceiveQueryParams`, which now also visits row policy filters and
masking policy expressions. A row policy stored by an older version with an
unsubstituted parameter in its filter (`USING k = {x:UInt64}`) was then
rejected while loading the access storage:

- on a normal restart every query of every user failed with
  INCORRECT_ACCESS_ENTITY_DEFINITION, because the row policy cache reads all
  policies;
- on a rebuild of the lists (`need_rebuild_lists.mark`, SYSTEM RELOAD USERS)
  the policy was skipped and dropped from the lists, so the rows it hid
  became readable.

Skip policy definitions in that check, as before: such a policy loads again
and reading its table fails with UNKNOWN_QUERY_PARAMETER.

Found by the AI review of ClickHouse#122688 after the merge with ClickHouse#109696.

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

clickhouse-gh Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 3c030114-72df-4bb5-ac28-5cb82fd1a0f8
  • MIRAI run: 5e3855bd-7b2d-47fb-9ef6-ae8aaac5fb6f
  • PR check IDs:
    • clickbench_929439_1791755555
    • clickbench_929445_1791755555
    • clickbench_929451_1791755556
    • tpch_adapted_1_official_929462_1791755555
    • tpch_adapted_1_official_929475_1791755555
    • tpch_adapted_1_official_929511_1791755555

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai at this point you can review where query parameters are not substituted in the remaining statements

EXPECT_THROW(deserializeAccessEntity("ATTACH ROLE r1; ATTACH GRANT SELECT ON *.* TO {g:Identifier};"), Exception);
}

TEST(AccessEntityIO, LoadsPolicyWithQueryParameterInExpression)

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 there is a sql test, no need for this

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.

Removed in 94987e5.

@PedroTadim
PedroTadim enabled auto-merge October 17, 2026 19:32
@PedroTadim

Copy link
Copy Markdown
Member

The 26.10 CI needs this, although the issue happens in 26.3. Backporting to 26.8 for now, later to other release branches if needed.

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 22, 2026
Merged via the queue into ClickHouse:master with commit fed910c Oct 22, 2026
179 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 Oct 22, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 22, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 22, 2026
Backport #122688 to 26.10: Substitute query parameters in row policy filters and reject unsubstituted `Identifier` parameters
PedroTadim added a commit that referenced this pull request Oct 22, 2026
Kept only the delta of #122688: `checkAccessEntityHasNoQueryParameters` (from "Support query parameters in user and
role identifiers") and `getColumnAliasNames` are not on 26.8, so the hunk editing the former is dropped and only
`throwIfQueryParameter` is added to `QueryTreeBuilder.cpp`.

#122688

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Oct 22, 2026
Kept only the delta of #122688: `checkAccessEntityHasNoQueryParameters` (from "Support query parameters in user and
role identifiers") and `getColumnAliasNames` are not on 26.9, so the hunk editing the former is dropped and only
`throwIfQueryParameter` is added to `QueryTreeBuilder.cpp`.

#122688

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse added a commit that referenced this pull request Oct 22, 2026
…ilters and reject unsubstituted `Identifier` parameters
robot-clickhouse added a commit that referenced this pull request Oct 22, 2026
…ilters and reject unsubstituted `Identifier` parameters
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 22, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 22, 2026
Backport #122688 to 26.9: Substitute query parameters in row policy filters and reject unsubstituted `Identifier` parameters
clickhouse-gh Bot added a commit that referenced this pull request Oct 22, 2026
Backport #122688 to 26.8: Substitute query parameters in row policy filters and reject unsubstituted `Identifier` parameters
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 18, 2026
`ReplaceQueryParameterVisitor` substitutes `{ts:DateTime64(3, 'UTC')}` as
`_CAST(<DecimalField>, 'DateTime64(3, \'UTC\')')`. `ASTLiteral` prints a
`DecimalField` as a quoted decimal string, so once the substituted query is
formatted and parsed again (a row policy filter, a column DEFAULT, a
Replicated mutation, ON CLUSTER DDL) the value becomes
`_CAST('20240101', 'DateTime64(3, \'UTC\')')`: a cast from String, which parses
date-time text. With `cast_string_to_date_time_mode = 'best_effort'` an
8-digit number is read as YYYYMMDD, so a row policy `ts <= {ts:DateTime64(...)}`
with a value before 1973-03-03 lets through rows it must hide, a negative value
fails CANNOT_PARSE_DATETIME, and a `Time64` value (decimal seconds are not
`Time64` text) fails CANNOT_PARSE_TEXT on every read. Since ClickHouse#122688 row policy
filters are stored with the parameters substituted, so this is reachable on
26.8+.

Build the substituted AST for any type containing DateTime64 / Time64 with
`columnConstantToExactLiteralAST`, the helper added by ClickHouse#95055 for exactly this
serialization problem in `ConstantNode::toASTImpl` and `ReadFromRemote`: it
writes `_CAST(_CAST('<ticks>', 'DecimalNN(S)'), '<type>')` for every leaf,
also inside Array / Tuple / Map / Nullable, with a carrier wide enough for
DateTime64(9). The parameter visitor runs on the AST before any query tree
exists, so it was the one serialization site that helper did not cover.

Casting from date-time text instead (adding the types to `needCastFromString`)
was rejected: local date-time text is ambiguous across DST overlaps, measured
one hour off for '1730615400.5' as DateTime64(1, 'America/New_York') even in
the query itself. Plain Decimal parameters already round-trip and are left
unchanged, as are Variant / Dynamic / Object and custom-serialization types,
which keep the cast-from-String path.

Already stored broken policies and defaults are not repaired; re-run the
ALTER with the parameter.

Closes ClickHouse#127330

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. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants