Skip to content

Do not skip access checks of a user query executed as a nested query - #119848

Merged
Manerone merged 10 commits into
masterfrom
sec-user-initiated-access-checks
Sep 17, 2026
Merged

Manerone merged 10 commits into
masterfrom
sec-user-initiated-access-checks

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

InterpreterParallelWithQuery::executeSubquery, InterpreterExecuteAsQuery::execute and the local execution path of the QueryRunner table engine re-execute a user-supplied query with QueryFlags{ .internal = true }. That flag reaches InterpreterCreateQuery, whose getRequiredAccess returns an empty set of required privileges for internal queries, so no authorization check ran for CREATE subqueries. An empty access set also means checkAccessImpl is never reached, which defeats the readonly and allow_ddl settings on the same path.

A user holding only GRANT SELECT on a single database was denied a direct CREATE TABLE, but the same statement wrapped in PARALLEL WITH succeeded. EXECUTE AS was affected the same way, which inverts its contract: the impersonated statement was checked against the privileges of neither party. For a QueryRunner table the queued query text comes from whoever inserted it, so a user with only INSERT on such a table could queue a CREATE and have it executed regardless of the privileges of the principal the job runs as.

The flag cannot simply be cleared for these subqueries: internal also keeps a nested query out of the ProcessList and deliberately leaves it without a SpanHolder so that the spans already on the stack finish in the correct order, EXECUTE AS relies on it to get raw blocks from the inner executeQuery, and it is what marks QueryRunner jobs with is_internal = 1 in system.query_log. So the queries stay internal and the authorization decision stops depending on that flag: the new QueryFlags::user_initiated marks a query whose text was written by the user, and InterpreterCreateQuery is told that a query is server-initiated only when internal is set and user_initiated is not.

This follows the approach of the internal patch prepared by @Manerone, and adds the tests for the three entry points.

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

Fixed PARALLEL WITH, EXECUTE AS and the QueryRunner table engine skipping the access checks of the CREATE statements they execute, which allowed creating tables and databases without the corresponding privileges, and defeated the readonly and allow_ddl settings.

🤖 Generated with Claude Code

Closes: #119600


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

Version info

  • Merged into: 26.10.1.39 (included in 26.10 and later)
  • Backported to: 26.9.1.1600, 26.8.7.16, 26.7.11.12, 26.6.9.18, 26.3.33.108

`InterpreterParallelWithQuery::executeSubquery`,
`InterpreterExecuteAsQuery::execute` and the local execution path of the
`QueryRunner` table engine re-execute a user-supplied query with
`QueryFlags{ .internal = true }`. That flag reaches `InterpreterCreateQuery`,
whose `getRequiredAccess` returns an empty set of required privileges for
internal queries, so no authorization check ran for `CREATE` subqueries. An empty
access set also means `checkAccessImpl` is never reached, which defeats the
`readonly` and `allow_ddl` settings on the same path.

A user holding only `GRANT SELECT` on a single database was denied a direct
`CREATE TABLE`, but the same statement wrapped in `PARALLEL WITH` succeeded.
`EXECUTE AS` was affected the same way, which inverts its contract: the
impersonated statement was checked against the privileges of neither party. For a
`QueryRunner` table the queued query text comes from whoever inserted it, so a
user with only `INSERT` on such a table could queue a `CREATE` and have it
executed regardless of the privileges of the principal the job runs as.

The flag cannot simply be cleared for these subqueries: `internal` also keeps a
nested query out of the `ProcessList` and deliberately leaves it without a
`SpanHolder` so that the spans already on the stack finish in the correct order,
`EXECUTE AS` relies on it to get raw blocks from the inner `executeQuery`, and it
is what marks `QueryRunner` jobs with `is_internal = 1` in `system.query_log`.
So the queries stay `internal`, and the authorization decision stops depending on
that flag: the new `QueryFlags::user_initiated` marks a query whose text was
written by the user, and `InterpreterCreateQuery` is told a query is
server-initiated only when `internal` is set and `user_initiated` is not.

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

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7099e77]

Summary: ✅


AI Review

Summary

This PR keeps nested user-authored queries internal for scheduling and logging, but stops treating them as server-authored CREATE statements by adding QueryFlags::user_initiated and wiring it through PARALLEL WITH, EXECUTE AS, and local QueryRunner execution; the follow-up dictionary change closes the same bypass for local ClickHouse dictionary invalidate_query by enforcing a SELECT-only query. After checking the current diff, surrounding code, and all prior review threads against the current head, I did not find a remaining correctness or RBAC gap in the touched surfaces.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 7099e77.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 33/33 (100.00%) · 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! comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7099e7763 with master f77edf0f9 (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

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

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

Translation unit Master PR Δ vs median
src/Processors/QueryPlan/ReadFromMergeTree.cpp 34.8 s 23.3 s -8.8 s (-27%)

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

BuzzHouse (amd_tsan) failed with std::terminate in MergeTreeData::loadOutdatedDataParts (STID 3782-4008). That is unrelated to this change: the same signature is on master - Stress test (amd_tsan) hit it on 2026-09-06 with no pull request attached, and Stress test/BuzzHouse hit it three times on master in the last 30 days - and it is tracked by #106736.

@diegomestre2 diegomestre2 left a comment

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.

Good work, @Manerone I was wondering if you tested with 2 layers of subqueries.

…tem.query_log`

The `INSERT` into a `QueryRunner` table succeeds no matter how the job ends, and the
absence of the database would also be observed if the job never ran at all, so the
test now reads the job's log entry - an `ACCESS_DENIED` exception before the grant,
`QueryFinish` after it - instead of discarding the client output.

Also cover two layers of nesting: a job that queues another job into a second
`QueryRunner` table, and `PARALLEL WITH` inside `EXECUTE AS`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

alexey-milovidov commented Sep 14, 2026 •

Copy link
Copy Markdown
Member Author

🕵 @diegomestre2, regarding two layers of subqueries: yes, each layer calls executeQuery with user_initiated = true, so the flag reaches the innermost CREATE. Added in 6b2819a as tests: a QueryRunner job that queues another job into a second QueryRunner table (05214, the inner CREATE DATABASE is denied and its system.query_log entry shows ExceptionBeforeStart ACCESS_DENIED), and PARALLEL WITH inside EXECUTE AS (05213, ACCESS_DENIED with nothing created). All three tests pass locally against a build of this branch.

…g by it

The style check asks every query of `system.query_log` to be constrained to the
database of the test. A job of a `QueryRunner` table runs with the database its
row names, so both tables now carry a `database` column and every job names the
test database - which is what puts it in `current_database`.

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

@diegomestre2 diegomestre2 left a comment

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.

LGTM

Comment thread src/Interpreters/executeQuery.cpp Resolved
…a `Replicated` database

The `05214` test read `system.query_log` rows filtered by names derived from the test database
only, so a second run against the same database would print the jobs of the first run again, and
its `QueryRunner` tables were never dropped. The user and the database now carry a random suffix,
and the tables are dropped before and after the run: the test passes repeatedly in one database.

The new `05215` test runs `PARALLEL WITH CREATE TABLE` in a `Replicated` database: the subquery is
denied without `CREATE TABLE` and succeeds with it. The replay through the replicated DDL log is a
separate server-side query which is non-internal for a direct `CREATE` as well, so a user-authored
subquery is now treated exactly like the direct statement on that path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The negative assertions of the two tests counted every table in the test database, and the success
paths left their fixed-name tables behind, so a rerun with `clickhouse-test --database=X` printed the
leftovers and failed with `TABLE_ALREADY_EXISTS`. Now only the objects each test creates are counted,
and they are dropped both before and after the run, as `05214` already does. Verified locally with two
consecutive runs of all three tests on one fixed database.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Stress test (arm_tsan) on 895fe7d failed with the logical error No set is registered for key __set_... (STID 0250-04e2). It is unrelated to this change: the stack is ReadFromMerge::createPlanForTable → StorageDistributed::getOptimizedQueryProcessingStageAnalyzer → isShardingKeySuitsQueryTreeNodeExpression → PlannerActionsVisitorImpl::makeSetForInFunction, i.e. a fuzzed SELECT reading a Distributed table through merge, while this PR only touches the user_initiated flag of nested CREATE queries. It is tracked in #119444 and fixed by the open #117817 (@groeneai); once that merges, a master merge here will pick it up. All other jobs are green or still running.

Address review: the test assumed it owned `rdb_${CLICKHOUSE_DATABASE}` and a fixed
ZooKeeper path, so a previous run that died after `CREATE DATABASE` (or after creating
`t_parallel_1` / `t_parallel_2`) made the next run on the same server fail at setup.

Now the user, the database and its ZooKeeper path carry a per-run random suffix, the
database is dropped with `IF EXISTS ... SYNC` up front and at the end, and only the
tables this test creates are counted and listed, as was already done for `05212`-`05214`.

Verified: two consecutive runs on one fixed database pass.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
…lickHouse` dictionary source

For a local source, `ClickHouseDictionarySource::doInvalidateQuery` executed the `invalidate_query`
text as an `internal` query on behalf of the configured user, without the `SELECT`-only check that
`createStreamForQuery` applies to the main query. The text comes from `CREATE DICTIONARY`, so a user
who may create a dictionary but has no `CREATE TABLE` privilege could run `CREATE TABLE ...` through
it with the access checks of `internal` queries skipped - the same bypass this PR closes for
`PARALLEL WITH`, `EXECUTE AS` and `QueryRunner`.

The check is now shared by both paths (`checkQueryIsSelect`), and a non-`SELECT` invalidate query is
rejected with `INCORRECT_QUERY` before anything is executed. Test `05218` creates such a dictionary as
a restricted user, waits for the periodic invalidate check, and asserts that nothing was created and
that a `SELECT` invalidate query keeps working.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Integration tests (amd_asan_ubsan, db disk, 4/8) on ce21881 failed in test_storage_nats/test_nats_jetstream_credentials_rotation.py::test_jetstream_unacked_messages_survive_rotation with Cannot connect to Nats last error: (unix/sock.c:56): poll error: 4 (report). It is unrelated to this PR: the same test fails on master (2026-09-14 19:30, 2026-09-15 11:34) and on other PRs. Root cause: the vendored nats-io client treats a poll interrupted by the profiler signal (EINTR) as a socket error, and the test uses a single startup connect try.

Tracked in #120201, fix in #120202.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: Stress test (arm_tsan) on ce21881 aborted with Logical error: Found patch part patch-...-all_0_36_4_27 (min data version: 5, max data version: 27) that intersects mutation with version 14 in StorageReplicatedMergeTree::addOpsToDropAllPartsInPartition -> MergeTreeData::assertNoPatchesForParts -> patchHasHigherDataVersion (report) and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is unrelated to this PR (RBAC query flags): the same stack fails on master, e.g. Stress test (amd_tsan) at a5bc4cc on 2026-09-14 (report), and CIDB shows 13 hits across unrelated PRs since 2026-08-26. Note that this is the ReplicatedMergeTree arm (DROP PARTITION after a patch-part merge spanned a mutation version): #116047 and its fix #119312 only cover plain MergeTree (MergeTreeMergePredicate / StorageMergeTree), so the ReplicatedMergeTreeMergePredicate side seems to need the same treatment.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I am investigating the arm_tsan logical error at ce21881b on the Replicated DROP PARTITION path (addOpsToDropAllPartsInPartition -> assertNoPatchesForParts).

Confirming the arm split you describe: #119312 touches only MergeTreeMergePredicate / StorageMergeTree / PatchPartsUtils, no ReplicatedMergeTree* file, so there is no in-progress fix of mine for this arm to link. I will follow up here with a separate PR, or with my findings if the conclusion turns out to be different.

@Manerone

Copy link
Copy Markdown
Contributor

@rschu1ze Yes, that is what I was trying to do yesterday, but CI was down due to MinIO issues.

…d-access-checks

Refresh the branch against master to get a new CI run; the previous run's only
failure was `Build profile diff`, which errored on a CI logs cluster query
rather than on anything in this branch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Manerone
Manerone added this pull request to the merge queue Sep 17, 2026
Merged via the queue into master with commit 3a3d261 Sep 17, 2026
350 of 351 checks passed
@Manerone
Manerone deleted the sec-user-initiated-access-checks branch September 17, 2026 15:14
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 17, 2026
Backport #119848 to 26.9: Do not skip access checks of a user query executed as a nested query
PedroTadim added a commit that referenced this pull request Sep 17, 2026
Backport #119848 to 26.7: Do not skip access checks of a user query executed as a nested query
clickhouse-gh Bot added a commit that referenced this pull request Sep 17, 2026
Backport #119848 to 26.8: Do not skip access checks of a user query executed as a nested query
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
robot-ch-test-poll added a commit that referenced this pull request Sep 18, 2026
Cherry pick #119848 to 26.6: Do not skip access checks of a user query executed as a nested query
robot-clickhouse added a commit that referenced this pull request Sep 18, 2026
Manerone added a commit that referenced this pull request Sep 18, 2026
Cherry pick #119848 to 26.3: Do not skip access checks of a user query executed as a nested query
robot-clickhouse added a commit that referenced this pull request Sep 18, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 18, 2026
rschu1ze added a commit that referenced this pull request Sep 18, 2026
Backport #119848 to 26.6: Do not skip access checks of a user query executed as a nested query
rschu1ze added a commit that referenced this pull request Sep 18, 2026
Backport #119848 to 26.3: Do not skip access checks of a user query executed as a nested query
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 21, 2026
`natsSock_WaitReady` treated a `poll` interrupted by a signal (`EINTR`) as a socket error, so a connection attempt of a `NATS` table failed spuriously with `Cannot connect to Nats last error: (unix/sock.c:56): poll error: 4` whenever the query profiler signalled the connecting thread. With `nats_startup_connect_tries = 1` in the credentials-rotation tests this made `CREATE TABLE` fail at random.

The fix (ClickHouse/nats.c@b88704df) waits again for the rest of the deadline. The bump also brings the two fork changes already merged there: the libuv attach ordering and the JetStream fetch lock-order backport.

Failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119848&sha=ce21881b746a07dc79574410b18f5c5b57e38551&name_0=PR&name_1=Integration%20tests%20(amd_asan_ubsan,%20db%20disk,%204/8)
PR: ClickHouse#119848

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

Labels

comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

EXECUTE AS <user> CREATE … skips the impersonated user's access checks

7 participants