Skip to content

Support SQL SECURITY for TimeSeries tables and check access in their table functions - #120267

Draft
vitlibar wants to merge 1 commit into
ClickHouse:masterfrom
vitlibar:timeseries-fix-access-rights
Draft

vitlibar wants to merge 1 commit into
ClickHouse:masterfrom
vitlibar:timeseries-fix-access-rights

Conversation

@vitlibar

@vitlibar vitlibar commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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

Support SQL SECURITY for TimeSeries tables and check access in their table functions

A TimeSeries table runs the queries over its target tables with the permissions given by its
DEFINER / SQL SECURITY clauses, so reading or writing it requires privileges on the table only.
timeSeriesSelector, prometheusQuery and the Prometheus HTTP API follow the same rule and require
SELECT on the columns they read. timeSeriesSamples, timeSeriesTags and timeSeriesMetricFamilies
return a target table itself, so they require SHOW COLUMNS on the TimeSeries table and the privilege
on the target table.


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

@vitlibar vitlibar added do not test disable testing on pull request comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Sep 15, 2026
@vitlibar
vitlibar force-pushed the timeseries-fix-access-rights branch from db5a301 to 2fd720e Compare October 14, 2026 14:02
@vitlibar vitlibar removed the do not test disable testing on pull request label Oct 14, 2026
@vitlibar vitlibar changed the title [WIP] Support SQL SECURITY for TimeSeries tables and check access in their table functions Support SQL SECURITY for TimeSeries tables and check access in their table functions Oct 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c583cc9]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_prometheus_protocols/test_insert_select.py::test_select_tags_with_separate_column FAIL cidb
test_prometheus_protocols/test_insert_select.py::test_select_with_row_policy FAIL cidb
Stateless tests (amd_debug, parallel) FAIL
05255_timeseries_time_ranges_table FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05255_timeseries_time_ranges_table FAIL cidb
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

Adds DEFINER / SQL SECURITY to TimeSeries and access checks to its table functions and Prometheus endpoints. ❌ Block: one newly identified privilege bypass and four remaining prior findings need attention; two of the prior findings were deliberately deferred or accepted by the author and are retained below without further inline replies.

Findings

❌ Blockers

  • src/Storages/StorageTimeSeries.cpp:948: ALTER SETTINGS can install an expression that executes as another user. The new context makes TimeSeriesSink evaluate id_generator as the definer, while replacing it still requires only ALTER SETTINGS. A user with ALTER SETTINGS, INSERT and SELECT on ts can install tuple(sipHash64(metric_name), dictGetUUID('db.private_dictionary', 'secret', toUInt64(1))), insert a sample and read the secret UUID through timeSeriesSelector. Require SET DEFINER (or ALLOW SQL SECURITY NONE) when modifying/resetting this executable expression under the corresponding security mode, as already done for replacing a view body. New inline finding.
  • src/Storages/StorageTimeSeriesSelector.cpp:1081: Source row policies remain bypassable. [dismissed by author -- https://github.com/Support SQL SECURITY for TimeSeries tables and check access in their table functions #120267#discussion_r4272231493] The author considers this pre-existing and defers the fix. It still violates the source-table access contract: USING 0 on ts denies a direct read, but the selector reads its targets as the definer without applying that policy. prometheusQuery, prometheusQueryRange, remote-read and HTTP series/labels/metadata share this gap. Apply the caller's source policy, or reject these paths when it cannot be enforced.

⚠️ Majors

  • src/Storages/StoragePrometheusQuery.cpp:113: prometheusQuery and prometheusQueryRange reject sufficient column grants. Table-wide SHOW COLUMNS is required before the generated selector's column-aware checks. A user with SELECT(metric_name, tags, samples) therefore fails despite satisfying the documented read contract. Mirror the selector's early checks on known columns, followed by its version-dependent samples-column check. Existing finding.
  • src/Server/PrometheusRequestHandler.cpp:286: The shared HTTP lookup rejects sufficient column grants for every data endpoint. Its table-wide SHOW COLUMNS check runs before the endpoint-specific SELECT / INSERT checks, denying readers or writers granted exactly the columns their requests use. Check the concrete required columns before lookup and any version-dependent columns afterward. Existing finding.
  • src/Interpreters/InterpreterCreateQuery.cpp:2140: Short ATTACH silently replaces legacy invoker semantics. [dismissed by author -- https://github.com/Support SQL SECURITY for TimeSeries tables and check access in their table functions #120267#discussion_r4272231528] The author accepts this for the experimental engine. It still contradicts the new documentation: attaching a stored definition without a security clause fills in the session default and attaching user's identity, whereas startup loading preserves invoker behavior. Preserve absent security for replayed definitions, or explicitly document and constrain this migration instead of promising invoker behavior until an explicit alteration.
Missing context / blind spots
  • ⚠️ No local build or clickhouse executable was available, so the new ID-expression exploit was verified by tracing the settings authorization, expression evaluation and selector output paths; it was not executed. A focused regression against the PR binary would provide runtime confirmation.
Tests
  • ⚠️ Add a stateless case proving an unrelated user with ALTER SETTINGS, INSERT and SELECT cannot replace a definer-owned id_generator with a private dictionary lookup; verify authorized changes still work.
  • ⚠️ Add successful column-only grants for both PromQL table functions and the affected HTTP read/write endpoints, plus denied reads/structure discovery without sufficient grants. The new shell test covers only a subset of these entrypoints.
  • ⚠️ Prove source deny policies hold through selectors and HTTP endpoints. The added row-policy test exercises direct SELECT only. If legacy invoker preservation remains the documented contract, cover DETACH / short ATTACH of a definition without a security clause.
Final Verdict

❌ Block. Close the executable-setting privilege bypass and enforce source row policies (or reject unsupported policy-bearing paths); align access checks with the promised column grants, and reconcile legacy ATTACH with its documented behavior. Add focused regressions for these contracts. Dismissed findings remain summary-only.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Oct 14, 2026
Comment thread src/Storages/StorageTimeSeries.cpp Resolved
AccessType::SELECT,
config.time_series_storage_id,
Strings{TimeSeriesColumnNames::MetricName, TimeSeriesColumnNames::Tags, TimeSeriesColumnNames::getOuterSamples(time_series_storage->getVersion())});
auto target_tables_context = time_series_storage->getSQLSecurityOverriddenContext(context);

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.

[P1] Enforce the source table's row policy before reading as its definer

checkAccess checks grants, but does not apply row policies. Here the generated queries read the tags and samples targets under the definer, and no query reads config.time_series_storage_id as the caller. The outer planner sees a StorageTimeSeriesSelector with a table-function storage ID, so it cannot apply the policy attached to the real TimeSeries table either.

Create a nonempty ts with SQL SECURITY DEFINER, grant reader only SELECT on ts, and attach CREATE ROW POLICY deny ON ts USING 0 TO reader. A direct read returns no rows, but timeSeriesSelector(ts, 'http_requests', ...) returns samples. prometheusQuery, prometheusQueryRange, PromQL HTTP queries and remote-read inherit this bypass. The new HTTP series/labels/metadata paths similarly check only grants before querying targets as the definer.

Apply the caller's policy on the source table to these reads, or reject these entrypoints when a nontrivial source policy is active until it can be honored. Add a caller-only deny-policy regression covering the selector and HTTP paths.

@vitlibar vitlibar Oct 14, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a preexisting problem and it's difficult to fix it at this point.
It will be fixed in a separate PR.

@vitlibar
vitlibar force-pushed the timeseries-fix-access-rights branch 2 times, most recently from ddd7a4d to 6f140b8 Compare October 14, 2026 22:44

/// Only the definition of the TimeSeries table is read here, so the `SHOW COLUMNS` privilege is checked before the table
/// is found. The data is read by `timeSeriesSelector` in the generated SQL, which checks the `SELECT` privilege on the read columns.
context->checkAccess(AccessType::SHOW_COLUMNS, time_series_storage_id);

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.

[P1] Keep prometheusQuery{Range} compatible with column-level grants

This table function now rejects users before the generated SQL runs unless they have table-wide SHOW COLUMNS on the TimeSeries table. That is stronger than the contract in the PR body/docs: a user with SELECT(metric_name, tags, samples) on db.ts can satisfy the actual read, but context->checkAccess(AccessType::SHOW_COLUMNS, time_series_storage_id) fails here first. timeSeriesSelector already avoids that regression by checking the known read columns before lookup and the version-dependent samples column after lookup.

Please mirror that pattern here instead of requiring whole-table SHOW COLUMNS, and add a regression where prometheusQuery / prometheusQueryRange are executed under column grants without table-wide SHOW COLUMNS.

StoragePtr checkAccessAndGetTable()
{
auto table_id = getTimeSeriesTableID();
context->checkAccess(AccessType::SHOW_COLUMNS, table_id);

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.

[P1] The shared HTTP lookup now over-constrains every Prometheus endpoint

This helper runs before the endpoint-specific access checks, so /api/v1/query, remote-read, remote-write, series/labels, and metadata all require table-wide SHOW COLUMNS just to resolve the TimeSeries storage. That blocks legitimate users who only have the advertised column-level rights (for example SELECT(metric_name, tags, samples) for query/read or column-level INSERT for remote-write), even though the later code already performs the concrete SELECT / INSERT checks each path needs.

Please move this precheck out of the shared helper and mirror the timeSeriesSelector approach per endpoint: fail early on the concrete columns that are known up front, then check any version-dependent column after loading the table. A regression with column grants but no table-wide SHOW COLUMNS would catch this.

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c583cc9b8 with master 16da7cdb0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of f71da6750; 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

1377 translation units recompiled, 8956 s compile time in total, 1376 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 8.4 s

Job report

…table functions

A `TimeSeries` table runs the queries over its target tables with the permissions given by its
`DEFINER` / `SQL SECURITY` clauses, so reading or writing it requires privileges on the table only.
`timeSeriesSelector`, `prometheusQuery` and the Prometheus HTTP API follow the same rule and require
`SELECT` on the columns they read. `timeSeriesSamples`, `timeSeriesTags` and `timeSeriesMetricFamilies`
return a target table itself, so they require `SHOW COLUMNS` on the `TimeSeries` table and the privilege
on the target table.
@vitlibar
vitlibar force-pushed the timeseries-fix-access-rights branch from 6f140b8 to c583cc9 Compare October 15, 2026 03:05
return std::make_shared<TimeSeriesSink>(*this, metadata_snapshot->getSampleBlock(), insert_columns, local_context, async_insert);
/// The inserts into the target tables run with the permissions given by the SQL security of this table.
return std::make_shared<TimeSeriesSink>(
*this, metadata_snapshot->getSampleBlock(), insert_columns, getSQLSecurityOverriddenContext(local_context), async_insert);

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.

[P1] Authorize changes to id_generator before running it as the definer

Passing the overridden context to the whole TimeSeriesSink also makes initTagsAndSamplesPipelines evaluate the stored id_generator with the definer's privileges (TimeSeriesSink.cpp:508-512, 563-578). However, checkSettingCanBeAltered still permits changing that expression, and InterpreterAlterQuery::getRequiredAccessForCommand requires only ALTER SETTINGS for it. There is no corresponding SET DEFINER / ALLOW SQL SECURITY NONE check.

For example, on an administrator-defined table with the default tuple ID, a user granted only ALTER SETTINGS, INSERT and SELECT on ts can replace the generator with:

tuple(sipHash64(metric_name), dictGetUUID('db.private_dictionary', 'secret', toUInt64(1)))

The next insert reads the private dictionary as the administrator and stores its UUID in the series ID, which the user can retrieve through timeSeriesSelector, despite lacking dictGet on that dictionary or SET DEFINER. Before this change, the same expression ran as the inserting user and failed its dictionary access check.

Require authorization to replace expressions executed as another definer (and under SQL SECURITY NONE) when modifying/resetting id_generator, analogous to the existing protection for ALTER ... MODIFY QUERY. Add a stateless regression with an unrelated definer and a user having only table-level grants.

qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Nov 24, 2026
`timeSeriesSamples`, `timeSeriesTags`, `timeSeriesTimeRanges` and
`timeSeriesMetricFamilies` (and the aliases `timeSeriesData`,
`timeSeriesMetrics`) look up the TimeSeries table and its target in
`parseArguments` and then return the target's columns, but nothing in the
class checks a privilege on the TimeSeries table. A user with only
`SHOW TABLES` on `db.ts` (or no grant on it at all) therefore got the
target's columns from `DESCRIBE TABLE timeSeriesSamples('db', 'ts')` and
`DESCRIBE (SELECT ...)`, and could `SELECT` from the target, also through a
`remote()` local shard or parallel replicas, while `DESCRIBE TABLE db.ts`
is denied.

Check `SHOW COLUMNS` on the resolved TimeSeries table id before the lookup,
the privilege `DESCRIBE TABLE db.ts` checks at the same point, through the
existing `ITableFunction::checkSourceTableAccess` helper. `parseArguments`
runs before every use of the function, so one check covers every spelling
and all four functions. A table-level `SELECT` or `INSERT` on the TimeSeries
table implies `SHOW COLUMNS`, so ordinary readers and writers are unaffected;
a missing table now gives `ACCESS_DENIED` to a user without the grant, as a
direct `DESCRIBE` does. The Prometheus `/api/v1/metadata` endpoint reads
through `timeSeriesMetricFamilies` as the request's user and inherits the
check.

`timeSeriesSelector`, `prometheusQuery` and `prometheusQueryRange` are not
changed: they are the PromQL engine's read path, can be persisted with
`CREATE TABLE ... AS`, and their access design is the owner's open work
(ClickHouse#120267).

Closes ClickHouse#133495 (the `dictionary(...)` half was fixed by ClickHouse#122678).

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant