Skip to content

Cherry pick #116793 to 26.9: Check access to the source table in the MergeTree introspection table functions - #129041

Merged
robot-clickhouse-ci-2 merged 21 commits into
backport/26.9/116793from
cherrypick/26.9/116793
Nov 11, 2026
Merged

robot-clickhouse-ci-2 merged 21 commits into
backport/26.9/116793from
cherrypick/26.9/116793

Conversation

@robot-clickhouse

Copy link
Copy Markdown
Member

Original pull-request #116793

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 20 commits August 27, 2026 20:13
… functions

`ITableFunction` had no way for a function to declare that it reads another
object's metadata, so every function that does had to remember to check for
itself, and five never did. Two seams were open and they leaked different facts.

`getActualTableStructureWithAccess` is the sole entry point for resolving a
table function's structure from outside `execute`, and it checked only the
source kind (`READ ON S3` and similar), never a source object. Both leaking
functions return an empty `getStorageEngineName`, so even that check was a
no-op for them. A user with no privilege on `db.t` could therefore read its
primary key, its `minmax_*` partition columns and, with `with_marks`, every
physical column and per-substream mark name through
`DESCRIBE mergeTreeIndex(db, t)`, and a projection's columns through
`DESCRIBE mergeTreeProjection(db, t, p)`. `viewIfPermitted` carried both
through by calling the ELSE function's raw `getActualTableStructure`, and on a
column mismatch printed that structure back to the caller.

`execute` performed no source-object check either, and the planner does not
check table functions, so `mergeTreeIndex`, `mergeTreeProjection`,
`mergeTreeTextIndex` and `mergeTreeAnalyzeIndexes` each resolved and inspected
the source before the storage they return authorized anything. That revealed
whether a table exists, its engine, and whether a projection or index of a
given name exists, all without a grant.

This adds one virtual, `checkSourceObjectAccess`, next to `checkSourceAccess`,
called from both base-class seams with the user's context, plus two protected
helpers. `checkSourceTableAccess` checks the grant on the name the function was
given, before that name is resolved. `checkSourceStorageAccess` takes an
already-resolved storage and, when it is a `StorageAlias`, checks the same
privilege on its target, the way `DESCRIBE` of that name does. Without the
alias leg the check would be weaker than the `DESCRIBE` it claims to match,
since `StorageAlias::getInMemoryMetadataPtr` forwards to its target with no
check of its own.

Authorizing a source object always happens at those two seams, under the
context of the user who issued the query, and never in `executeImpl`.
`InterpreterCreateQuery` passes non-empty cached columns, so `execute` returns
a `StorageTableFunctionProxy` whose closure calls `executeImpl` lazily with
`getGlobalContext()`, and a context with no user is full access, so a check
placed there passes unconditionally. `CREATE TABLE ... AS
mergeTreeProjection(db, alias, p)` reaches that path, with an explicit column
list or with the structure taken from the function, and so does the
`mergeTreeTextIndex` form.

The alias leg additionally runs at each site that consumes alias-forwarded
metadata, next to the lookup that produced it, taking that resolved storage
rather than resolving the name a second time, so the check binds the object
whose metadata is then read. A name re-pointed between two lookups would
otherwise leave the checked target and the read target different;
`InterpreterDescribeQuery` reuses its storage for the same reason. On the lazy
path the seam check is the only one that authorizes, so a re-point by a
privileged session between the seam and the read is still possible there, which
is a strictly smaller window than the unconditional pass it replaces.
`mergeTreeIndex` and `mergeTreeAnalyzeIndexes` need no leg at all, because
their `MergeTreeData` cast rejects a `StorageAlias` before any of its metadata
is returned or reported, and `StorageAlias::getName` reports the literal
`Alias` rather than the target's engine. `loop` needs one only where it returns
a structure, since `StorageAlias::read` re-checks `SELECT` per column under the
reader's context.

Resolving a structure requires `SHOW COLUMNS`, which is exactly what
`InterpreterDescribeQuery` requires for the same table, so
`DESCRIBE f(db, t)` agrees with `DESCRIBE db.t` by construction. Execution
requires `SHOW TABLES`. Neither privilege is chosen: a user holding only
`GRANT SELECT (b) ON t` must still be able to read `b` and `b.mark` through
`mergeTreeIndex`, which `02947_merge_tree_index_table_3.sh` and
`02346_text_index_mergeTreeTextIndex_access.sh` assert, and a column grant
confers table-level `SHOW TABLES` but only column-level `SHOW COLUMNS`. The
`SHOW COLUMNS` tier follows the merged precedent in
`04514_table_functions_access_rights_rewrite.sh`.

`mergeTreeTextIndex` and `mergeTreeAnalyzeIndexes` have static structures, so
they owe nothing at the structure seam and override only the execution one.
`mergeTreeAnalyzeIndexes` is covered in its database-and-table form only,
because a UUID cannot be checked before it is resolved and a check placed
after resolution on that path is not effective; that form needs a different
mechanism and a separate change. `mergeTreeCodecBlockCounts` is deliberately
untouched because #116647 fixes that function and is open and approved, so
changing it here would duplicate another author's work and conflict with it.

`viewIfPermitted` forwards the ELSE function's source-kind check and its
structure-level object check on both of its paths, because that wrapper
resolves that structure and nothing else, and may print it in its mismatch
error. This has a user-visible cost: a permitted primary query now also needs
what resolving the ELSE function's structure needs. It also closes an
unauthenticated fetch, since `TableFunctionURL::getActualTableStructure`
performs schema inference when the structure is `auto`, so
`DESCRIBE viewIfPermitted(SELECT 1 ELSE url(...))` made the server fetch with
no `READ ON URL`.

`loop` needed the alias leg too. Its nested inner-function form forwards to
`getActualTableStructureWithAccess`, and its database-and-table form performs
its own `SHOW COLUMNS` check when resolving a structure and its own `SELECT`
check when executing, but both were on the name only, so
`DESCRIBE loop(db, alias)` returned the target's columns to a caller holding
`SHOW COLUMNS` on the alias alone. `04411_loop_table_function_describe_access_check.sh`
already requires that form to agree with a direct `DESCRIBE`, and
`04945_loop_over_table_expression_without_columns_access.sh` already requires
its read path to deny an alias whose target is not granted, so this completes
a contract those two tests assert rather than adding a new one.

Verified as `merge` (skips tables without `SHOW TABLES`, then checks
`SHOW COLUMNS` per table) and the `remote`/`cluster` family are already gated,
and `viewExplain` and the argument-derived and external-source families are not
carriers.

Related: #116647
… assert

The test failed only in `Stateless tests (amd_llvm_coverage, old analyzer, s3 storage,
DBReplicated, WasmEdge, parallel, 1/3)`, on four output lines, from two independent causes.
Both were reproduced locally one dimension at a time, against a diff byte identical to the
one CI reported.

Two arms create a table `AS mergeTreeProjection(db, alias, p)` and
`AS mergeTreeTextIndex(db, alias, 'idx')`, which only the check at the table function
execution seam can deny. In a `Replicated` database the statement is carried out by the DDL
worker, which runs with no user and therefore full access, so no execution-seam check denies
there. That is not specific to the checks added here: the pre-existing `READ ON URL` check in
`ITableFunction::checkSourceAccess` behaves identically, measured as
`CREATE TABLE t (x UInt8) AS url('http://localhost:1/', TSV, 'x UInt8')` being denied under
`Atomic` and accepted under `Replicated` for a user holding no `READ ON URL`. Those two arms
are the only ones pinning the seam-level check on the lazy `CREATE TABLE ... AS` path, so the
test is tagged `no-replicated-database` instead of dropping them. The cost is that the whole
test is skipped in that one job, which is also the only stateless job running the old
analyzer today.

Two further arms reached the `ELSE` function of `viewIfPermitted` only because the analyzer
resolves nested table functions while analysing the arguments. With `enable_analyzer = 0` the
function compares the primary query's single column against the eight the `ELSE` function
declares and throws `BAD_ARGUMENTS` instead, for every user including one with full access,
on this branch and on its base alike. The primary query now reads a table the user can see
but not read, so `isPermitted` returns false and the `ELSE` function is executed under both
analyzers, which is the branch those arms are about.

The reference file is unchanged. With `enable_analyzer = 0` and no replicated database the
test fails before this commit on exactly those two lines and passes after it; the base build
still reddens the same 26 reference lines; and 50 runs with randomization pass under both
analyzers for this test, `02947_merge_tree_index_table_3`,
`02346_text_index_mergeTreeTextIndex_access`,
`04411_loop_table_function_describe_access_check`,
`04945_loop_over_table_expression_without_columns_access` and
`03636_storage_alias_metadata_access_rights`.
The one failed check on the previous head was a job level wall clock timeout of
`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`, not
a test failure. All 13261 tests in that shard ran; exactly one failed,
`04648_replicate_generic_no_quadratic_realloc`, which is not from this pull request
and which the runner's own diagnosis then passed `3` out of `3` reruns; the job
crossed its `9000` second budget by 55 seconds during failure diagnosis and log
collection and was killed with `exit code [-15]`, so praktika recorded
`ERROR: Timeout` and uploaded no test summary. That is why the check is red while
the CI database holds no failing test row for this commit.

Re-running a single job needs write access to the repository, which this account
does not have, so this commit re-triggers the workflow instead. Its tree is
identical to `16339a314a676f37f92305c920121b571f3dd414`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Both sides add a base class access check and call it from the same two seams.
Master's `checkEngineAccess` checks the `TABLE ENGINE` grant; this branch's
`checkSourceObjectAccess` checks access to the object a function reads metadata
from. The concerns are disjoint, so both definitions survive and both are
called from `getActualTableStructureWithAccess` and from `execute`.

The two `Deliberately not under check_source_access` comments stated the same
invariant about the same seam, so they are now one comment covering both calls.

Ordering between the two checks is not observable for anything this branch
touches: `TableFunctionExecutable` is the only override of
`requiresTableEngineGrant` in the tree, so `checkEngineAccess` returns early
for every function that gets a `checkSourceObjectAccess` override here.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ted` resolves its structure

`TableFunctionViewIfPermitted` never reaches the base-class seams for its `ELSE` function:
`getActualTableStructure` calls `else_table_function->getActualTableStructure` directly, so the
wrapper hand-forwards the access checks instead. It forwarded `checkSourceAccess` and
`checkSourceObjectAccess` but not `checkEngineAccess`, so with `table_engines_require_grant = 1`
a user without `TABLE ENGINE ON Executable` could run
`DESCRIBE viewIfPermitted(SELECT 1 AS x ELSE executable(...))`, which `DESCRIBE executable(...)`
denies. Measured: the `DESCRIBE` returned `x UInt8` before and is `ACCESS_DENIED` after. Both
`SELECT` forms were already denied, and `ELSE null(...)` is unaffected because `null` does not
require the grant, so the change is confined to resolving the structure of an `ELSE executable(...)`.

The gap is pre-existing, not introduced by the master merge: master carries no forwarding in this
wrapper at all, so the `ELSE` function's `checkEngineAccess` was unreachable from `viewIfPermitted`
before and after. The forward is added at the seam, in the base seam's own order, rather than by
routing `getActualTableStructure` through `getActualTableStructureWithAccess`: `viewIfPermitted`
leaves `hasStaticStructure` at its default `false`, so `execute` with cached columns returns a lazy
`StorageTableFunctionProxy`, and routing there would defer these checks into that lazy path under
the global context.

Co-Authored-By: Claude Opus 5 <[email protected]>
…cution seams

Every successful execution-seam arm in `05046_table_function_source_access` held full `SELECT` on
the source, and every `CREATE TABLE ... AS` arm was a denial, so strengthening a seam check from
`SHOW TABLES` to `SELECT` - or the delegated `viewIfPermitted` engine check into an unconditional
denial - left the reference unchanged. Three arms close that:

- `mergeTreeProjection` and `mergeTreeAnalyzeIndexes` created from `CREATE TABLE ... AS` with
  explicit columns by a user holding only `SHOW TABLES` on the source. Explicit columns keep the
  storage lazy, so the seam is the only thing that runs, and the count is 2 unless the seam asks
  for more than naming the source. The matching denials for a user without `SHOW TABLES` are
  already in the file, so both directions are now pinned.
- the `viewIfPermitted` `ELSE executable(...)` `DESCRIBE` repeated with
  `TABLE ENGINE ON Executable` granted, which must resolve. The neighbouring `ELSE null(...)` case
  cannot cover this: `null` does not require the grant, so it never reaches `checkEngineAccess`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Its seam asks the same `SHOW TABLES` on the source as the two arms already covered, but every
existing `mergeTreeTextIndex` execution either lacked the alias-target grant or held full `SELECT`,
so strengthening its check to `SELECT` left the reference unchanged. Adding it to the same
`CREATE TABLE ... AS` group with explicit columns takes the count to 3 and pins the third seam.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ivileges

The published description said the current user's permission for the primary query alone decides
whether its result or the `ELSE` function's is returned. Resolving the `ELSE` structure has its own
source and `TABLE ENGINE` privileges, and they are checked before that branch is taken, so an
authorized primary query can still be refused. `viewIfPermitted` is the only table function whose
description makes a permission claim, so it is the only one this affects.

Co-Authored-By: Claude Opus 5 <[email protected]>
`05046_table_function_source_access` reached a median of 175.8 s against the
per-file 180 s limit of `Stateless tests (amd_asan_ubsan, flaky check)`, so 8 of
its 32 runs at the previous head failed with `Test runs too long (> 180s)`. The
median sat 4.2 s under the limit, so that ratio is the arithmetic of the margin
and a re-run cannot move it.

The cost is per `clickhouse-client` invocation and near-uniform across them. The
file spawns 70 clients, and with the flaky check's thread fuzzer one client
costs 0.72 s (0.06 s to spawn, 0.26 s to connect, 0.40 s for the query) while
the queries themselves read 100 rows. Shrinking the fixture therefore saves
nothing; the file has to run fewer statements per file.

Every scenario body moves verbatim, and the four new reference files concatenate
to the previous one byte for byte, so no arm is dropped or weakened. Measured
locally with 50 runs at 8-way self-concurrency against a thread-fuzzer server:
the whole file has a median of 107.6 s and the four parts 48.6, 31.5, 44.6 and
41.2 s, so the largest is 45% of the previous cost and projects to 80 s on that
check. Repeating one fixture in four files costs 54% more test time in total.
…dex`

The alias-backed `mergeTreeTextIndex` arms were all denials, and the positive
text index arms all name a plain table, so a leg that demanded `SELECT` on an
alias target instead of `SHOW COLUMNS` would have left every reference
unchanged. The user holding exactly `SHOW COLUMNS` on the alias and on its
target now reads the index through the alias and reaches the missing index
diagnostic; dropping that target grant turns the same line into
`ACCESS_DENIED`, so the arm is sensitive to the privilege it pins.
`mergeTreeTextIndex` conflicted: master now resolves the source index from
`getActualTableStructure` as well as from `executeImpl`, through a new
`resolveIndex`, which checks `SHOW TABLES` on the source name before any
metadata is read, refuses the function when no user is attached to the context,
and checks `SELECT` on the index columns plus the row policy of the source.

Master's version is kept whole and this branch's override for that function is
dropped: its `SHOW TABLES` check on the source name is now made by
`resolveIndex` on both paths, and its `for_structure` early return is obsolete
because the structure path is no longer static.

What master does not cover is the alias hop, so the one check that is not
redundant moves into `resolveIndex`, before the metadata is read: the metadata
of an `Alias` is its target's, so `getSecondaryIndices().getByName()` reports
whether a table the user cannot see holds that index, and its type.
Master resolves the source index of `mergeTreeTextIndex` to answer a `DESCRIBE`,
so that structure is no longer static and needs `SHOW TABLES` on the source
table; the arm that read it with no grants now pins the denial, and
`mergeTreeAnalyzeIndexes` is left as the static-structure control.

Master also refuses `CREATE TABLE ... AS <MergeTree introspection function>`
outright, before any grant is considered, so the three arms that persisted such
a table now pin that refusal instead of `ACCESS_DENIED`: with no grants on an
alias target, and with exactly `SHOW TABLES` on the source, no table is created
either way, which is what those arms were there to prove.

Measured against the pure-master snapshot build (no hunks of this branch): all
four files still redden without them, including the alias arm that master alone
answers with `There is no index with name 'idx_none'` for a target the user
cannot see.
The three `CREATE TABLE ... AS` arms stop at master's unconditional refusal now,
so they no longer say which privilege the source hooks ask for and would stay
green if a hook were removed or strengthened. The denial message names the
privilege, so reading that name back restores the sensitivity those arms had.

With nothing granted, reading `mergeTreeProjection` and `mergeTreeAnalyzeIndexes`
is denied naming `SHOW TABLES` and resolving a structure naming `SHOW COLUMNS`;
with exactly `SHOW TABLES` the same two reads are denied naming `SELECT`, so the
seam is satisfied by naming the source and asks for nothing stronger.

Measured against the pure-master snapshot build: without these hooks the first
two lines name `SELECT` and the structure line disappears, so all three arms
redden. The `SHOW TABLES` pair is the over-blocking control and is green on both
builds by design.
…ce-object-access

Check access to the source table in the MergeTree introspection table functions
@robot-clickhouse robot-clickhouse added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Nov 3, 2026
Resolve the conflicts by porting only the hunks of #116793. The
conflicting regions hold code of master PRs that are not on 26.9
(#125401 refreshExternalMetadata in TableFunctionLoop.cpp, #123364
SecretArgumentsSpec in TableFunctionViewIfPermitted.cpp); they are
left as on 26.9.

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

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

I resolved the conflicts on my fork. The branch is a merge of backport/26.9/116793 into cherrypick/26.9/116793, so it fast-forwards the cherry-pick branch:

git fetch https://github.com/groeneai/ClickHouse groeneai/resolve-26.9-cherrypick-116793 && git push origin FETCH_HEAD:cherrypick/26.9/116793

@robot-ch-test-poll2

Copy link
Copy Markdown
Contributor

Dear @nikitamikhaylov, @groeneai, this cherry-pick PR has not been updated for 3d0h2m20s. Please resolve the conflicts to backport #116793, or close this PR if the backport is no longer needed. This PR will be automatically closed after 7 days of inactivity.

@robot-clickhouse-ci-2
robot-clickhouse-ci-2 merged commit 21b07dd into backport/26.9/116793 Nov 11, 2026
2 checks passed
@robot-clickhouse-ci-2
robot-clickhouse-ci-2 deleted the cherrypick/26.9/116793 branch November 11, 2026 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants