Repository navigation
Let a user cancel their own query by id without SELECT on system.processes - #117999
Conversation
Internal second-model reviewReviewed cold against the resulting code, then re-reviewed by an independent model, over several fix ❌ The read that authorizes rows ran in the calling query's own thread group, so the rows it scans before ❌ A ❌ The caller's
💡 Not fixed, disclosed rather than left to be found. The test's arm labels jump from 10 to 12, because Session id: cron:clickhouse-review-slot-9:20260904-034700 |
|
Workflow [PR], commit [7b5953a] Summary: ❌
AI ReviewSummaryThis PR adds a reduced Findings❌ Blockers
Final Verdict❌ Changes requested. The reduced path closes the no- LLVM Coverage ReportMeasured on commit 7b5953a.
Changed lines: Changed C/C++ lines covered: 122/125 (97.60%) · Uncovered code |
|
cc @vitlibar @yariks5s, could you review this? A caller without |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes32 object files changed (+40.44 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units213 translation units recompiled, 1767 s compile time in total, 213 of them have a recent master baseline. |
CI finish ledger - 1455001Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260905-030000 |
|
@groeneai Abstract |
|
Thanks, that is a much smaller surface and I will cut this PR down to it. What stays:
What goes: the internal full-access read of
I will push the reduced version on this PR. |
…esses KILL QUERY learns which queries exist by running an internal SELECT query_id, user, query FROM system.processes under the caller's own rights, so that table's SELECT grant became a de-facto prerequisite for killing anything, including one's own query: Code: 497. DB::Exception: u1: Not enough privileges. To execute this query, it's necessary to have the grant SELECT ON system.processes. (ACCESS_DENIED) That is a side effect of the mechanism, not a policy. ProcessList already indexes queries by (user, query_id), so for a single constant id the only authorisation question, "is this query mine?", is answerable without reading the table. Recognise exactly one statement shape, query_id = '<literal>' with an optional AND user = '<the caller>' conjunct, and answer it from one keyed ProcessList lookup that can only ever return the caller's own query. An id that is absent and an id owned by somebody else both yield an empty block, which is what a read of system.processes returns for a predicate matching no row, so the observable answer is the same in both cases and nothing about other users leaks. Any other predicate, including a qualified processes.query_id, keeps requiring the grant, so an unrecognised statement can only fail closed. A caller who holds the grant takes the unchanged path. The grant probe is column-level over exactly the three columns the read names, because every referenced column needs its own SELECT grant; a table-wide check would divert callers who hold only some of them. ON CLUSTER works too. The initiator replaces the WHERE of the statement it enqueues with the canonical query_id = '<id>' AND user = '<caller>', written by the server from the authenticated context. That replacement is a security precondition, not a nicety: executeDDLQueryOnCluster checks access on the initiator only, and a worker runs DDL with no bound user, and therefore with full access, unless distributed_ddl_use_initial_user_and_roles is enabled, so a bare id would let the workers kill any user's query with that id. Query ids are caller-chosen, which would make that directly exploitable. AccessType::CLUSTER is still required for every ON CLUSTER statement. Carrying the initiator's identity in the DDL entry instead was measured and rejected: entry.initiator_user is serialized only at distributed_ddl_entry_format_version >= 8, nothing raises the version for that field, and forcing 8 makes every not-yet-upgraded worker throw UNKNOWN_FORMAT_VERSION and permanently skip the entry. Closes ClickHouse#112376
Follow-up to the previous commit on this branch, after @pufit reviewed it on 2026-09-16 and asked for the simple feature only: "give a user opportunity to kill their own query (by id) when they don't have select on system.processes or KILL grant ... Abstract WHERE condition can be implemented later". ClickHouse#117999 (comment) Correcting the previous commit's message explicitly: it says "ON CLUSTER works too", and that claim no longer holds, because this commit removes the `ON CLUSTER` relaxation. Removed: * the initiator's rewrite of the enqueued `WHERE` into a canonical `query_id = '<id>' AND user = '<caller>'`, and the matcher branch that accepted that conjunct; * the `getRequiredAccessForDDLOnCluster` relaxation, so `KILL QUERY` is again required for every `KILL QUERY ... ON CLUSTER` and that function is byte-identical to master; * `tests/integration/test_kill_query_on_cluster`. `ON CLUSTER` is left out because relaxing the initiator's `KILL QUERY` requirement relaxes it for the whole cluster, including workers that have not been upgraded yet. `executeDDLQueryOnCluster` checks access on the initiator only and `ON CLUSTER` is stripped before a worker runs the statement, so a not-yet-upgraded worker runs the old full-access read of `system.processes` and cancels by the queued user name. User names are reusable, so after a rename plus a re-creation of the freed name that worker cancels the previous principal's query. No worker-side change reaches an old worker and the initiator has no capability handshake to gate on, so during a rolling upgrade the relaxation is not safe. Gating it on `distributed_ddl_use_initial_user_and_roles` does not help either: that setting is a no-op at the default `distributed_ddl_entry_format_version = 5`. The local path has no such propagation. Authorisation and execution happen in the same process under one access context, so there is no version skew to be unsafe across. Ownership is now a user id comparison, not a name comparison, because names are recycled and a running query keeps the name it was filed under. Three cases all dissolve into one `UUID` check: a re-created name reaching the previous principal's still-running query, a session that outlives a rename reaching the new principal's query, and a renamed principal locked out of its own query. So `QueryStatus` carries the `std::optional<UUID>` its query runs as, snapshotted in `ProcessList::insert` before the mutex is taken because `Context::getUserID` locks the context and `QueryStatus` is constructed with `ProcessList::mutex` held. `ProcessList::tryGetOwnRunningQuery` locates the entry through the process-wide id index, exactly as `sendCancelToPostgreSQLQuery` does, and authorises it on that id; the caller's own name is never read. The comparison is repeated at the cancel, because both cancel sites re-resolve `(user, query_id)` after the lock is released, so authorising only at lookup time would let a replacement entry be cancelled without ever passing the check. The keyed cancellation is now one private implementation with two thin public overloads, so there is a single lock, `is_cancelling` and `SCOPE_EXIT` sequence rather than a copy of it. It stays keyed rather than pinning the verified `QueryStatusPtr`: `SyncKillQuerySource` finishes a row on `NotFound` from that lookup, and a pointer overload could never answer `NotFound`, so `KILL QUERY ... SYNC` would hang on a query that has already finished. A caller who holds `KILL QUERY` but not the `SELECT` grant now also gets the by-id self kill, since their ordinary path only throws, and granting a privilege must not take an ability away. When such a caller names an id that is not their own, the statement falls through to the ordinary path and its error, rather than answering with a silent zero rows. `docs/concepts/features/configuration/settings/permissions-for-queries.mdx` stated that killing your own query requires `SELECT` on `system.processes`, which is now false for the by-id form, so it names the exception. The stateless test drops the three arms that pinned the canonical predicate and the foreign-user literal, and gains four: a `KILL QUERY` holder without the `SELECT` grant aimed at another user's id and at their own, a re-created user name, and a renamed principal.
The previous commit on this branch added a fifth, non-defaulted `const std::optional<UUID> & user_id_` parameter to the `QueryStatus` constructor but updated only `ProcessList::insert`. The other direct construction, `makeQueryStatus` in `gtest_cancellation_checker.cpp`, still passed twelve arguments against thirteen parameters, which does not compile. `src/CMakeLists.txt` globs every `gtest*.cpp` under `src/` into `unit_tests_dbms`, and the debug, ASan and TSan builds are configured with `-DENABLE_TESTS=1`, so this broke those builds and every check downstream of them. `std::nullopt` is the right value here: the test builds a `QueryStatus` bound to no principal, which is what an empty `user_id` means for a server-internal query. The constructor parameter deliberately keeps no default value, so that a future call site cannot silently lose its user binding. Also include `<Core/UUID.h>` and `<optional>` in `ProcessList.h` directly. It declares `std::optional<UUID>` members and parameters and was relying on both arriving transitively.
The arms were left labelled 1, 2, 3, 4, 7, 9, 10, 11, 12, 13 when the reduction removed arms 5, 6 and 8, so a reader of the `.reference` had to wonder what the gaps were. Label text only, in both files: no assertion, no poll bound and no arm order changes.
`selfKillDescriptors`'s loop over `processes_block.rows()` already shows that a block with no row produces no descriptor, and `OwnQuery`'s two members are named `user` and `query`. Comments only: the code is unchanged.
…ct the doc
Three arms, each shown to fail when the code it names is broken:
* arm 11 writes the literal on the left, `'<id>' = query_id`. Removing the
reversed branch of the matcher reddens this arm and only this arm, so the
"either operand order" claim now has a test.
* arm 12 uses `SYNC`, which reaches `KILL QUERY` through a separate source
with its own call to the keyed cancellation. Passing `UUIDHelpers::Nil` as
the expected user there reddens this arm and only this arm.
* arm 13 aims a holder of `SELECT` on `system.processes`, but not of
`KILL QUERY`, at another user's id. It must be refused by the ordinary path,
which reports `attempts to kill query created by`. Inverting the grant check
that keeps such a caller out of the by-id path turns that refusal into an
empty result, which is what this arm exists to catch: the by-id path must
never take a caller who can read the table, because it does not apply their
row policies.
The documented promise was also too strong. It said an id that is not running
as the caller returns no rows rather than an error, which is true only for a
caller who holds neither grant: a `KILL QUERY` holder without `SELECT` keeps the
ordinary path and its error, as arm 7 already asserted. The paragraph in
`ParserKillQueryQuery.cpp` now says so, and the changelog entry is qualified the
same way.
A `KILL QUERY` runs through the process list like any other query, so a statement whose own id is the one it names would find itself. The ordinary path skips that row; the by-id path has an explicit outcome for it. Nothing asserted that outcome: making its condition unsatisfiable leaves the rest of the suite green and turns this arm's empty result into three rows, the statement having cancelled itself.
Master suppressed the cancellation with a ternary on `query.test`; carrying the keyed overload meant rewriting that into a statement, so `KILL QUERY ... TEST` not killing anything became this branch's responsibility. Nothing asserted it: with the guard removed the other fourteen arms stay green while `TEST` silently cancels its victim, which this arm now catches.
The `TEST` arm sampled `system.processes` right after the statement returned. Asynchronous cancellation only signals the executors, so that sample could still list a victim that was on its way out, and the arm would then pass against code that does cancel. The status column does not depend on that timing: `TEST` never reaches the cancellation, so its code stays `Unknown` and reports `unknown_status`, whereas anything that does cancel reports `waiting`. `user_id` was described as empty for a server-internal query. `ProcessList` snapshots the context's user unconditionally, so what is really true is that it is empty when the context has no bound user.
1455001 to
d7a2664
Compare
SELECT on system.processes for KILL QUERYSELECT on system.processes
|
Pushed the reduction. I left I am happy to open a follow-up for One note from reviewing my own change: the global |
…out-processes-grant
`gtest_cancellation_exception_aliasing.cpp` landed on master after this branch was cut, so merging master left it calling the pre-`user_id` constructor and `Build (arm_tidy)` failed with `no matching function for call to '__construct_at'` out of `std::make_shared<QueryStatus>`. It gets the same argument the sibling cancellation gtest already passes: these tests bind no user, so the id is absent. Co-Authored-By: Claude Opus 5 <[email protected]>
The gate asks for `SELECT` on all three columns the ordinary path reads, so a holder of `SELECT(query_id, user)` fails it and falls back to the by-id path, exactly as a holder of nothing does. That is deliberate: its ordinary path also throws for want of that `SELECT`, so routing it there instead would make granting a column privilege take the ability to stop one's own query away. A holder of all three columns can complete that read, so it keeps the ordinary path and with it row policies and the ordinary refusal. Neither shape was covered: arms 6 and 13 grant the whole table and the rest grant nothing, so both narrowing the check to fewer columns and widening it to the table would have kept the suite green. Arm 16 measures the refused three-column read and the self-kill that still succeeds; arm 17 measures that a column-list grant is refused by the ordinary path when it names another user's query, rather than answered with an empty result. Co-Authored-By: Claude Opus 5 <[email protected]>
`ProcessListEntry::~ProcessListEntry` erases `user_process_list.queries[query_id]` only when the entry it finds there is its own, but it erases `queries_to_user[query_id]` by key alone, and between the two it waits on `cancelled_cv`, releasing the `ProcessList` mutex. A query of the same user that takes the id over in that window publishes itself in the per-user map while its own `queries_to_user.emplace` is a no-op against the key that is still there, so the parked destructor then erases the mapping of the query that is now running, and this path answers with no rows for a live query of its own caller. `queries_to_user` is maintained for the query id uniqueness check (`ProcessList.h`), and this was the only place that used it as an index, so drop that use rather than teach the map a second invariant. `processes` is the list the ordinary path reads through `system.processes`, an entry leaves it only through its own iterator, and the entry carries both the `user_id` that decides ownership and the user name the cancellation needs, so one walk of it answers exactly what this path asks: the caller's own running query with this id. The walk is bounded by the queries running now, and it replaces a `SELECT` over the same list. The window itself has no deterministic test: the pause would have to sit in a destructor holding the `ProcessList` mutex, which stops every query on the server and leaves nothing observable while it is held. 100 orchestrated attempts did not reach it either, because `cancelQuery` returns at once when `is_killed` is already set, which is what `replace_running_query` sets, leaving a window of microseconds unless the cancellation is both in flight first and slow. Arm 18 pins the reachable half: an id taken over with `replace_running_query` resolves to the query now running under it, carrying that query's own text. Co-Authored-By: Claude Opus 5 <[email protected]>
|
|
||
| /// Every column the read below names needs its own `SELECT` grant, hence exactly these three. | ||
| static const Strings kill_query_columns{"query_id", "user", "query"}; | ||
| if (context->getAccess()->isGranted(AccessType::SELECT, "system", "processes", kill_query_columns)) |
There was a problem hiding this comment.
Returning early for every caller that already has SELECT(query_id, user, query) on system.processes puts the exact same query_id = '<id>' shape back on the old name-based ownership path. The reduced path uses user_id, but extractQueriesExceptMeAndCheckAccess() still compares current_user strings and sendCancelToQuery(query_id, user) still resolves by name only.
That means the new recreated/renamed-principal safety disappears as soon as the grant is present:
- after
ALTER USER a RENAME TO b, the same principal can no longer kill its own pre-rename query by id once it hasSELECT, because the row still carriesawhilemy_client.current_useris nowb; - after
DROP USER a; CREATE USER a, the recreated login is still treated as the owner on the ordinary path because the names match.
So this branch still makes a privilege grant change the ownership semantics of the same statement shape, which is the opposite of the contract in the comment above. Please keep the user_id-based self-match for this exact shape even when SELECT is granted, or teach the ordinary path to compare/cancel by user_id too, and add the renamed/recreated cases under a SELECT grant.
There was a problem hiding this comment.
Both facts are right, and I measured them: the gate at :116 does route every SELECT(query_id, user, query) holder to the ordinary path, and that path compares my_client.current_user (:223) and cancels by name (:289).
What I cannot reproduce is the regression. Same rig, fresh access storage per start, master 26.10.1.1 (buildId 3f17173) against this head (buildId 1767268a):
| case | master | this head |
|---|---|---|
renamed SELECT holder kills its own pre-rename id |
refused, attempts to kill query created by ..., victim survives |
identical |
recreated name (rename-away + CREATE) under the grant |
1 row, waiting, victim gone |
identical |
literal DROP USER + CREATE USER under the grant |
victim survives the drop, then 1 row, victim gone | identical |
| no grant at all, renamed, own pre-rename id | refused, needs SELECT ON system.processes, still running |
1 row, waiting, victim gone |
Only the last row changes. The function body of extractQueriesExceptMeAndCheckAccess hashes identically on the merge base and on this head (sha256 199b9d6d...), and user_id is only ever set by selfKillDescriptors, so a grant holder runs the base revision's bytes. The rename and recreate semantics you describe are therefore pre-existing properties of the ordinary path, not something this branch introduces; what the branch adds is identity-based resolution on the path that previously just threw.
The part of your point that stands, stated precisely: after this change, granting those three columns moves a caller from the last row to the first, so for a principal renamed mid-query the grant removes an ability this PR itself introduced. I am keeping that, for a measured reason.
Remedy 1, keeping the user_id self-match when SELECT is granted, re-opens the row-policy root from 05:32Z today. Measured on this head, with a permissive policy for the observer so the liveness check is not blinded:
- grant holder,
ROW POLICY ... USING 0: 0 rows, no error, victim survives, so the policy is applied; - same caller, only the predicate flipped to
USING 1: 1 row, victim gone, so that survival is attributable to the predicate and not to some other denial; - no-grant caller, identical
USING 0policy: 1 row, victim gone, so the reduced path does not consult the policy.
Dropping the early return moves the grant holder from the first outcome to the third. The two asks are mutually exclusive, and I am keeping the one that does not widen what a row policy exists to hide.
Remedy 2, comparing and cancelling by user_id on the ordinary path, is a behaviour change for every SELECT holder: rows 2 and 3 above would stop working, so a recreated name would lose the ability to stop the previous principal's in-flight queries. That is a compatibility decision about code this PR does not touch, in a branch I was asked to shrink, so it is a maintainer's call rather than mine. It is a small change if it is wanted.
On the tests: arms 8 and 10 already pin the recreated and renamed cases on the reduced path, and arm 17 pins that a holder of exactly those three columns keeps the ordinary path. Arms for the same two cases under the grant would pin master behaviour this branch does not change, and would have to be deleted if remedy 2 were ever adopted.
On the comment you cite: its scope is why KILL QUERY is not required on the reduced path, not a claim about the SELECT gate. The principle it appeals to does reach the gate in the narrow renamed case above, which is why I stated that case instead of dismissing it.
This is the fourth automated root on this PR today and I have answered each on its merits. I am treating the automated pass as concluded for this head; the remaining design fork is the one in remedy 2, and I will leave that to a human.
|
@groeneai is the failed test related? |
|
No. The only red on this head is
The signature is pre-existing, and not specific to this branch or to arm: 22 rows in CIDB over the last 30 days, spread over 8 check flavours including the AST fuzzer, and split as 19 other pull requests, two master runs (2026-08-26 Owner: my closest merged fix for this shape is #119860, and it is already in this branch ( |
CI finish ledger - 7b5953aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
176 checks, all completed: 154 success, 19 skipped, 1 failing job (the two remaining reds are the Session id: cron:our-pr-ci-monitor:20260922-230208 |
|
Fixing PR for the The query in the fatal log is my own
#115916 deletes the guard from Nothing to change on this branch. |
33bd2f8
Conflicts resolved: - `InterpreterKillQueryQuery.cpp`: kept master's reduced/self-kill descriptor path (`selfKillDescriptors` from ClickHouse#117999) and re-applied the empty-match throw (`NOTHING_TO_KILL`) after descriptor selection. - `SettingsChangesHistory.cpp`: kept both new 26.10 entries (master's `analyzer_compatibility_allow_cte_redefinition` and ours `kill_throw_if_noop`). Verified: full build clean; `05233_kill_throw_if_noop`, `00417_kill_query`, `01003_kill_query_race_condition` pass against the merged binary. Co-Authored-By: Claude Code <[email protected]>
The self-kill path merged from zwy/master (ClickHouse#117999) documents that a user holding neither `SELECT` on `system.processes` nor `KILL QUERY` gets "no rows rather than reporting an error" when naming an id that is not running as them. With `kill_throw_if_noop` enabled (the default), that no-op now throws instead, so say so explicitly in the statement docs. Co-Authored-By: Claude Code <[email protected]>
Closes: #112376
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
KILL QUERY WHERE query_id = '<id>'now cancels the caller's own query without requiringSELECTonsystem.processes. For a caller holding neither that grant norKILL QUERY, an id that is not running as them cancels nothing and returns no rows. Any otherWHEREcondition keeps requiring the privileges it requires today.Description
KILL QUERYlearns which queries exist from an internalSELECT query_id, user, query FROM system.processesrun under the caller's own rights, so that grant is a de-facto prerequisite for killing anything, including one's own query:ProcessListalready holds the running queries with their owners, so for a constant id the question is this query mine? is answerable without reading the table. This PR answers one statement shape,query_id = '<string literal>'(either operand order), from a caller who does not holdSELECTonsystem.processes, out ofProcessList: it cancels the query when that id runs under the caller's own user id, and otherwise returns the zero rows a table read gives for a predicate matching no row, so an absent id and another user's id are indistinguishable.Ownership is a user-id comparison, never a name comparison, at both the lookup and the cancel: names are reusable, and a query keeps the name it was filed under.
KILL QUERYis deliberately not required here, since its holder's ordinary path also throws without theSELECTgrant and granting a privilege must not remove a capability; a holder naming an id that is not their own still gets today's error, not a silent no-op.Everything else takes the existing path, row policies included: any other
WHERE, a qualifiedprocesses.query_id, and every caller holdingSELECTonsystem.processes.ON CLUSTERreturns before this path on the initiator, and a replica reaches it only underdistributed_ddl_use_initial_user_and_roles(off by default), for that same user's own query.New test
05060_kill_query_without_processes_grantcovers eighteen arms: each privilege state, a recreated name, a renamed principal,SYNC, both column-grant shapes, and an id taken over withreplace_running_query; eleven fail when the code they name is broken.Workflow [PR]
Sync PR [sync-upstream/pr/117999]
Version info
26.10.1.486-master(included in26.10and later)