Skip to content

Log what runs under a SQL SECURITY DEFINER or NONE view as a child query_log row - #130654

Merged
pufit merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/query-log-sql-security-child-rows-126334
Nov 18, 2026
Merged

pufit merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/query-log-sql-security-child-rows-126334

Conversation

@groeneai

@groeneai groeneai commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126334

Changelog category (leave one):

  • Backward Incompatible Change

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

What a query runs under the identity of a SQL SECURITY DEFINER or NONE view or materialized view is now logged in system.query_log as a child row (is_initial_query = 0, the query's initial_query_id, the definer as user) with the tables, columns, partitions and projections it accessed; the caller's row no longer lists the tables such a materialized view writes. Reads of a serialized query plan record the tables they read. system.user_query_log returns only top-level (is_initial_query = 1) rows of the authenticated matching user. A row policy that exposes system.query_log rows by user (user, initial_user or authenticated_user) should add is_initial_query = 1 to keep the child rows hidden.

Description

On master, the body of a SQL SECURITY DEFINER/NONE view or materialized view runs in a query context of its own. What it accesses is recorded there and never logged, so system.query_log does not show what a query read through such a view. #126334 merges it into the caller's row, which then needs a marker column, reader filters and a default-off server option. This PR implements @ vdimir's alternative (#126334 (comment)): the body is logged as a child row, like a distributed query's shard query.

The first commit is #126334 at b4be48e6; the second replaces its marker, marking sites, reader logic and option. Each caller of getSQLSecurityOverriddenContext that runs something (including DESCRIBE and the analysis of a parameterized view) registers the body's QueryAccessInfo on the enclosing query context (a materialized view only when the insert pushes to it), and executeQuery writes one row per distinct body.

Deviations from the proposal:

  • Transparent views, reads through a materialized view and inserts into one are child rows too: in the caller's row, a transparent body would put partition ids of a key the view need not expose into the grant-free system.user_query_log.
  • analyzer_inline_views (experimental) no longer inlines DEFINER/NONE views, because an inlined body's query context has no owner.
  • 05257_sql_security_view_sealed counts only forwarded rows (distributed_depth > 0), and 05616_sql_security_definer_view_read_by_definer only top-level rows.

Validation: 05616-05618 fail on master and pass here (150/150 randomized runs), 20 one-line mutations each fail them, one more fails test_user_query_log_insecure_cluster_uses_initial_user, and 57 related tests are unchanged apart from those two.


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

Version info

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

groeneai and others added 5 commits November 10, 2026 19:25
This is ClickHouse#126334 at head b4be48e, applied
verbatim as the base of the child-row variant proposed by @ vdimir in
ClickHouse#126334 (comment).

Co-authored-by: Sergey Kuznetsov <[email protected]>
Co-authored-by: vdimir <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ery_log row

The body of a `SQL SECURITY DEFINER` / `NONE` view or materialized view runs in a query
context of its own (`getSQLSecurityOverriddenContext`), and everything it records goes to that
context's `QueryAccessInfo`, which nothing logs. The previous commit (ClickHouse#126334) merges it into
the caller's row, and so needs the `query_access_info_is_hidden` marker, its marking sites, the
reader's marker logic and the `query_log.enable_query_access_info_attribution` option. This
replaces all of that with the design proposed by @ vdimir in
ClickHouse#126334 (comment): the body is logged
as a child row of the query, like the shard query of a distributed query.

- `Context::addSQLSecurityOverriddenBody` registers a body's `QueryAccessInfo` on the enclosing
  query context. It is called where the body context is created: `getViewContext` (a view read),
  `StorageMaterializedView::readImpl` (a read through an MV, logged as `SELECT <columns> FROM
  <target>`), the root of `InsertDependenciesBuilder` (an insert into an MV, logged as `INSERT
  INTO <target>`) and `createSelectInsertContext` (an MV run on INSERT). A body registered again
  with the same view, query tree hash and user is redirected to the first registration, so a
  view planned for every block of an MV insert is one row. The registry is not copied with a
  context.
- `executeQuery` writes one row per registered body after the caller's row at QueryFinish,
  ExceptionWhileProcessing and ExceptionBeforeStart, recursively for nested bodies, and consumes
  the registry: `is_initial_query = 0`, a generated `query_id`, the caller's `initial_query_id`,
  `user` = the definer (empty for NONE), the body's query formatted for logging, and what it
  accessed; no metrics.
- `InsertDependenciesBuilder` records an MV's target and the views its write triggers on the
  context that writes them, so for a DEFINER/NONE MV they are in its child row. INVOKER and
  legacy MVs share the caller's query context, so their rows do not change.
- `analyzer_inline_views` no longer inlines a DEFINER/NONE view (the parallel-replicas bail-out
  becomes unconditional): an inlined body's query context has no owner, and keeping every inlined
  occurrence alive would grow per block inside an MV body. The view is read through `readImpl`,
  whose transparent plan is still merged into the caller's. ClickHouse#126334's switch of the inlined body
  to the caller's query context and its `enable_shared_storage_snapshot_in_query` override are
  reverted with it.

Deviation from the proposal: transparent views, reads through an MV and inserts into an MV are
child rows too. Attributed to the caller, a transparent body would put the partition ids it
selected, of a partition key the view need not expose, into the grant-free
`system.user_query_log`.

`system.user_query_log` keeps ClickHouse#126334's identity check and its `is_initial_query = 1` filter,
which now also hides the child rows. 05257 counted every non-initial row as a query shipped to
another server; it now counts only rows with `distributed_depth > 0`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s child row

A read through a `SQL SECURITY DEFINER` / `NONE` materialized view reads its target with
`storage->read`, which bypasses the planner, so the body's child row named no table or column.
`StorageMaterializedView::readImpl` now records the target and the columns read on the body's
query context, after the body is registered.

- 05617: a read through a DEFINER MV with a `Memory` target, and exact `tables` / `columns` of
  both MV-read child rows.
- 05617: `INSERT INTO mv_definer ... VALUES` runs with `async_insert = 0`. Under an
  `async_insert = 1` profile the insert is flushed by the async-insert queue, whose context has
  current database `default`, so its child rows were outside the test's database filter.
- 05616: a child row logged at `ExceptionWhileProcessing`.
- 05616: `used_row_policies` of a child row (a row policy on the table a DEFINER view reads).
- QueryAnalyzer.cpp: drop the now unused `parallel_replicas_plan_based` declaration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ns of child rows

- test_user_query_log_insecure_cluster_uses_initial_user: a read through the `insecure` cluster reaches n2 as `default` with `initial_user` = the caller, and must not return the caller's top-level `user_query_log` rows.
- 05617: the child rows of reads through a materialized view assert their `partitions` and `databases` exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Delete comments that narrate the new code and condense the rest to standalone invariants; no code change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 3 rounds, 11 findings) plus my own review (7 findings, 1 withdrawn).

# Sev Finding Verdict Evidence / action
1 ❌ The child row of a read through a DEFINER materialized view lists no table or column for the target it reads (StorageMaterializedView::readImpl reads it without the planner) AGREE, fixed @ df37671 the body records the target and its columns
2 ⚠️ 05617 accepts the target from partitions, which masks the missing tables entry, and never reads columns AGREE, fixed @ df37671 exact tables and columns for a MergeTree and a Memory target
3 ⚠️ used_row_policies of a child row is not asserted AGREE, fixed @ df37671 a row-policy case in 05616
3b ⚠️ Child rows have no metrics, but no test asserts it DISAGREE the row starts default-initialized and only the listed fields are set, so no line of the diff sets a metric
4 ⚠️ The fail-closed identity check of system.user_query_log is not exercised AGREE, fixed @ d0485dd a seeded top-level row on n2, read from n1 through the insecure cluster, returns nothing (remote() cannot test it: it sends the address user as initial_user)
5 ⚠️ 05617's INSERT ... VALUES into the view becomes an async insert in the AsyncInsert job, whose flush logs with another current database AGREE, fixed @ df37671 async_insert = 0 on that insert
6 💡 Child rows at ExceptionWhileProcessing are not tested AGREE, fixed @ df37671 a throwIf case in 05616
7 💡 parallel_replicas_plan_based is declared but unused in QueryAnalyzer.cpp AGREE, fixed @ df37671 declaration removed
8 ⚠️ partitions and databases of a child row are not asserted on their own AGREE, fixed @ d0485dd exact partitions and databases of both MV-read child rows
9 ❌ A read through a DEFINER MV whose target access check fails writes no child row, while a view writes one DISAGREE nothing is accessed before the check; a view denied the same way writes a row with empty access sets; the denial and the definer are in the caller's exception row
10 💡 The changelog entry does not mention that analyzer_inline_views no longer inlines DEFINER/NONE views DISAGREE the setting is experimental; the PR description states the change
11 ⚠️ Every DEFINER view in the tests is defined by the caller, so a child row that took the caller's user would pass DISAGREE the SQL SECURITY NONE child row is asserted with an empty user while the caller is default; a row that took the caller's user fails it
12 ⚠️ 05618 would pass if the serialized plan fell back to query text DISAGREE without the resolveStorages.cpp change 05618 fails (shipped_plan 0 0), so the serialize_query_plan = 1 case reaches it
13 💡 The row-policy warning names only initial_user; a policy by user shows child rows to the definer, by authenticated_user to the caller noted, not blocking child rows keep the caller's initial_user, authenticated_user and client info; a system.query_log row policy that should hide them needs is_initial_query = 1

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

Session id: cron:clickhouse-review-slot-8:20261110-230700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: 05616, 05617 and 05618 fail on master (no child rows, the caller's INSERT row lists the MV targets, user_query_log returns secondary rows) and pass with the change.
b Root cause explained? A DEFINER/NONE body runs in its own query context; its QueryAccessInfo is never connected to the caller's query, so executeQuery never logs what the body accessed.
c Fix matches root cause? Yes: each executing caller of getSQLSecurityOverriddenContext registers the body on the enclosing query context, and executeQuery writes it as a child row.
d Test intent preserved / new tests added? 05616/05617 rewritten for child rows, 05618 kept; 05257's shipped-query count narrowed to distributed_depth > 0, reference unchanged.
e Both directions demonstrated? Fail on master, pass here; 19 one-line mutations each fail the check they target (one of them the integration test).
f Fix is general across code paths? View read (sealed or transparent), read through an MV, insert into an MV, MV on INSERT, nested bodies, inlining, and the finish, exception and before-start log paths.
g Fix generalizes across inputs (params/datatypes/wrappers)? DEFINER, NONE, INVOKER, legacy; parameterized views with two argument sets; the same view twice; colliding dotted names; multi-block inserts.
h Backward compatible? (maintainer-approved exception only) Backward Incompatible Change, as #126334, in the design the PR assignee proposed; no setting, format or protocol change.
i Invariants and contracts preserved? The registry holds only QueryAccessInfo, is not copied with a context, is consumed when written, and never holds two access-info mutexes at once; INVOKER rows are master's.

Session id: cron:clickhouse-impl-slot-40:20261110-192400

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b396466]

Summary: ✅


AI Review

Summary

Reviewed PR #130654 at b3964660e72eed9428814c49de7943d7e5da9b45. The change records work performed by SQL SECURITY DEFINER and NONE views as child rows in system.query_log, attributes serialized-plan reads, and restricts system.user_query_log to top-level rows with a consistent caller identity. No unresolved findings. Both previous inline findings are fixed in the current code. The three new stateless regression tests pass in the Fast test report; no local tests were run.

Consumers of the additional log rows reviewed:

  • SystemLogQueue and QueryLogElement::appendToBlock persist them through the existing schema.
  • system.user_query_log excludes child rows and rejects inconsistent forwarded identities.
  • Direct system.query_log readers retain child rows; the documentation explains filtering with is_initial_query = 1.
  • The affected existing test consumers distinguish top-level rows with is_initial_query and forwarded queries with distributed_depth.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes can be tested Allows running workflows for external contributors comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). labels Nov 10, 2026
Comment thread src/Storages/StorageView.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b3964660e with master 204d73c05 (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.

Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits November 11, 2026 01:36
…s child rows

`DESCRIBE TABLE pv(...)` of a `DEFINER`/`NONE` parameterized view analyzes the
substituted body in the view's own context without `only_analyze`, so a scalar
subquery of the body runs under the definer (a `throwIf` in it fires), and
`Context::buildParameterizedViewStorage` runs the scalar subqueries in the
arguments of a table function in the body even in analysis mode
(`EXPLAIN QUERY TREE SELECT * FROM pv(...)`). Neither context was registered, so
neither the caller's row nor a child row listed what they read. Both now
register the body like `StorageView::readImpl` does; a `SELECT` still gets one
child row per body, because the registration of the analysis and of the read
coalesce on view, query hash and user.

The pre-analyzer overload `Context::executeTableFunction(const ASTPtr &)` builds
a parameterized view the same way and now registers it too. No SQL statement
was found to reach that branch (`x IN pv(p = 1)` fails on the unknown
identifier `p` in SELECT, ALTER DELETE/UPDATE, DELETE, CHECK, DEFAULT,
MATERIALIZED and row policies; `IN (SELECT ... FROM pv(...))` and JOIN go
through the analyzer and get child rows), so it has no test.

The "has a query context of its own" check moves into
`Context::addSQLSecurityOverriddenBody`, so call sites need not repeat it.

Found by the AI review of ClickHouse#130654 (r4532409526).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sql-security-child-rows-126334

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
groeneai and others added 2 commits November 15, 2026 18:37
05616_sql_security_definer_view_read_by_definer counts only top-level rows:
the read of a DEFINER view is now also logged as a child row without
metrics, which its query_log probe matched too.

The body of a DEFINER or NONE materialized view is registered where its
chain is attached to the pipeline, not when the view is found as a
dependent. A view skipped for a dropped target
(ignore_materialized_views_with_dropped_target_table = 1) or behind a
storage that does not push on INSERT (Kafka, NATS, RabbitMQ, FileLog)
no longer gets a child row for a body that never ran.

05616 and 05617 cover a NONE materialized view, the target of a nested one,
two distinct views with the same body, a dropped target and an INSERT into
a FileLog table; each child row is joined to its caller by
initial_query_id, and child query ids must be distinct.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In a Replicated database the DDL worker replays every CREATE/DROP of the
test as a secondary query, logged as QueryStart and QueryFinish rows with
is_initial_query = 0 and one query_id. The check counted those rows too, so
05616 and 05617 failed `1 1` -> `1 0` in the DBReplicated jobs. Count only the
non-initial rows of the labelled queries, whose child rows the check is about.

Also say in the system.user_query_log description that a row policy keyed
on any of `user`, `initial_user` or `authenticated_user` exposes child rows:
a child row keeps the caller's `initial_user` and `authenticated_user` and
has the definer as `user`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@pufit pufit self-assigned this Nov 17, 2026
@pufit

pufit commented Nov 17, 2026

Copy link
Copy Markdown
Member

@groeneai please resolve conflicts

…sql-security-child-rows-126334

# Conflicts:
#	src/Interpreters/executeQuery.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

Resolved by merging master in b396466. The only conflict was in executeQuery.cpp with the new query plan logging: the plan is attached to the caller's row, and the child rows are written right after it. 05616, 05617, 05618, 05616_sql_security_definer_view_read_by_definer, 05257 and the query_plan_json tests pass on the merged build.

@pufit pufit 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.

merge after #126334

@pufit
pufit added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 3634df0 Nov 18, 2026
193 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 18, 2026
alexey-milovidov added a commit that referenced this pull request Nov 18, 2026
…and under randomized settings

- Since #130654 the body of a `SQL SECURITY NONE` view
  is logged as a child `query_log` row with the same `log_comment`; select only `is_initial_query` rows.
- Pin `merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 0`:
  the CI diagnosis named it as the culprit for one extra row read from `t_outer_sv`.
- Disable parallel replicas: with them `05618_clone_recovered` did not take the recovery path.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130374&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20sequential)
PR: #130374

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-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). pr-backward-incompatible Pull request with backwards incompatible changes 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.

4 participants