Skip to content

Check access to the source table in the MergeTree introspection table functions - #116793

Merged
nikitamikhaylov merged 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/table-function-source-object-access
Nov 3, 2026
Merged

nikitamikhaylov merged 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/table-function-source-object-access

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116647
Related: #116647 (comment)
Related: #120529

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed the access checks of the mergeTreeIndex, mergeTreeProjection, mergeTreeTextIndex, mergeTreeAnalyzeIndexes, viewIfPermitted and loop table functions. Resolving their structure, for example with DESCRIBE, required no privilege on the source table, an Alias source was read with no privilege on its target, and a source that did not exist or had another engine was named in the error. viewIfPermitted resolved an ELSE executable(...) with no TABLE ENGINE grant. Reading them was already checked.

Description

Follow-up to #116647. ITableFunction had no way to say a function reads another object's metadata, so each checked for itself; five did not.

getActualTableStructureWithAccess checked only the source kind (READ ON S3), never a source object, so DESCRIBE mergeTreeIndex(db, t) returned the primary key and every per-substream mark name of a table the caller cannot DESCRIBE, and mergeTreeProjection a projection's columns. execute checked nothing either.

I add one virtual, checkSourceObjectAccess, called from both seams. Resolving a structure requires SHOW COLUMNS, what DESCRIBE of that table needs; execution requires SHOW TABLES, which still reveals whether a named index or projection exists. Neither is chosen: 02947_merge_tree_index_table_3 forbids SHOW COLUMNS there, 04514 is the merged precedent.

StorageAlias forwards metadata to its target unchecked, so the check binds that target too, at the seam and each consuming site. loop got it on its structure path, a contract 04411 and 04945 assert.

viewIfPermitted now forwards the ELSE function's checks even when the primary query is permitted, since it resolves and prints that structure in its mismatch error: viewIfPermitted(SELECT 1 ELSE url(...)) no longer infers a schema without READ ON URL, nor resolves an ELSE executable(...) without a TABLE ENGINE grant.

Not covered: mergeTreeAnalyzeIndexesUUID (a UUID names nothing) and dictionary (its own privilege decision). Residuals: view and eval resolve a structure through the analysis-only planner path, which checks no table-function node, so DESCRIBE view(SELECT * FROM mergeTreeIndex(db, t, with_marks = true)) needs only SHOW TABLES; closing it means checking table functions in the planner. A read of no rows through loop still reports an Alias target's columns. Reading mergeTreeProjection through an Alias fails an internal cast; unwrapping or rejecting is separate.

Complements #116629 (same class, timeSeries*).


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

Version info

  • Merged into: 26.11.1.1224-master (included in 26.11 and later)

… 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 ClickHouse#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: ClickHouse#116647
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex), 3 rounds: 21 findings, 13 fixed in
this branch, 5 declined with the evidence below, 3 noted. All fixes are in 80b2ec3.

# Sev Finding Verdict Evidence / action
1 ❌ The alias-target leg resolved the source name a second time, so a re-point between the two lookups left the checked target and the read target different. AGREE, fixed @ 80b2ec3 The leg now takes the already-resolved storage at each site that consumes alias-forwarded metadata, the way InterpreterDescribeQuery reuses its storage.
2 ❌ On CREATE TABLE ... AS mergeTreeProjection(...) and the mergeTreeTextIndex form, the storage is built lazily under the global full-access context, so the alias leg passed unconditionally there. AGREE, fixed @ 80b2ec3 Authorization moved to the two base-class seams, under the querying user's context; the consumption-site call stays so the check binds the object actually read. Two new arms pin it, and deleting the leg from mergeTreeProjection alone reddens exactly one arm.
3 ❌ loop's structure path checked SHOW COLUMNS on the requested name but not on an Alias source's target, so it still returned the target's columns. AGREE, fixed @ 80b2ec3 Same helper, same privilege.
4 ⚠️ The test proved SHOW COLUMNS necessary but not sufficient: raising the requirement to SELECT would have left the reference file unchanged. AGREE, fixed @ 80b2ec3 Two users now hold exactly SHOW COLUMNS, one on the source and one on an alias and its target, and assert real column output. A SHOW COLUMNS to SELECT mutation at all six sites reddens exactly 3 arms and nothing else.
5 ⚠️ Two statements in the commit message were false: a self-contradiction about where the check belongs, and "before any metadata is read" for mergeTreeIndex, which reads that metadata one line before the cast. AGREE, fixed @ 80b2ec3 Both restated. The conclusion for mergeTreeIndex holds for a different reason: nothing of the target is returned or reported.
6 ❌ mergeTreeCodecBlockCounts is left without a source-object check, the same leak. DISAGREE #116647 fixes that function, in getActualTableStructure before the dynamic_cast and again in read. This branch is based on a commit that predates it, which is the only reason it reads as unchecked here. Adding it would duplicate an approved fix and conflict with an open PR by another author.
7 💡 The changelog category should be Critical Bug Fix (crash, data loss, RBAC). DISAGREE #116647 fixes the identical class in a sibling function and is labelled pr-bugfix. I follow that classification rather than escalate on my own.
8 ⚠️ Add a positive DESCRIBE viewIfPermitted(...) case, since every wrapper-specific arm is a denial and none proves the forwarded check is satisfiable. DISAGREE A positive arm does not redden when a check is removed, so it would stay green under every deletion mutant. The two over-strict mutants the wrapper admits are already covered: forwarding the caller's mode instead of structure mode reddens exactly the SHOW TABLES but not SHOW COLUMNS arm (measured), and the ELSE function's own structure requirement is pinned by the SHOW COLUMNS only section. The arm would catch no mutant an existing arm does not.
9 ⚠️ On the lazy path the seam check is the only authorization, so a privileged session re-pointing the alias between the seam and first materialization is still unchecked. DISAGREE on the remedy Left open on purpose, and stated in the commit message. Binding the authorized storage into the lazy closure changes ITableFunction::execute's contract for every table function, which is more than this fix should carry, and the window is strictly smaller than the unconditional pass it replaces. Metadata only: reads still go through each storage's own per-column SELECT check.
10 💡 Noticed, not raised: url resolves its delegate's structure without forwarding this hook (no delegate implements it, and its execution path already runs through execute); the new denial wording differs from the two existing alias sites, which say "... to describe/show metadata exposed by X"; the comment above the last viewIfPermitted arm credits the delegated check where the ELSE path's own execution check is what denies; and SELECT from mergeTreeProjection with an Alias source still surfaces a std::bad_cast rather than a clear message. Noted No change here.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260827-202000

@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, single run, not probabilistic. clickhouse-test 05046_table_function_source_access fails on a master build and passes on this one.
b Root cause explained? ITableFunction had no seam for "I read another object's metadata", so getActualTableStructureWithAccess and execute checked only the source kind and never the source object.
c Fix matches root cause? The check is added at the two base-class seams, not guarded at the sites that throw. No widened bounds, no no-random-* tag, no defensive masking.
d Test intent preserved / new tests added? No test removed or weakened. One new test, 52 arms under 15 headers across four users; 22 redden on master, the rest pin non-regression. Five mutations show the added arms are live and narrow (see below).
e Both directions demonstrated? Yes, per arm. Master's output is recorded arm by arm (a column list, an engine-revealing BAD_ARGUMENTS, a projection or index error, UNKNOWN_TABLE, or a successful CREATE); all 22 become ACCESS_DENIED.
f Fix is general across code paths? Every sibling enumerated by reading each getActualTableStructure and each executeImpl body, not by grepping files. Fixed: mergeTreeIndex, mergeTreeProjection, mergeTreeTextIndex, mergeTreeAnalyzeIndexes (name form), viewIfPermitted, and loop (its nested inner-function form was already gated, its database-and-table form checked the name but not an Alias target). Verified already gated: merge, the remote/cluster family. Verified not carriers: viewExplain and the argument-derived and external-source families.
g Fix generalizes across inputs (params/datatypes/wrappers)? with_marks/with_minmax; name- and UUID-addressed forms; a MergeTree source, a Log source, a source that does not exist, and a source reached through a StorageAlias; a projection name and an index name that do not exist; four privilege states (none, column-only, SHOW TABLES-only, table-level).
h Backward compatible? No setting, no serialization format, no default changed, so no SettingsChangesHistory.cpp entry. The tightening for narrowly granted users is the intended behaviour change and is described in the PR body.
i Invariants and contracts preserved? Checks run before the source is resolved, so they cannot themselves leak existence. Authorization happens at the two base-class seams under the querying user's context, never in executeImpl, precisely because InterpreterCreateQuery reaches it lazily under a context with no user and therefore full access; the alias leg additionally runs where the metadata is consumed so it binds the object actually read. The leg resolves the target only after the check on the requested name passes and uses the non-throwing tryGetTable, which also caches nothing on a miss: measured, an authorized user still gets UNKNOWN_TABLE for a missing source, and that is a permanent arm.

Also run: 27 existing tests covering these functions, including all 13 that use loop. 25 are green;
the two that fail do so identically on a master build, with byte-identical failure reasons, for a
hardcoded default port (9000 and 8123) that no local server listens on. Among the green ones,
02947_merge_tree_index_table_3.sh and 02346_text_index_mergeTreeTextIndex_access.sh have the
column-only-grant arms that force SHOW TABLES rather than SHOW COLUMNS on the execution seam, and
04411_loop_table_function_describe_access_check.sh plus
04945_loop_over_table_expression_without_columns_access.sh are the merged tests whose contract the
loop leg completes. 50 randomized runs each of the new test and those four: 250/250 pass.

Five mutations, each reddening a disjoint and narrow set: viewIfPermitted forwarding the caller's
mode instead of structure mode reddens exactly 1 reference line; deleting the Alias leg from
mergeTreeProjection's structure seam reddens exactly 1; demanding SELECT instead of SHOW COLUMNS
at the structure seam reddens exactly 5, all of them the arms that pin SHOW COLUMNS as sufficient at
that seam; deleting the Alias leg from mergeTreeProjection's access-check seam reddens exactly 1,
the CREATE TABLE ... AS arm; and demanding SELECT at every Alias-target site reddens exactly 3,
the arms that pin SHOW COLUMNS as sufficient on the target.

Session id: cron:clickhouse-impl-slot-40:20260827-190100

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c454021]

Summary: ✅


AI Review

Summary

The PR adds source-object authorization to table-function structure resolution and execution, including delegated checks for viewIfPermitted and alias metadata checks. It closes the direct grant-less schema disclosure, but several entrypoints still expose protected metadata. Focused reproductions with the fast-test binary for head c4540213d703d9e3b124a08b12b917f1438f3ba3 confirmed the findings below. One finding is new; the others consolidate still-valid prior findings without repeating their inline discussions.

Missing context / blind spots
  • ⚠️ Current-head CI is still running. The underlying Praktika JSON reports the functional Bugfix validation and main stateless jobs as pending; the report-fetching tool's “all-green” message does not establish completion. Completed regression jobs would close this gap. Current-head report.
Findings

❌ Blockers

  • Named loop sources are resolved before authorization. TableFunctionLoop.cpp:132: the added check protects structure resolution only. Execution still calls getDatabase and tryGetTable before its SELECT check at line 157. A caller with only CREATE TEMPORARY TABLE receives ACCESS_DENIED for an existing source, UNKNOWN_TABLE for a missing table, and UNKNOWN_DATABASE for a missing database. Move authorization ahead of both lookups and test the read entrypoint with missing sources.

  • Header inference through view and eval bypasses the structure privilege. ITableFunction.cpp:93 [dismissed by author -- https://github.com/Check access to the source table in the MergeTree introspection table functions #116793#discussion_r3876078510]. DESCRIBE view(SELECT * FROM mergeTreeIndex(hidden, t, with_marks = true)) succeeds with only SHOW TABLES, revealing the primary key and physical column names; the projection wrapper likewise returns projection columns. The sample-block path executes nested functions in execution mode and skips their storage read. The author deliberately deferred the planner change; the protected schema remains observable. Propagate structure-mode authorization through header inference while preserving supported column-only reads.

  • Projection and index diagnostics still disclose protected metadata with only SHOW TABLES. ITableFunction.cpp:93 [dismissed by author -- https://github.com/Check access to the source table in the MergeTree introspection table functions #116793#discussion_r3971499612]. A caller unable to describe or read the source still gets NO_SUCH_PROJECTION_IN_TABLE for a guessed projection and There is no index with name 'missing_index' for a guessed text index, before the later read authorization. Unlike the engine name, these facts are not already available through system.tables. The author confirmed and deferred this residual. Authorize the relevant metadata before validation without imposing table-wide SHOW COLUMNS on legitimate column-scoped reads.

  • The UUID variant skips source-object authorization. TableFunctionMergeTreeAnalyzeIndexes.cpp:252 [dismissed by author -- https://github.com/Check access to the source table in the MergeTree introspection table functions #116793#discussion_r3896259911]. An ungranted caller knowing a Log table's UUID receives Storage MergeTreeAnalyzeIndexes expected MergeTree table, got: Log before the read-time check; an unknown UUID follows a different error path. UUID possession must not replace authorization, including after grants are revoked. Check the resolved table's identity before constructing the introspection storage. The author's scope decision does not eliminate the observed disclosure.

  • Nested TimeSeries functions still inspect sources during argument parsing. ITableFunction.h:136 [dismissed by author -- https://github.com/Check access to the source table in the MergeTree introspection table functions #116793#discussion_r3930974946]. On the current code, DESCRIBE loop(timeSeriesMetrics(hidden, t)) with no source grant returns UNEXPECTED_TABLE_ENGINE, including the protected table's UUID. TableFunctionFactory::get invokes the child's parseArguments before either new authorization seam; the direct function and viewIfPermitted carrier have the same ordering. The author deferred this to the sibling family, but the current head still reproduces it. Authorize inside the earliest source-resolving path, before catalog lookup or engine validation.

⚠️ Majors

  • loop bypasses nested functions' persistence vetoes. TableFunctionLoop.cpp:132; existing thread. CREATE TABLE own.persisted AS loop(mergeTreeIndex(hidden, t)) succeeds, retains the expression in SHOW CREATE TABLE, and can be materialized. InterpreterCreateQuery recursively checks only dependsOnCurrentUserGrants, whereas these introspection functions and eval prohibit persistence through canBeUsedToCreateTable. Their prohibited lifetime/global-context behavior remains reachable through loop. Enforce the nested veto or have loop reject such persisted children.

  • Authorized alias projection reads still produce an internal exception. TableFunctionProjection.cpp:103 [dismissed by author -- https://github.com/Check access to the source table in the MergeTree introspection table functions #116793#discussion_r3876082398]. After the new alias authorization succeeds, the storage constructor still casts StorageAlias directly to MergeTreeData, producing std::bad_cast even for the full-access user. The author deliberately deferred the supported-source decision; the read path still fails. Explicitly reject unsupported aliases with a user-facing exception, or unwrap them with defined privilege and row-policy semantics.

Tests
  • ⚠️ Add the smallest stateless case distinguishing authorization from source existence in named loop reads: an ungranted existing table, missing table, and missing database must all deny access before resolution.
  • ⚠️ The existing tests do not enforce the remaining boundaries: header-only wrappers, guessed projection/index names with SHOW TABLES only, an ungranted non-MergeTree UUID, early nested-source parsing, and nested persistence vetoes. Add focused negative cases when closing these paths, preserving positive column-scoped access coverage.
Final Verdict

❌ Block. Complete authorization before protected metadata can be observed on the remaining entrypoints, enforce nested persistence vetoes, define alias projection rejection/support, and add focused regression coverage. Dismissed findings above remain summary-only; no repeat inline replies were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @nikitamikhaylov, could you review this? It adds one virtual to ITableFunction, called from both base-class seams that resolve a table function, so a function that derives its structure from another object declares that once instead of each remembering to check for itself: resolving a structure now requires SHOW COLUMNS on the source, exactly what DESCRIBE of it requires, execution requires SHOW TABLES, and an Alias source also requires the privilege on its target.

Comment thread src/TableFunctions/ITableFunction.cpp Resolved
Comment thread src/TableFunctions/ITableFunction.h Resolved
Comment thread src/TableFunctions/ITableFunction.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit c4540213d703d9e3b124a08b12b917f1438f3ba3 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

… 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`.
@PedroTadim

Copy link
Copy Markdown
Member

cc @rienath @yariks5s

@rienath

rienath commented Aug 28, 2026

Copy link
Copy Markdown
Member

@PedroTadim looks good to me, but this is API change to ITableFunction.h‎. It's better for a component owner to take a look

@groeneai

Copy link
Copy Markdown
Collaborator Author

Review is already requested for exactly that reason: #116793 (comment) (2026-08-27 21:12Z) asks @ pufit and @ nikitamikhaylov and calls out the ITableFunction change.

By history they are the right owners: 63057e7 ("Fix RBAC bypass for DESCRIBE/CREATE TABLE AS via table functions") by @ pufit added the two seams this PR extends, getActualTableStructureWithAccess and checkSourceAccess, so the new virtual sits on that design. @ nikitamikhaylov is also an author of the file.

checkSourceObjectAccess has an empty body in the base class, so no existing derived function changes behaviour; five override it here. If a different owner should sign off on the interface, name them and I will route it there instead of adding a second ping.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 16339a3

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
will be posted here when it opens. Only CH Inc sync is exempt.

175 check-runs, 0 incomplete, Finish Workflow success at 11:56:27Z, single workflow run. One
real red, and it is not caused by this PR: the diff is src/TableFunctions/* plus one new
stateless test, and neither failure below touches that code.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / job level job hit its 9000s wall clock (7246s of tests, then log collection), so per-test results were never uploaded and CIDB records only a bare job-level error #116209 (ours, open) - splits this exact un-batched job into 2 batches
the same check / 04648_replicate_generic_no_quadratic_realloc TIMEOUT_EXCEEDED, elapsed 66020 ms against the test's own SETTINGS max_execution_time = 60, on the cheapest carrier in the file ([toLowCardinality('x')]), which returned correct results. Coverage instrumentation plus 12-way suite load makes that cap the first thing to trip, which the file's own comment expects to be the runner timeout instead a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
CH Inc sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR are rollups of the first row, not separate failures.

Session id: cron:our-pr-ci-monitor:20260828-123000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 04648_replicate_generic_no_quadratic_realloc timeout on Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel): #116918. The arm that reported it holds no JSON object, so it never reaches the quadratic path the test guards and its wall clock cannot detect a regression; that PR drops the limit from the four such arms and keeps it on the nine carriers.

pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Aug 28, 2026
`loop` authorizes the table name it is given, but an `Alias` publishes its
target's metadata eagerly while the target's own authorization happens lazily,
inside the synthetic `SELECT` that `LoopSource::initLoop` builds. `StorageLoop`'s
constructor copies the inner storage's metadata into its own, and for a
`StorageAlias` that metadata is the target's, so the response header is populated
before any row is read. A query that pulls no rows never reaches the lazy check
and receives the target's column names and types.

A user holding `SELECT, SHOW COLUMNS` on the alias and nothing on the target
therefore gets the target's structure from
`SELECT * FROM loop(db, ali) LIMIT 0`, from
`EXPLAIN header = 1 SELECT * FROM loop(db, ali) LIMIT 0` and from
`DESCRIBE TABLE (SELECT * FROM loop(db, ali) LIMIT 0)`, while every direct path
denies the same user: `DESCRIBE ali`, `SHOW CREATE TABLE ali` and
`SELECT * FROM ali LIMIT 0` all return `ACCESS_DENIED`. Rows are never disclosed,
so the leak is metadata only.

The check goes in `TableFunctionLoop::executeImpl`, right after the existing
table-level `SELECT` check on the given name and before `StorageLoop` is
constructed. `PlannerJoinTree.cpp` states that access rights for table functions
are checked in `ITableFunction::execute`, so that is the designated seam, and it
is not gated by `only_analyze`, which is what covers the `DESCRIBE (subquery)`
vector. `isTargetTableGranted` is a name-based grant probe that never resolves
the target, so a dangling `Alias` still reports `UNSUPPORTED_METHOD` to a caller
granted the dropped target's name, and full-access behaviour is unchanged.

The tier is table-level `SELECT`, matching what `loop` already demands of the
name it is given. Table-level `SELECT` implies table-level `SHOW_COLUMNS`, so no
caller receives a column list it could not already have read with `DESCRIBE`.
Table-level `SHOW_COLUMNS` and `SHOW_TABLES` were both rejected as tiers because
a column grant does not imply the former and does imply the latter, so each
admits or rejects the wrong caller. Accepted cost: a caller holding only a
column-level `SELECT` grant on the target can no longer use `loop` over the
alias, although reading the alias directly still works.

One arm of `04945_loop_over_table_expression_without_columns_access` changes from
`UNSUPPORTED_METHOD` to `ACCESS_DENIED`: its alias is dangling and the caller
holds nothing on the dropped target, and a direct `DESCRIBE` of that alias
already denies. Arms are added to show that this is a tightening and not a loss.

ClickHouse#116793 closes the structure seam of the same invariant,
`DESCRIBE loop(db, alias)`, at the same tier; this closes the read seam. An
unauthorized `CREATE TABLE ... AS loop(...)` still succeeds, because
`ITableFunction::execute` defers `executeImpl` through a closure carrying the
global context; that belongs to the source-object seam ClickHouse#116793 adds, not here.

Co-Authored-By: Claude Opus 5 <[email protected]>
@nikitamikhaylov nikitamikhaylov self-assigned this Aug 31, 2026
@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai make the PR green.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

The only red check is Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) (job), and it is a job level timeout, 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; its timing limit is what #116918 removes. The job then 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 CI database holds no failing test row for this commit. The job also reports IO stalled 8761.84s (97% of runtime).

05046_table_function_source_access, the test this pull request adds, passed in that same run at 26.94 sec.

Re-running a single job needs write access, which I do not have, and the hourly Retry Infrastructure Failures workflow only considers runs from the last 6 hours, so a red from 2026-08-28 does not clear by itself. I am re-triggering the workflow with a commit whose tree is byte identical to 16339a31, so the content you have is unchanged.

One caveat: CH Inc sync is the other required check and is also red, tests failed (8 new, 1 known). That is the private sync, which I cannot read. If it stays red once the stateless job is green, that half needs someone with access to it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 181e0b3

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
posted here when it opens.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64) and Bugfix validation (functional tests, aarch64) both ERROR at ci/jobs/functional_tests.py:734 with AssertionError: Could not find master builds in S3, before any server starts, so neither job measured a test; a new trunk-wide onset at 19:00Z today with zero occurrences in the preceding 7 days, 23 distinct pull requests so far and still rising a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases result differs from the reference on the old analyzer lane, and it is trunk-wide rather than specific to this branch: 84 rows over 72 distinct pull requests and 12 true-master commits on 08-31 alone #117364 (external, merged 2026-08-31 22:05Z), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) job-level container-memory abort with no failing test assertion; 277 rows over 269 distinct trees and 25 true-master commits on 08-31 #117202 (external, merged 2026-08-31), absent from this tree, and it provably does not clear 6/6. A fix task holds the residual, blocked on the integration-test capacity decision I put to the maintainers at #115963 (comment)
Finish Workflow / new_tests_check.py direct cascade of the row above: the hook reds when no per-arch Bugfix validation job reports OK or XFAIL, and both functional arms ERRORed while both integration arms were skipped for having no integration-test changes a fix task is created (the same one as the Bugfix validation row)

None of the rows above is caused by this pull request.

On the 03707_autopr_unsupported_cases row: the test collects parallel-replicas statistics from the
query plan, which only the analyzer builds, so on the old analyzer lane every shape it checks
reported no statistics. #117364 forces the analyzer in the test itself. It merged at 22:05:00Z, and
compare reports this head diverged from its merge commit c9ed88dbecbb, so the run predates the
fix. On true master, the 7 runs after that merge are clean against 2 to 4 failures per hour before
it. I am not merging master here purely to re-run CI, to keep the review load down.

On the /docker row: the /docker cgroup that bounds the nested test containers is capped at
40.78 GiB, and docker compose stop signals every node of a cluster at once, so each node that
outlives the 60 s deadline attaches gdb at the same moment, holding about 3.4 GiB of anonymous
memory each on an ASan build. #117202 serialises those attaches. Measured caveat, stated so it is
not a surprise later: on master trees that do contain #117202, shards 2/6 and 5/6 are clean but
6/6 still fires, so that PR is deliberately not linked as this row's owner.

Session id: cron:our-pr-ci-monitor:20260831-233000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 11, 2026
@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Dear @nikitamikhaylov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

if (!storage)
throw Exception(ErrorCodes::UNKNOWN_TABLE, "Table '{}' not found in database '{}'", loop_table_name, database_name);

checkSourceStorageAccess(context, storage, StorageID{database_name, loop_table_name}, AccessType::SHOW_COLUMNS);

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 named loop sources before resolving them

This check covers structure resolution, but loop still inherits the empty checkSourceObjectAccess, so its execution path resolves the source before checking any source privilege. In executeImpl, getDatabase and tryGetTable at lines 153–156 precede the SELECT check at line 157.

Confirmed with this head's fast-test binary: a user holding only CREATE TEMPORARY TABLE gets ACCESS_DENIED for SELECT a FROM loop(hidden, t) LIMIT 0 when t exists, UNKNOWN_TABLE when it does not, and UNKNOWN_DATABASE for a missing database. Direct DESCRIBE loop(hidden, missing) correctly denies access first. The read path therefore still exposes source existence across the boundary this PR is securing.

Move the named-source authorization before both catalog lookups, or enforce it through the new hook. Add a stateless negative case for reading an ungranted missing source, alongside the existing-source case.

@nikitamikhaylov nikitamikhaylov self-assigned this Nov 3, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Nov 3, 2026
@nikitamikhaylov nikitamikhaylov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 3, 2026
Merged via the queue into ClickHouse:master with commit 4d0396b Nov 3, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 3, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
nikitamikhaylov pushed a commit that referenced this pull request Nov 11, 2026
Resolve the conflicts by porting only the hunks of #116793. The
conflicting regions hold code of master PRs that are not on 26.10
(#125401 refreshExternalMetadata in TableFunctionLoop.cpp); they are
left as on 26.10.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nikitamikhaylov pushed a commit that referenced this pull request Nov 11, 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]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 11, 2026
Cherry pick #116793 to 26.9: Check access to the source table in the MergeTree introspection table functions
robot-clickhouse added a commit that referenced this pull request Nov 11, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 11, 2026
Cherry pick #116793 to 26.10: Check access to the source table in the MergeTree introspection table functions
robot-clickhouse added a commit that referenced this pull request Nov 11, 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 Nov 13, 2026
nikitamikhaylov pushed a commit that referenced this pull request Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.

8 participants