Skip to content

Require privileges on an Alias target in the loop table function - #116873

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-loop-alias-target-access-read-path
Aug 28, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-loop-alias-target-access-read-path

Conversation

@groeneai

@groeneai groeneai commented Aug 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116793
Related: #116647

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 loop table function disclosing the column names and types of an Alias table's target to a user who holds no privilege on that target: a query that read no rows received them in its response header. loop now requires table-level SELECT on the target, matching what it already requires of the table name it is given.

Description

loop authorizes the name it is given, but an Alias publishes its target's metadata eagerly while authorizing the target lazily. StorageLoop's constructor copies the inner storage's metadata, which for a StorageAlias is the target's, so the response header is populated before any row is read; the target is only checked inside LoopSource::initLoop's synthetic SELECT, which a row-less query never reaches.

A user with SELECT on the alias and nothing on the target gets its structure from any row-less form: SELECT * FROM loop(db, ali) LIMIT 0, the same query under EXPLAIN header = 1, or DESCRIBE TABLE (SELECT ... LIMIT 0), while DESCRIBE ali and SELECT * FROM ali LIMIT 0 deny that user. Rows are never disclosed; it reproduces on master.

The fix adds a name-based target grant check in TableFunctionLoop::executeImpl, before StorageLoop is constructed. PlannerJoinTree.cpp designates ITableFunction::execute as that seam; it runs at query-tree resolution, not pipeline setup, which covers the DESCRIBE subquery. The probe never resolves the target, so a dangling Alias still reports UNSUPPORTED_METHOD to a caller granted the dropped name; full-access behaviour is unchanged. One merged arm of 04945_loop_over_table_expression_without_columns_access changes to ACCESS_DENIED; added arms show it is a tightening.

Validated both directions: a mutation per new arm, 50 randomized runs, and a base-versus-fix run of the loop/alias suite.

Table-level SELECT is the tier, so a caller holding only a column-level grant on the target loses loop over the alias, though reading it directly still works; the permissive tiers are unsound. #116793 closes the structure seam of this invariant, DESCRIBE loop(db, alias), at that seam's own SHOW COLUMNS tier, so until it merges that form still discloses the columns. Two further residuals: an unauthorized CREATE TABLE ... AS loop(...) succeeds through the global context ITableFunction::execute uses, and merge reads an Alias's metadata the same way, uncovered.


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

groeneai and others added 2 commits August 28, 2026 09:15
`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]>
`.claude/CLAUDE.md` requires literal names from the ClickHouse SQL language and
class names to be wrapped in inline code blocks in comments, not only in
documentation and commit messages.

The edit changes no code, and the recompiled object is byte-identical, so the
binary keeps Build ID `3a2159fbe20de9d17f50516903477a633f573075`.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Aug 28, 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; 4 findings;
bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ An Alias chain defeats the one-hop target check (TableFunctionLoop.cpp:149) DISAGREE Agreed on the mechanism, not that it belongs here. It is a pre-existing StorageAlias authorization gap: every consumer of isTargetTableGranted in the tree authorizes a single hop the same way, it is reachable with no table function involved, and this change neither introduces nor widens it (before it, the same query needed no privilege on the target at all). Per SECURITY.md I am not describing it in public; it is recorded and handled outside this pull request.
2 ❌ CREATE TABLE ... AS loop(alias) bypasses the check and persists the target's header DISAGREE True and pre-existing: measured identically on the unpatched binary, so this change does not cause it. Two seams, both already owned in public. The schema-inference half is TableFunctionLoop::getActualTableStructure, which is the one hunk #116793 changes in this file (@@ -117,6 +117,8 @@, four lines above mine); adding the same check here would collide with that open pull request and duplicate it inside one function. The execution half is ITableFunction::execute deferring executeImpl through a closure carrying getGlobalContext(), which has no user, so any per-function check is a no-op there; the merged precedent for that class, 63057e7e408ccc4, fixes it at a base-class seam and removes per-function checks. Both are stated in the description.
3 ⚠️ No EXPLAIN header = 1 arm, although the description names that vector DISAGREE The vector is measured in both directions: on the unpatched binary it returns the target's columns, with the fix ACCESS_DENIED. What is missing is a permanent arm, and no mutation separates one from the two arms that bracket it. EXPLAIN resolves the query tree and builds a plan without running the pipeline, so it sits between the analysis-only DESCRIBE TABLE (SELECT ... LIMIT 0) arm and the executed LIMIT 0 arm. Measured: moving the guard into StorageLoop::read reddens only the dangling-alias arm, moving it into ReadFromLoopStep::initializePipeline reddens the DESCRIBE subquery arm, and an EXPLAIN arm would redden under exactly the second. Its mutation set equals an arm already present, so it would add lines and no detection.
4 💡 Category should be Critical Bug Fix (RBAC) DISAGREE I apply that category only when a maintainer asks for it. On the merits the defect discloses column names and types, never rows, and grants no new access, so Bug Fix is the accurate tier; the sibling fixes for this class carry the same one.

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

Also noted in my own review, not blocking: executeImpl resolves the table name and throws
UNKNOWN_TABLE before checking SELECT on it, so that seam remains a table-existence probe for a
caller with no grants. It is byte-identical in the base tree and the new check is added after both,
so this change neither creates nor widens it; the structure path already orders its check first.
Every new test arm is backed by a mutation that reddens it and no other, and the three control arms
are deliberately reddened by none: they measure that the direct path gives the same answer, which is
what makes the one tightened expectation in the existing test defensible.

Session id: cron:clickhouse-review-slot-11:20260828-095100

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, not probabilistic. As a user holding GRANT SELECT, SHOW COLUMNS ON ali plus GRANT CREATE TEMPORARY TABLE ON *.* and nothing on the target: SELECT * FROM loop(currentDatabase(), ali) LIMIT 0 FORMAT JSON returns secret_id UInt64, secret_text String. Same for EXPLAIN header = 1 over that query and for DESCRIBE TABLE (SELECT * FROM loop(currentDatabase(), ali) LIMIT 0). Every run first asserts CHECK GRANT SELECT/SHOW COLUMNS on alias and target reads 1 1 0 0, so a missing CREATE TEMPORARY TABLE grant cannot make the matrix read as a false negative.
b Root cause explained? Yes. StorageLoop's constructor copies the inner storage's metadata into its own (StorageLoop.cpp:18-19), and for a StorageAlias that metadata is the target's (StorageAlias.h:122-129), so the response header is populated eagerly. The target's own authorization is lazy: it happens inside the synthetic SELECT that LoopSource::initLoop builds (ReadFromLoopStep.cpp:118-139), which only runs when a row is requested. A row-less read gets the header and never reaches it. TableFunctionLoop::executeImpl:142 checked only the alias name.
c Fix matches root cause? Yes. The missing authorization is added, at the seam the codebase designates for table functions (PlannerJoinTree.cpp:785-787: access rights for table functions are checked in ITableFunction::execute). No widened bound, no no-random-* tag, no reduced dataset, no defensive check masking an upstream bug. +12/-0 in one .cpp, no header change, no shared code, no setting.
d Test intent preserved / new tests added? Yes. No arm was weakened or removed. One merged arm of 04945_loop_over_table_expression_without_columns_access is tightened from UNSUPPORTED_METHOD to ACCESS_DENIED, accompanied by two arms proving it is a tightening and not a loss: a direct DESCRIBE of that same dangling alias already denies, and the authorized answer for the dangling case is still UNSUPPORTED_METHOD. Nine arms added, every one with a mutation that reddens it.
e Both directions demonstrated? Yes. All three vectors disclose the target's columns on the unpatched binary (f47b2baf) and return ACCESS_DENIED with the fix (3a2159fb), same server config and same grants. At test level, running the changed test against the unpatched binary reddens exactly five of its arms and leaves every control green.
f Fix is general across code paths? The invariant "a consumer of an Alias's metadata or rows must hold the privilege on the target" has 16 existing isTargetTableGranted carriers; this adds the 17th. Deliberately not covered here, each for a reason: TableFunctionLoop::getActualTableStructure is the single hunk #116793 already changes in this file (its hunk ends at line 125, this one starts at 140, so there is no conflict in either merge order); the loop(<inner table function>) branch never resolves a table name, so the inner function's own checks apply; merge and the mergeTree* / timeSeries* family belong to #116793 and #116629, with merge disclosed in the description as a residual. executeImpl's named branch has exactly two exits before the guard (UNKNOWN_DATABASE, UNKNOWN_TABLE), both preceding it, so the guard cannot be skipped once that branch is entered.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers do not apply: the predicate is on a storage engine identity (as<StorageAlias>()), not a data type. The dimension that does vary is the grant tier, and all four are covered by arms: nothing granted, column-level SELECT, table-level SHOW COLUMNS, table-level SELECT. Target state varies too: live and dangling both have arms, and non-alias plus inner-table-function forms are covered by the untouched loop suite.
h Backward compatible? (maintainer-approved exception only) No setting, so no SettingsChangesHistory.cpp entry; no serialization or format change. One deliberate behaviour tightening, which is the point of the fix. Full-access behaviour is unchanged: 04945_loop_over_table_expression_without_columns.sql stays byte-identical, because the grant probe is name-based and never resolves the target. The one accepted cost is disclosed in the description: a caller holding only a column-level SELECT grant on the target loses loop over that alias, while reading the alias directly still works.
i Invariants and contracts preserved? The check is placed after the alias's own SELECT check, so a caller who cannot read the alias still learns nothing about the target's grants. It is a read-only grant probe: no lock, no allocation, no shared state, nothing to release on an error path, and it throws before StorageLoop exists, so there is no half-constructed storage. Row policies and quotas attached to the alias name are untouched, because the alias and not the target is still what gets wrapped; 03928_loop_row_policy stays green.

Validation runs: 50 randomized runs of the changed test (50 OK / 0 FAIL); the whole loop and alias
stateless suite (332 tests) run against both the patched and unpatched binaries, with zero failures
present only on the patched one; and eight separate mutations, each built and run on its own, each
reddening a disjoint subset of the new arms.

Session id: cron:clickhouse-impl-slot-41:20260828-081200

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7bba89b]

Summary: ✅


AI Review

Summary

This PR adds a target-side SELECT check in TableFunctionLoop::executeImpl before StorageLoop snapshots an Alias target's metadata, and extends the shell regression to cover the row-less SELECT and analyzer-only DESCRIBE TABLE (SELECT ...) paths. I reviewed the current diff, the surrounding access-control code, the prior PR discussion, and the current CI state, and I did not find an unresolved correctness, safety, or evidence gap in the patch as it stands.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 7bba89b.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

cc @pufit @vitlibar, could you review this? StorageLoop's constructor copies the inner storage's metadata, which for a StorageAlias is its target's, so a loop read that pulls no rows hands back the target's column names and types before the lazy per-column check inside LoopSource::initLoop ever runs; this requires table-level SELECT on the target at the ITableFunction::execute seam instead.

@PedroTadim PedroTadim self-assigned this Aug 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7bba89be9 with master f1840f9f3 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 712.38 MiB 709.32 MiB -3.06 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

18 translation units recompiled, 23 s compile time in total, 18 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +2.1 s (+10%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7bba89b

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.

362 check-runs over TWO concurrent workflow runs on this same tree (33164377810 and
33164388203, 175 each), 0 incomplete, Finish Workflow success in both (latest 15:43:09Z),
Mergeable Check success 15:43:00Z, CH Inc sync success. One real red, and it is not caused by
this PR: the diff is src/TableFunctions/TableFunctionLoop.cpp plus two test files (+90/-0) and
touches neither object storage nor set building.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error: 'Not-ready Set is passed as the second argument for function 'globalIn'' (STID 0250-4e52) Chronic trunk abort at src/Functions/in.cpp:128. The stack is ReadFromObjectStorageStep::initializePipeline -> StorageObjectStorageSource::createFileIterator -> VirtualColumnUtils::getFilterByPathAndFileIndexes -> FunctionIn::executeImpl, i.e. the object-storage _path/_file pruning runs while the pipeline is built, before the globalIn set exists. Same tree, same job, other run: PASS (33164388203 failed at 13:45:20Z, 33164377810 succeeded at 14:07:33Z), so this is timing dependent, not tree dependent. CIDB has 12 true-master hits for this STID in the last 30 days. #112968 (external, open) - it fixes exactly this chain, and its new test 04669_object_storage_path_filter_global_in.sql describes it in the same terms

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116873&sha=7bba89be9c43a4a08fb5d74d5a5702163df77076&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

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

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 28, 2026
Merged via the queue into ClickHouse:master with commit 8342360 Aug 28, 2026
361 of 362 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 28, 2026
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Sep 22, 2026
… its columns

`StorageMerge::getColumnsDescriptionFromSourceTablesImpl` authorizes every table
its regexp matches against that table's own id, `isGranted(SHOW_TABLES, ...)` as
the existence tier and `checkAccess(SHOW_COLUMNS, ...)` as the column tier, and
then reads the table's metadata. For an `ENGINE = Alias` row the metadata that
comes back is the target's: `StorageAlias::getInMemoryMetadataPtr` resolves the
target with `tryGetTargetTable` and forwards it with no check of any kind. So the
privilege that governs reading those columns, `SHOW COLUMNS` on the target, is
never consulted. A check is present and simply bound to the wrong object, which
is why this is a bypass of an existing check rather than a missing feature.

A user holding only `SHOW TABLES, SHOW COLUMNS` on the alias's database, and
nothing at all on the target, obtains the target's column names and types from
`DESCRIBE merge('nl', '^al$')`, while `DESCRIBE nl.al`, `SHOW CREATE TABLE nl.al`
and `system.columns` deny that same user the same information. Rows are never
disclosed, because `StorageAlias::read` re-checks `SELECT` through
`getTargetTable`; the leak is metadata only.

The target is bound with the same privilege at the site that consumes the
metadata. That is the seam all fourteen existing alias guard sites use, and the
shape approved in ClickHouse#116647; making `getInMemoryMetadataPtr` itself check was
rejected because it is called from internal full-access paths and system
introspection relies on it not throwing for a dangling alias. Throwing rather
than skipping the row follows the tier immediately above it: a `merge` over a
plain table the caller cannot `SHOW COLUMNS` already fails the whole query, wide
regexp included.

`getColumnsDescriptionFromSourceTablesImpl` is the sole chokepoint, so the one
guard covers the `merge` table function, its database-regexp form, and both
`StorageMerge` constructors when `ENGINE = Merge` is created without a column
list. Creating such a table over an alias whose target the creator cannot
`SHOW COLUMNS` now fails instead of silently inheriting, and thereby persisting,
the hidden schema. Existing tables cannot break: the derived column list is
persisted into the CREATE query, so the constructor takes the non-empty
`columns_` branch at load and never traverses, which a `DETACH`/`ATTACH`
round-trip and a full server restart both confirm.

`isTargetTableGranted` is a name-based `isGranted` that never resolves the
target, so a dangling `Alias` still reaches the existing empty-metadata handling
and `04236_merge_with_alias_missing_target_104740` and
`04238_storage_alias_missing_target_merge` are unaffected. Table-level
`SHOW COLUMNS` is the tier, so a caller holding only a column-level grant on the
target loses `merge` over the alias while reading the target directly still
works; ClickHouse#116873 recorded that same tradeoff for `loop`.

Two arms are added to `03636_storage_alias_metadata_access_rights`, whose fixture
already grants table-level `SELECT` on the alias and revokes `SHOW COLUMNS` on
the target: one negative arm for the leak and one positive control that must keep
passing, so an over-denial reddens it. Validated on three binaries built from the
same base, each asserted by `buildId()`: the base discloses, a mutant that keeps
every new line but neuters only the throw discloses again, and the fix denies. 50
randomized runs pass, and the `alias` and `merge` suites were run base versus fix
with no failure attributable to the change.

Related: ClickHouse#116873
Related: ClickHouse#116793
Related: ClickHouse#116647

Co-Authored-By: Claude Opus 5 <[email protected]>
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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants