Repository navigation
Add a new system table system.user_query_log - #110156
Conversation
Shows every user their own query log records without requiring access to the query log table. The inner query over the configured query log table runs under an internal full-access context and is embedded into the outer query plan as an opaque, fully built pipeline, so no outer expression (WHERE, additional_table_filters, additional_result_filter) can be moved below the user filter.
|
Workflow [PR], commit [1a9357e] Summary: ✅
AI ReviewSummaryThis PR adds Findings❌ Blockers
Final Verdict❌ Changes requested. The current pushdown optimization leaks information about other users' log rows through the caller's own query-log statistics, so the feature is not yet safe to merge. |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…ure being enabled Address the code review of the pull request: `ContextAccess::addImplicitAccessRights` granted `SELECT` on `system.user_query_log` to every user unconditionally. When `query_log.enable_user_query_log = 0`, the name can back a regular table (or the raw query log via `query_log.table = user_query_log`), which would then become world-readable instead of requiring an explicit grant. The documented upgrade workaround (disabling the feature for a pre-existing table with this name) had the same problem. The implicit grant is now conditional on `AccessControl::isUserQueryLogEnabled`, mirroring the `query_log.enable_user_query_log` server setting read at startup. This is exactly when `system.user_query_log` is attached as `StorageSystemUserQueryLog` (the attach code rejects any other table under this name while the feature is enabled), so the grant applies only when the name is backed by the row-filtering storage. When the feature is disabled the name has no implicit grant and behaves like any other table, so the disable/upgrade path is now safe. Adds an integration test that starts a server with the feature disabled and the raw query log configured under the `user_query_log` name, and verifies a user without grants cannot read it, while a privileged user still can. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…into the inner read context Address review (clickhouse-gh @ `StorageSystemUserQueryLog.cpp`): the inner `query_log` read started from a bare `Context::createCopy(context->getGlobalContext())` and never reapplied the caller's execution settings or normalized query hash. As a result, `NORMALIZED_QUERY_HASH` quotas were bucketed under `0`, and the backing query log scan ran with server-default settings (e.g. `max_threads`) instead of the caller's profile. Mirror `StorageInMemoryMetadata::getSQLSecurityOverriddenContext`: carry over the client info and the normalized query hash, and apply the caller's settings changes. The expression-injection settings `additional_table_filters` and `additional_result_filter` are dropped from the applied changes, because they would inject expressions evaluated on other users' rows before the user filter hides them. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test shipped a custom `users.xml` that added `<grants>` to the `default` user. The integration harness always merges `0_common_instance_users.xml`, which sets `<access_management>1</access_management>` for `default`, and combining `grants` with `access_management` is rejected with `Any other access control settings can't be specified with grants` (`BAD_ARGUMENTS`), so the server exited during config load and the test errored. The harness default `default` user already has full access (the base `users.xml` grants `ALL` and the common config enables access management), so the custom `users.xml` was redundant. Remove it and let the test rely on the default user. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110156&sha=a127abec2e86e75f6a90a354d6e01ee4bd623a65&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e-local too `AccessControl::setUserQueryLogEnabled` was only called from `AccessControl::setupFromMainConfig`, i.e. the server startup path. `clickhouse-local` sets up its access control separately in `LocalServer::setupUsers` and never set the flag, while still attaching `system.user_query_log` through `attachSystemTablesServer`: a local user without an explicit `SELECT` grant would get `ACCESS_DENIED` on a table that is documented as readable without grants. Mirror `query_log.enable_user_query_log` into the local access-control setup and extend `04516_user_query_log_local` with regression checks: `SHOW GRANTS WITH IMPLICIT` for a grantless user must list `GRANT SELECT ON system.user_query_log` when the table is enabled and must not list it when it is disabled. Co-Authored-By: Claude Fable 5 <[email protected]>
`system.user_query_log` copied only `QueryLogElement::getColumnsDescription` and dropped the alias columns exposed by `system.query_log` (`ProfileEvents.Names`, `ProfileEvents.Values`, `Settings.Names`, `Settings.Values`). As a result, queries that use those aliases stopped working against the new table, and the doc's "same columns except `LowCardinality`" contract was false. Carry over `QueryLogElement::getNamesAndAliases` as well, de-LowCardinality-ing the alias types the same way as the physical columns, so the new table exposes exactly the same user-facing surface as `system.query_log`. The aliases are computed by the outer query plan on top of the per-user-filtered, opaque `ReadFromPreparedSource`, so they cannot observe other users' rows. Extended `04515_user_query_log.sh` to check the alias column types are de-LowCardinality-ed and that the aliases still resolve to the corresponding `mapKeys`/`mapValues` of the physical columns. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
CI note: the only non-green check is
@groeneai, could you take a look and confirm / open a tracking issue for the |
|
Confirmed: pre-existing test fragility, not a regression from this PR. CIDB ( Tracking issue: #110190 (likely fix: add the |
…d database
Address review: the startup guard for `system.user_query_log` only checked the raw
`query_log.database` value. `SystemLog::createSystemLog` coerces any non-`system`
database back to `system`, so a config like
<query_log><database>foo</database><table>user_query_log</table></query_log>
still materializes a real `system.user_query_log` and only died later on a generic
"Table already exists" startup exception, bypassing the focused `BAD_ARGUMENTS`
message; the message wording was also misleading.
Drop the `query_log.database == system` condition so the guard fires on
`query_log.table = user_query_log` regardless of the configured database, and reword
the message. Add integration test `test_user_query_log_config_validation` covering
startup rejection for both a `system` and a non-`system` configured database.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… query log table The opaque `ReadFromPreparedSource` barrier protected the user filter from plan-level optimizations, but it also stripped all predicate pushdown: every lookup on `system.user_query_log` scanned the whole retained query log with only the current-user filter, and `SELECT` on this table is implicitly granted to every user. The read is now built as a `SourceStepWithFilter`: the plan optimization offers it the outer filter (and keeps the outer `FilterStep` in place, so the full predicate is always re-applied on top), and a vetted subset of its conjuncts is embedded into the internal query, restoring partition pruning and index analysis on the backing table. A conjunct is pushed only when it consists of logical connectives and comparisons (which cannot fail per row, so they cannot act as an error-based oracle on other users' rows) over the partition / point-lookup columns and constants whose values were already computed by the outer query. The `LIKE` family additionally requires a constant pattern, because a pattern from a cell is compiled per row and a malformed one throws. The outer `LIMIT` is applied inside only when there is no filter at all (the internal query applies the user filter before it). Addresses the review finding on the PR.
The safe-predicate allow-list in `StorageSystemUserQueryLog` used the names `lessOrEqual` and `greaterOrEqual`, but both analyzers emit the `<=` and `>=` comparisons as functions named `lessOrEquals` and `greaterOrEquals`. Because of the mismatch, those operators never satisfied `pushable_functions.contains(function_name)`, so predicates such as `event_date >= ...` or `query_start_time <= ...` stayed outside the internal query and lost partition pruning and index analysis on the backing `system.query_log` table. Rename the two allow-list entries to the canonical function names, and extend `04550_user_query_log_pushdown.sh` with a focused regression that a `>=` and a `<=` predicate on the partition column each prune every partition (read zero rows from the backing table), so this operator-name mismatch cannot regress silently. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…he pushdown test The `check_functional_test_cases` style check flagged `04550_user_query_log_pushdown.sh` because it filtered `event_date >= today() + 2`, and the rule bans `event_date` compared with `=` / `>=` against `today()` (it wants `yesterday()` for a one-day buffer against midnight flakiness). Rewrite the `04550_pruned_ge` predicate as the equivalent `event_date >= yesterday() + 3` (`yesterday() + 3` folds to the same `Date` as `today() + 2`), so the predicate still prunes every partition of the `event_date`-partitioned backing `system.query_log` and the case still asserts `read_rows = 0`. The reference is unchanged. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110156&sha=583dd0511086904fc4bfc10025c2b54045f24240&name_0=PR&name_1=Style%20check Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…` mode `StorageSystemUserQueryLog::read` treated `Context::getQueryLog()` returning `nullptr` as "no backing query log table exists" and returned an empty result. That is wrong in `clickhouse-local --only-system-tables`: `LocalServer` deliberately skips `initializeSystemLogs` there (so the live `QueryLog` object is absent) while still loading the persisted `system` tables from disk, so the configured `system.query_log` can be present and queryable. In exactly the mode meant for inspecting existing system tables, `system.user_query_log` silently went empty instead of filtering the loaded query log. When the live `QueryLog` object is absent, resolve the backing table from the `query_log.database` / `query_log.table` server settings (`system.query_log` by default; a custom `query_log.database` is coerced back to `system` in `createSystemLog`, so only the table name is configurable) and read it if it exists, instead of equating "logger not running" with "query log not configured". Extends `04516_user_query_log_local.sh` with a regression test: a persistent `system` database is seeded, a first invocation persists query log records, and a second `--only-system-tables` invocation still sees the current user's own records instead of an empty result.
…y log is configured `StorageSystemUserQueryLog::read` resolved `system.<query_log.table>` from the catalog whenever `Context::getQueryLog` returned nothing. That is the right thing for `clickhouse-local --only-system-tables`, which skips starting the loggers while still loading the persisted `system` tables, but `createSystemLog` also returns nothing when the `query_log` section is missing from the configuration altogether, while a `system.query_log` table created by an earlier run is still attached from disk on startup. So after removing `<query_log>` and restarting, `system.user_query_log` kept reading that stale table instead of being empty, contrary to the documented "the query log is not configured, so the table is empty" behavior. Gate the resolution on a configured `query_log` section, and extend `04516_user_query_log_local` with the case: after the persisted query log table is written, an `--only-system-tables` run with the `query_log` section removed sees the table attached, while `system.user_query_log` reads no rows.
…for the read The internal query is built by an interpreter inside `ReadFromUserQueryLog::initializePipeline`, so its processors were accounted to the steps of that internal query plan, which does not outlive the call and is not part of the plan the outer query knows about. `EXPLAIN ANALYZE` populates its per-step wall clocks from the explained plan and looks one up for every executed processor by its plan step (`ExecutionThreadContext::executeTask`, `chassert(clock)`), so a processor of the internal query had no clock: its time was not accounted to `ReadFromUserQueryLog`, and the assertion fired in a build with assertions enabled. Hand these processors to `ISourceStep::updatePipeline`, which accounts them to this step, the way other source steps do. Now `EXPLAIN ANALYZE SELECT count() FROM system.user_query_log` reports the time of the read (0.5 ms, 45% of the query) at `ReadFromUserQueryLog` instead of 770 ns, and `EXPLAIN PIPELINE` describes the processors of the read. `04516_user_query_log_local` runs `EXPLAIN ANALYZE` over the table, which covers the assertion in the builds that enable it (a release build only silently misaccounts the time).
|
CI note on That said, |
alexey-milovidov
left a comment
There was a problem hiding this comment.
It's not as straightforward as I expected, but all good.
| log_table_id.getFullTableName(), | ||
| quoteString(outer_context->getClientInfo().initial_user)); | ||
|
|
||
| if (String pushed_conditions = buildPushedDownConditions(); !pushed_conditions.empty()) |
There was a problem hiding this comment.
This reintroduces a side channel on other users' query_log rows through the probe query's own execution statistics. Once we splice caller-controlled predicates into the inner system.query_log read here, the backing scan is narrowed before the per-user filter, so a low-privilege user can probe for foreign activity with something like WHERE query_id = 'victim-id' or WHERE user = 'victim', then read the probe query's recorded read_rows (or just time it) back from their own system.user_query_log entry. 04550_user_query_log_pushdown.sh already demonstrates that these pushed predicates measurably change read_rows; because this feature exposes the caller's own query-log rows without extra grants, that measurement becomes a direct oracle on the global log.
I don't think the current allow-list can make this safe: even "harmless" columns like query_id, user, initial_user, current_database, or event_date leak whether matching foreign rows exist once their effect is observable through read_rows / runtime. The fix needs to keep caller-controlled predicates above the opaque ReadFromPreparedSource barrier again (or otherwise suppress those stats for this storage, which is much harder).
There was a problem hiding this comment.
This is expected but unavoidable.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 170/179 (94.97%) · Uncovered code |
Closes: #82539
Related: #104462
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new system table,
system.user_query_log, which shows every user their own query log records without requiring access to the query log table. The original implementation and the idea belong to Yue Ni (@niyue), #104462.Documentation entry for user-facing changes
This is a simplified implementation of #104462.
The original PR implements
system.user_query_logas an automatically createdSQL SECURITY NONEview over the query log table. Since such a view is a first-classStorageViewfused into the outer query plan, every user-controllable expression channel has to be defended individually, and every DDL path has to know that the name is special. This required introducing two new concepts across the codebase: "security barrier views" (bans on view inlining in both analyzers, strippingadditional_table_filtersfrom the inner context, rejectingadditional_result_filterin three places, refusing predicate pushdown, removingLowCardinalityfrom the exposed types) and "reserved table names" (guards inInterpreterCreateQuery,InterpreterRenameQuery,DatabasesCommon,DatabaseCatalog, plus validation of a pre-existing table at startup) — around 340 lines across 15 files insrc.Here the same feature is an ordinary system table,
StorageSystemUserQueryLog(195 lines across 4 files insrc, no changes toStorageView,Planner,QueryAnalyzer, the interpreters, or the database layer):read()resolves the configured query log table (query_log.database/query_log.table) at query time and runsSELECT <requested columns> FROM <log table> WHERE if(initial_user != '', initial_user, user) = <current user>under an internal full-access context. The user's session settings are deliberately not propagated into it, so settings such asadditional_table_filterscannot inject expressions into the inner query.read()and embedded into the outer plan as an opaqueReadFromPreparedSource. Plan-level optimizations of the outer query (filter push-down, filter merging) cannot move any outer expression below the user filter, where it could observe other users' rows through a side channel such asthrowIf. This makes the barrier structural instead of defending each channel separately. Note that in a plan-fused design, an outerWHEREmerges with the inner filter intoand(inner, outer)and the safety of athrowIfside channel then depends on the evaluation order and laziness ofand, which is controlled by the user-settableshort_circuit_function_evaluation— an opaque pipeline does not have this dependency at all.LowCardinalityremoved) materializes the result, so dictionaries shared with filtered-out rows cannot leak other users' values.query_log.enable_user_query_logis enabled, which is the default),CREATE/RENAME/DROPofsystem.user_query_logare rejected by the existing generic mechanisms for system tables, and no reserved-name machinery is needed. A leftover user table with this name (e.g., created before an upgrade) produces a clear error at startup.User-visible differences from #104462:
SHOW CREATE TABLE system.user_query_logshows a table withENGINE = SystemUserQueryLograther than a view definition.UNKNOWN_TABLEerror. This also resolves the blocker from the automated review of the original PR.additional_result_filteris not rejected: it is applied above the user filter and is therefore safe.query_log.enable_user_query_log = 0there are no restrictions on the name.clickhouse-local, the table always exists and is empty when the query log is not configured.The integration test for the distributed
initial_usersemantics is taken from the original PR. The behavior was verified with a real binary: a user without any grants sees exactly their own records and cannot readsystem.query_log; athrowIfpredicate never observes other users' rows regardless of how it is injected (WHERE,additional_table_filterskeyed on the source table or on the table itself,additional_result_filter) across both analyzers and allshort_circuit_function_evaluationmodes.Version info
26.8.1.638(included in26.8and later)