Skip to content

Check access to the source table when resolving the structure of mergeTreeCodecBlockCounts - #116647

Merged
alexey-milovidov merged 22 commits into
masterfrom
mergetree-codec-block-counts-access-check
Sep 14, 2026
Merged

alexey-milovidov merged 22 commits into
masterfrom
mergetree-codec-block-counts-access-check

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

mergeTreeCodecBlockCounts checked the SELECT privilege on its source table only in StorageMergeTreeCodecBlockCounts::read, that is, only when the function was read. Resolving the structure of the function went straight to DatabaseCatalog, so DESCRIBE mergeTreeCodecBlockCounts(db, t) succeeded for a user without any privilege on db.t, and the BAD_ARGUMENTS message thrown for a table of another engine ("expected MergeTree table, got: ...") revealed that engine. No data of the table leaked, because the read itself was checked.

The name of the source table was also resolved through DatabaseCatalog before any check ran, on both paths, so a user without any privilege on it could still tell an existing table it may not see from a missing one, by ACCESS_DENIED against UNKNOWN_TABLE. Both paths now check SHOW TABLES on the name first, before the catalog is consulted. That privilege is implied by a grant on any single column of the table, so it does not narrow the grant this function accepts, and it is the privilege that governs whether the existence of the table may be learned.

Now the same check runs in getActualTableStructure, before anything is derived from the table, and it is shared with read as StorageMergeTreeCodecBlockCounts::checkSourceTableAccess.

The read side had no test for its check either, so the new test covers both paths, a grant that covers only one column of the table, which is not enough, and a grant that covers every column of it individually, which is. It also covers a source table of another engine, without the grant, which now gives ACCESS_DENIED instead of the engine-revealing BAD_ARGUMENTS, and with the grant, which still gives BAD_ARGUMENTS. The privilege requirement is now also documented in the description of the function.

The same check also closes the persisted form of the function. canBeUsedToCreateTable refuses CREATE TABLE ... AS mergeTreeCodecBlockCounts(...), but it is checked only on the outermost table function, so the same function nested in an argument of another one still reaches a persisted definition: both remote(..., f(...)) and ENGINE = Remote(..., f(...)) keep it in remote_table_function_ptr. For a cluster with a local shard both forms resolve the nested function under the creating user's context, through getStructureOfRemoteTableInShard and getActualTableStructureWithAccess, which is the seam this change adds the check to, so both are now refused for a user who may not read the source table. The test pins that with four arms, one per form and per privilege tier, reporting the privilege each attempt demanded next to the error code so that an arm cannot pass on a refusal that came from the carrier rather than from the source table.

The function was added in 26.8, which is branched but not released yet, so this is an Improvement rather than a bug fix in a released version, and it is worth having on 26.8 before it ships.

The same defect in the sibling MergeTree introspection table functions, mergeTreeIndex and mergeTreeProjection, is fixed separately in #116793.

Related: #109623
Related: #116793

Changelog category (leave one):

  • Improvement

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

Tightened the access check of the mergeTreeCodecBlockCounts table function: resolving its structure, for example by DESCRIBE, did not require the SELECT privilege on the source table, while reading it did, and a user without any privilege on the source table could tell an existing table from a missing one.


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

Version info

  • Backported to: 26.8.7.14

…eTreeCodecBlockCounts

`mergeTreeCodecBlockCounts` checked the `SELECT` privilege on its source table
only in `StorageMergeTreeCodecBlockCounts::read`, that is, only when the
function was read. Resolving the structure of the function went straight to
`DatabaseCatalog`, so `DESCRIBE mergeTreeCodecBlockCounts(db, t)` succeeded for
a user without any privilege on `db.t`, and the `BAD_ARGUMENTS` message thrown
for a table of another engine revealed that engine.

Run the same check in `getActualTableStructure`, before anything is derived
from the table. The check is now shared with `read` as
`StorageMergeTreeCodecBlockCounts::checkSourceTableAccess`.

The read side had no test for its check either, so the new test covers both
paths, a grant that covers only one column of the table, which is not enough,
and a grant that covers every column of it individually, which is.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0e6d354]

Summary: ✅


AI Review

Summary

This PR closes the mergeTreeCodecBlockCounts access-control gaps that were still left outside the actual read: DESCRIBE, hidden-vs-missing source-table resolution, analysis-only EXPLAIN paths that must stay source-independent, and local-shard remote(...) / Remote(...) schema inference now all behave consistently with the function's documented privilege contract. I did not find an unresolved correctness or access-control issue in the current PR head, and the new stateless coverage is focused on the relevant privilege tiers and entrypoints.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 0e6d354.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

Changed lines: Changed C/C++ lines covered: 39/40 (97.50%) · 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 27, 2026
/// Resolving the structure is a read of the source table, so it needs the same access as reading it.
/// Checked before anything is derived from the table, so that a user without `SELECT` on it cannot learn
/// its engine from the error below. `StorageMergeTreeCodecBlockCounts::read` checks again for the read itself.
StorageMergeTreeCodecBlockCounts::checkSourceTableAccess(source_table, context);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If the invariant here is that resolving a MergeTree introspection table function's structure is a read of the source table, this same bypass is still open in siblings. InterpreterDescribeQuery calls getActualTableStructureWithAccess, but TableFunctionMergeTreeIndex::getActualTableStructure (src/TableFunctions/TableFunctionMergeTreeIndex.cpp:151-188) and TableFunctionMergeTreeProjection::getActualTableStructure (src/TableFunctions/TableFunctionProjection.cpp:66-78) still go straight to DatabaseCatalog and source metadata without any source-table SELECT check, while their actual reads are gated later in StorageMergeTreeIndex::readImpl (src/Storages/StorageMergeTreeIndex.cpp:390-416) and StorageFromMergeTreeProjection::read (src/Storages/MergeTree/StorageFromMergeTreeProjection.cpp:38-49).

That means this PR fixes the leak only for mergeTreeCodecBlockCounts; a user who cannot read a table can still DESCRIBE mergeTreeIndex to learn its primary-key and marks schema, or DESCRIBE mergeTreeProjection to learn a projection's schema. Please extend the same pre-structure access check to those table functions as well, and add DESCRIBE coverage next to their existing grant tests.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai please investigate if we can make a structural fix s.t. all current (and future) table functions are covered. If yes, please open a follow-up with it and ask the most appropriate person for a review. If not, please open a follow-up targeting the remaining affected table functions

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Investigated. The two named above are the only ones left: on master, mergeTreeIndex and mergeTreeProjection are the sole table functions that derive their structure from another table without a check. mergeTreeAnalyzeIndexes and mergeTreeTextIndex return a static column list, so structure resolution reveals nothing there, and merge and loop are already gated (StorageMerge::getColumnsDescriptionFromSourceTablesImpl skips tables without SHOW TABLES and checks SHOW COLUMNS per table; loop forwards to the inner function's getActualTableStructureWithAccess).

A structural fix looks feasible, since getActualTableStructureWithAccess is already the only entry point from outside execute() (DESCRIBE, CREATE ... AS f(...), remote structure inference, loop): a table function can declare the table it derives its structure from and be checked there once. What I cannot promise yet is fail-closed coverage of future functions, because that declaration would default to no source table unless it is made mandatory for every table function. The seam also has to settle which privilege applies, which is inconsistent today: this PR requires SELECT on all columns, while StorageMerge and my open #116629 (the same defect in the timeSeries* functions) require SHOW COLUMNS.

I will open the follow-up with that and report there if the fail-closed part does not hold up.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up opened: #116793.

It adds one virtual to ITableFunction, checkSourceObjectAccess, called from both base-class seams (getActualTableStructureWithAccess and execute) under the querying user's context, and overrides it in mergeTreeIndex, mergeTreeProjection, mergeTreeTextIndex, mergeTreeAnalyzeIndexes and viewIfPermitted. loop needed only the Alias-target leg. Resolving a structure requires SHOW COLUMNS, exactly what DESCRIBE of the source requires; execution requires SHOW TABLES.

Reporting back on the fail-closed half, as promised: it did not hold up. Making the hook pure virtual needs an override in every table function, around 100 of them, almost all of which have no source object, so the default stays a no-op and the hook is opt-in, documented at the declaration. Future functions are therefore covered by the seam only if they use it. mergeTreeCodecBlockCounts is left to this PR.

The ACCESS_DENIED-before-the-engine-check arm is in the new test for both functions, over a Log source, so a caller without the grant no longer learns the engine from BAD_ARGUMENTS. I put it in the follow-up's own test file rather than in 05045_* here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Recording where this stands, so the thread is not the only place that carries it.

mergeTreeIndex and mergeTreeProjection are handled in the follow-up #116793, which is open and targets master, as @rienath asked. This pull request keeps only mergeTreeCodecBlockCounts, and its description now links the follow-up.

One inconsistency is worth flagging before both land, because it is visible to users and cannot be settled inside either pull request alone: this change requires SELECT on every column of the source table to resolve the structure, while #116793 requires SHOW COLUMNS, matching what DESCRIBE of the source table itself requires, and StorageMerge requires SHOW COLUMNS too. The stricter rule here is defensible, because every column of mergeTreeCodecBlockCounts is derived from the data of the table rather than from its metadata, so resolving its structure is closer to a read than to a DESCRIBE. It is still a difference between two neighbouring functions, and if the seam in #116793 should own mergeTreeCodecBlockCounts as well, converging on one privilege is the natural place to do it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Measured on master 438a6180ae96 (debug, 26.9.1.1) by granting one privilege at a time, plus the code at both heads:

structure resolution read
DESCRIBE t, SHOW CREATE TABLE t SHOW COLUMNS ON t (AccessType.h:167)
merge SHOW COLUMNS SELECT on the columns read
mergeTreeIndex, #116793 SHOW COLUMNS SELECT on the columns read (StorageMergeTreeIndex.cpp:416)
mergeTreeProjection, #116793 SHOW COLUMNS SELECT ON t, table level
mergeTreeCodecBlockCounts, here SELECT on every physical column SELECT on every physical column

The read column is not diverging in this pull request: checkAccess(AccessType::SELECT, source_storage_id, ...getNamesOfPhysical()) is already on master at StorageMergeTreeCodecBlockCounts.cpp:332. SELECT part_name FROM mergeTreeCodecBlockCounts(...) is refused today asking for SELECT(a, b), where the same shape over mergeTreeIndex needs only SELECT(a). That predates both pull requests and neither can settle it.

The structure column does diverge, and it points the opposite way to how it reads. The structure here is six fixed columns independent of the source, so resolving it discloses nothing about the source but its existence and engine. mergeTreeIndex resolves to the partition key columns, the whole primary key sample block with names and types, and with with_marks one column per physical substream named after the source's columns, which is most of DESCRIBE t. The function asking for SHOW COLUMNS is the one whose structure reproduces the source's metadata.

Your data versus metadata distinction holds, and it cuts against my rule rather than for relaxing yours: resolving mergeTreeIndex with with_marks calls getDataPartsVectorForInternalUsage and enumerates the substreams present in the current parts, which is part level layout, the same class of fact this function reports rows about.

So my answer on the seam is yes, and the privileges need not converge for it, because they are not alternatives and cannot run at the same point. A check naming the source's columns needs the resolved storage, so it cannot precede DatabaseCatalog::getTable. A SHOW COLUMNS check binds to the parsed StorageID, and both functions build that id from literals in parseArguments with no catalog lookup, so the earlier slot is free. DESCRIBE uses that earlier slot: measured, DESCRIBE d.nosuch by an ungranted user is ACCESS_DENIED, not UNKNOWN_TABLE, whereas on master both DESCRIBE mergeTreeCodecBlockCounts('d', t) and DESCRIBE mergeTreeIndex('d', t) answer UNKNOWN_TABLE for a missing table and a full structure for one the user cannot see.

ITableFunction::checkSourceObjectAccess names no privilege: it is a virtual with an empty default, and each override picks its own. So an override checking SHOW COLUMNS on the name at the structure leg, leaving StorageMergeTreeCodecBlockCounts::checkSourceTableAccess where it is, keeps your rule unchanged and adds the pre-resolution tier, in about eight lines with no change to ITableFunction.

I can add that to #116793 and pin the missing source against the hidden one in 05046, or hand you the override for here. If you would rather have one privilege across both, say which and I will make #116793 match; 05046 currently pins SHOW COLUMNS as sufficient for the structure, so that arm moves with the decision.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Answering the question you left for me, now that the pre-resolution tier is in this pull request as well.

Do not converge the two on one privilege, and do not move mergeTreeCodecBlockCounts under the seam's SHOW COLUMNS. Keep #116793 on SHOW COLUMNS for the structure of mergeTreeIndex and mergeTreeProjection, whose structures reproduce the source's metadata, exactly as you have it. Here the pre-resolution check is SHOW TABLES.

The reason is a measurement rather than a preference. On a build of this branch, a user holding SELECT on each column of the source table separately, which is precisely the grant this function accepts and which 05045 pins, is refused a table-level SHOW COLUMNS check: column-level grants imply SHOW TABLES on the table, so the table is listed by SHOW TABLES, but they do not imply SHOW COLUMNS, so DESCRIBE of the source itself is still ACCESS_DENIED for that user. I had this pull request on SHOW COLUMNS first and the existing arm of 05045 failed on it. So a SHOW COLUMNS pre-check would refuse the exact grant the function is documented to accept, which is a behaviour change rather than a tier added below the existing one.

SHOW TABLES is also the narrower fit for what this tier hides. The structure here is six fixed columns, so the only fact the pre-check protects is the existence of the source, and SHOW TABLES is the privilege that governs that. Your functions are the opposite case: their structure carries the source's column names and types, so the tier there has to be the privilege that governs reading metadata.

So the divergence stands, and it is the same rule stated once: check the privilege that matches what the structure discloses. Nothing is owed from you here; 05046 can keep pinning SHOW COLUMNS as sufficient.

@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0e6d3543a with master abcadc3ce (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 3345498c8; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

/// Resolving the structure is a read of the source table, so it needs the same access as reading it.
/// Checked before anything is derived from the table, so that a user without `SELECT` on it cannot learn
/// its engine from the error below. `StorageMergeTreeCodecBlockCounts::read` checks again for the read itself.
StorageMergeTreeCodecBlockCounts::checkSourceTableAccess(source_table, context);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai please investigate if we can make a structural fix s.t. all current (and future) table functions are covered. If yes, please open a follow-up with it and ask the most appropriate person for a review. If not, please open a follow-up targeting the remaining affected table functions

@@ -0,0 +1,55 @@
#!/usr/bin/env bash

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It'd be also nice to add a test that DESCRIBE of a non-MergeTree table without a grant returns ACCESS_DENIED rather than the engine-revealing BAD_ARGUMENTS

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Will add it in the same follow-up. It pins behavior this PR already produces (the check runs before the dynamic_cast), rather than changing it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Added it here after all, in 05045_mergeTreeCodecBlockCounts_access.sh, rather than in the follow-up: the ordering it pins is produced by this change, so the arm belongs next to the change that produces it.

The arm runs DESCRIBE over a Log source twice, first without any grant on it, which gives ACCESS_DENIED and a message that names only the table, and then with SELECT on it, which gives the BAD_ARGUMENTS that names the engine. So the test witnesses the order of the two checks instead of only the first one.

Non-MergeTree source table, without SELECT on it
ACCESS_DENIED
Non-MergeTree source table, with SELECT on it
BAD_ARGUMENTS

Verified locally against a build of this branch, 5 runs with randomised settings, all green. The follow-up #116793 keeps its own equivalent arm for mergeTreeIndex and mergeTreeProjection.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

That arm pins what I asked for, and next to the change that produces the ordering is the right place for it.

One correction to the comment above it, for a later reader: the engine is not concealed below SELECT, it is concealed below SHOW COLUMNS. AccessType.h:167 gives SHOW_COLUMNS as the privilege for SHOW CREATE TABLE and DESCRIBE, and measured on master 438a6180ae96, a user holding SHOW COLUMNS on the source and no SELECT reads ENGINE = Log straight out of SHOW CREATE TABLE, while a user holding only SHOW TABLES is refused and told to get SHOW COLUMNS. The arm is unaffected, because the user it uses at that point holds neither. Figures are in the other thread, where the privilege question sits.

Nothing owed from me on this half. #116793 keeps its own arms for mergeTreeIndex and mergeTreeProjection.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 You are right, and the comment is now corrected in 6f620710: the engine is disclosed by SHOW CREATE TABLE, which requires SHOW COLUMNS, not SELECT. The comment above the arm says that, and says why the arm is unaffected — the user holds neither privilege at that point.

The same measurement decided the pre-resolution check that was added here since: it is SHOW TABLES, not SHOW COLUMNS, because column-level SELECT grants imply the former but not the latter, so a SHOW COLUMNS pre-check would refuse the very grant 05045 pins as sufficient. Details are in the other thread.

alexey-milovidov and others added 2 commits August 28, 2026 23:38
`rienath` asked for a test that `DESCRIBE mergeTreeCodecBlockCounts` over a
table of another engine, without the grant, returns `ACCESS_DENIED` rather than
the engine-revealing `BAD_ARGUMENTS`. That is what this change already produces,
because the check runs before the `dynamic_cast`, but nothing pinned it.

The new arm runs `DESCRIBE` over a `Log` table, first without any grant on it,
which gives `ACCESS_DENIED`, then with `SELECT` on it, which gives
`BAD_ARGUMENTS`, so the ordering of the two checks is witnessed rather than
assumed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 29, 2026
… siblings

Two errors in the sibling example, both found by the reviewer, plus one it did
not flag.

`StorageFromMergeTreeProjection` was listed as having no `SELECT` check on any
path. It does: `StorageFromMergeTreeProjection::read` calls
`context->checkAccess(AccessType::SELECT, parent_storage->getStorageID())` and
goes on to apply row policies. The earlier grep that produced the claim searched
only the file declaring the class, which is the header, and so missed the
definition. Removed from that bucket.

`mergeTreeAnalyzeIndexes` was missing. Its `getActualTableStructure` ignores its
`ContextPtr` and returns a fixed column list; `executeImpl` resolves the source
table through `DatabaseCatalog`, and the engine-disclosing `BAD_ARGUMENTS`
(`Storage MergeTreeAnalyzeIndexes expected MergeTree table, got: {}`) is thrown
one level deeper, in the `StorageMergeTreeAnalyzeIndexes` constructor, ahead of
the `checkAccess` in `readImpl`. Added as a second `executeImpl` sibling, and the
inventory's `executeImpl` bullet now says to descend into the storage
constructor, since validation placed there runs while the surface is built.

The example is now grouped by carrier — `getActualTableStructure`, `executeImpl`,
`parseArguments` — and explicitly scoped to the `mergeTree*` and `timeSeries*`
functions as one deliberately swept family, rather than reading as an inventory
of every table function. The read side is restated from a full sweep of
`checkAccess(AccessType::SELECT` under `src/Storages`: every `mergeTree*`
function checks at read time, so the whole family shows one asymmetry — guarded
at the read, unguarded at whichever earlier entrypoint resolves the table — while
the `TimeSeries` storages have no check on any path. That asymmetry, rather than
a missing check, is what the sweep looks for.

Not flagged, but wrong for the same reason: the worked example said
`mergeTreeCodecBlockCounts` was "fixed by" #116647. That pull request is still
open, so the structure path is unguarded in `master`, and the function belongs in
the sibling list. Reworded, and `mergeTreeCodecBlockCounts` added to the
`getActualTableStructure` group.
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Aug 29, 2026
`mergeTreeCodecBlockCounts` (ClickHouse#109623)
checked `SELECT` on its source table in `StorageMergeTreeCodecBlockCounts::read`
only. The review looked straight at that check and argued its column granularity
was too coarse; the author answered that the strict check was intentional, and the
review ended there. Meanwhile `getActualTableStructure` went straight to
`DatabaseCatalog`, so `DESCRIBE mergeTreeCodecBlockCounts(db, t)` succeeded for a
user with no privilege on `db.t`, and the `BAD_ARGUMENTS` thrown for a table of
another engine disclosed that engine. Fixed by
ClickHouse#116647.

The miss was not a failure to read the right file. It was answering the shape
question about a guard instead of the prior question of whether every path reaches
it, and having no inventory of what the entrypoints of a table function are.

- New triggered expansion for an access check or a new surface derived from
  another object, pointing at `references.md#access-checks`.
- New `references.md` section with the procedure: completeness before granularity,
  the entrypoint inventory (`getActualTableStructure`, reached by `DESCRIBE` and
  `CREATE TABLE ... AS`, `executeImpl`, `read`, `totalRows`/`totalBytes`,
  inherited mutating operations), the note that
  `getActualTableStructureWithAccess` covers only source access and never `SELECT`
  on a table named in the arguments, why metadata and error text are protected
  information, one negative test per entrypoint, the sibling sweep, and severity.
- New general rule "Do not let one finding close a topic": a finding about a
  mechanism is not a review of it, and an author's "this is intentional" closes the
  shape question only.
- Blocker for a check any entrypoint can bypass, including one that exposes only
  structure, metadata, or an error message naming a property of the object.
- Test-coverage rule: a new access check needs a negative test per guarded
  entrypoint; no test at all is a Major, since nothing then distinguishes a check
  on every path from a check on one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`getActualTableStructure` and `executeImpl` resolved `source_table_id` through `DatabaseCatalog` before
any check, so a user with no privilege on the source table could tell an existing hidden table from a
missing one by `ACCESS_DENIED` against `UNKNOWN_TABLE`. Both now check `SHOW COLUMNS` on the name first,
the privilege `DESCRIBE` of the source table itself requires, which any grant on the table implies, so
the `SELECT` rule that follows the resolution is unchanged. The test pins that a hidden source and a
missing one answer alike.
Measured against a build of this branch: a user holding `SELECT` on every column of the source table
separately is refused a table-level `SHOW COLUMNS` check, which `DESCRIBE` of the source table requires,
so checking `SHOW COLUMNS` before the resolution would reject exactly the grant this function accepts.
`SHOW TABLES` is implied by a grant on any single column, and it is the privilege that governs whether
the existence of the table may be learned, which is all this tier hides.
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Aug 31, 2026
The engine of a table is disclosed by `SHOW CREATE TABLE`, which requires `SHOW COLUMNS` on it, not
`SELECT`, as the comment above the arm said. The arm is unaffected: the user it uses holds neither.
The new arms only ran `DESCRIBE`, which exercises `getActualTableStructure`. An ordinary
`SELECT` goes through `TableFunctionMergeTreeCodecBlockCounts::executeImpl`, which carries
its own pre-resolution `SHOW TABLES` check, so a regression there would have kept the test
green while execution became an existence oracle again. The test now runs both paths, and it
is renumbered to `05059` after the merge with master.
@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. The whole upgrade_error_messages.txt for 2f8becc33ed is one signature on one part of one table: 180 lines, 60 mutation attempts, all test_5.t_stale_part_type_5 (4844ba05-db11-4327-a3c0-35ca9757925b)::all_1_1_1_2.

The fix is already in progress, so no separate PR from me: #118499, open since 2026-09-07. StorageMergeTree::selectPartsToMutate skips a zero-row part instead of mutating it, and asks cleanup to drop it right away. I have linked it on the other threads that showed this exact signature.

The test is 04653_mutation_rewrite_stale_part_column_type, section --- a renamed column with a stale type ---:

CREATE TABLE t_stale_part_type_5 (a String, b String, c String MATERIALIZED concat(a, '!'))
ENGINE = MergeTree ORDER BY a SETTINGS min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0;
INSERT INTO t_stale_part_type_5 VALUES ('x', 'y');
ALTER TABLE t_stale_part_type_5 DETACH PART 'all_1_1_0';
ALTER TABLE t_stale_part_type_5 MODIFY COLUMN b Nullable(String);
ALTER TABLE t_stale_part_type_5 ATTACH PART 'all_1_1_0';
ALTER TABLE t_stale_part_type_5 RENAME COLUMN b TO d SETTINGS mutations_sync = 1;

Two corrections to the reading.

No mutation is left unfinished, and mutations_sync is 1 here. DETACH PART leaves an empty tombstone at level + 1 (all_1_1_1) carrying the column list as of that moment, and clearEmptyParts only outdates it in memory, so the directory survives old_parts_lifetime. Under --upgrade-check the client gets --fake-drop (tests/clickhouse-test:7739), so the test's own DROP TABLE is a no-op and the table plus the tombstone are still there when the check restarts the server. The restart revives the tombstone as Active and replays the mutation entries kept on disk against it:

01:25:08.662720  test_5.t_stale_part_type_5: Loaded data parts (2 items)
01:25:08.662889  Loading mutation: mutation_2.txt entry, commands size: 1
01:25:08.663004  Loading mutation: mutation_5.txt entry, commands size: 2
01:25:08.663074  Loading mutation: mutation_4.txt entry, commands size: 1

b does not resolve against the tombstone's column list, hence the UNKNOWN_IDENTIFIER.

It does not retry in a loop. From clickhouse-server.upgrade.log of the same job:

01:25:09.855953  first MutatePlainMergeTreeTask: Code: 47 ... UNKNOWN_IDENTIFIER
01:25:43.901275  last of 60 MutatePlainMergeTreeTask errors (34.0 s window)
01:25:44.596696  test_5.t_stale_part_type_5: Will drop empty part all_1_1_1

Nothing further for that table until shutdown at 01:26:04. Mutation selection and cleanup race once per second and cleanup won, which matches your "~20 s". So the durable effect is the log-scan red, not a wedged queue.

On the missing issue: this shape is tracked by #118499. The same message text also covers a sibling shape, a non-empty re-attached part that nothing drops, which is permanent and survives KILL MUTATION; that one is issue #115416 by @ zlareb1, fixed by #115962. #115962 does not cover the rows above: its hunks sit inside the block guarded at MutateTask.cpp:281-282, and section 5 sets min_bytes_for_wide_part = 0, min_bytes_for_full_part_storage = 0, so the tombstone is Wide with full part storage and that block is not entered. The two are complementary. I do not think a new issue would add anything over those two.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 AST fuzzer (arm_asan_ubsan) is red on an ASan heap-buffer-overflow (STID 1740-4c22) that this change cannot reach: the fuzzer cast a string to AggregateFunction(uniqTheta, ...) and compact_theta_sketch_parser::parse read the state's header past the end of its buffer, while this pull request only adds an access check to the structure resolution of mergeTreeCodecBlockCounts.

The overflow is real and reproduces on master with no fuzzing:

SELECT CAST(char(8, 0, 1, 3, 0, 0, 0, 0, 0), 'AggregateFunction(uniqTheta, UInt64)');
-- Cannot deserialize Theta sketch state: at least 86160 bytes expected, actual 8
-- Cannot deserialize Theta sketch state: at least 2072 bytes expected, actual 8

The size in that message is read from beyond the 8-byte buffer, which is why it differs between runs. Filed as #119595 and fixed by #119598.

Related: #119595

`EXPLAIN QUERY TREE` exists only with the analyzer, so the configurations that
run the suite with `enable_analyzer = 0` answered that arm with a rejection
instead of a query tree - and the rejection is not the same for a readable, a
hidden and a missing source table, so the test reported a disclosure that the
statement never made. Pin the setting for that comparison, which is what the
other configurations were exercising all along.

Fixes the `05059_mergeTreeCodecBlockCounts_access` failure in
`Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel)`.
@clickhouse-gh clickhouse-gh Bot added comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). and removed comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Sep 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both reds on fca3eb85 are unrelated to this pull request, and neither is cleared by merging master, so I left the branch where it is (it merged master this morning and is only a few hours behind).

  1. Stress test (arm_asan_ubsan, s3) — Cannot start clickhouse-server, Code: 36 ... Path does not exist: /var/lib/clickhouse/user_files/d_05153_test_..._21520: while loading database db_05153_test_..._23401. This is 05153_database_filesystem_cache_read_on_file_grant on master: it removes the directory of its Filesystem database unconditionally, while the DROP DATABASE that precedes it fails whenever the server is gone — routine under a stress run — so the database's metadata outlives the path it points at and every later start aborts. Fix: Do not leave a Filesystem database pointing at a removed directory, which makes the server refuse to start #119618.

  2. Integration tests (arm_binary, distributed plan, 1/4) — test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write, already tagged retry_ok, issue against Flaky test: test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write #116417 (open).

The AI review on the current head is ✅ Approve, and the two open threads both end with my own replies from 2026-08-31 — nothing is owed on this pull request.

alexey-milovidov and others added 2 commits September 13, 2026 07:21
…ockCounts(...)`

Master (e5ae260) now refuses to persist any `MergeTree` introspection table function through
`canBeUsedToCreateTable`, and pins that in `05138_forbid_mergetree_introspection_table_functions_as_engine`.
The arm of `05059_mergeTreeCodecBlockCounts_access` that created such a table and read it as another user
can no longer run, so it is removed together with its reference lines.

The comment master attached to the veto said the storage holds the source table's storage object; on this
branch `StorageMergeTreeCodecBlockCounts` holds only the source's `StorageID` and resolves it on every read,
so the comment is reworded: the veto is kept for parity with the sibling functions. The comments that
justified the per-read resolution by the persisted-table path are reworded accordingly.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (cf5b6317) and reconciled with e5ae26012b92, which now refuses CREATE TABLE ... AS mergeTreeCodecBlockCounts(...) through canBeUsedToCreateTable for every MergeTree introspection table function, pinned by 05138_forbid_mergetree_introspection_table_functions_as_engine.

  • The arm of 05059_mergeTreeCodecBlockCounts_access that created such a table and read it as another user cannot run any more, so 343f74b8 removes it with its reference lines. The rest of the test is unchanged.
  • The comment master attached to the veto says the storage holds the source table's storage object. On this branch StorageMergeTreeCodecBlockCounts holds only the source's StorageID and resolves it on every read, so the comment now says the veto is kept for parity with the sibling functions, and the comments that justified the per-read resolution by the persisted-table path are reworded to match.

Verified on a local build of the merged head: both 05059_mergeTreeCodecBlockCounts_access and 05138_forbid_mergetree_introspection_table_functions_as_engine pass. The scope against master is still the same five files.

The two reds on fca3eb85 were unrelated, as documented above; their fixes (#119618 and #116417) are still open.

`canBeUsedToCreateTable` refuses `CREATE TABLE ... AS mergeTreeCodecBlockCounts(...)`, but it is checked
only on the outermost table function, so the same function nested in an argument of another one still
reaches a persisted definition: both `remote(..., f(...))` and `ENGINE = Remote(..., f(...))` keep it in
`remote_table_function_ptr`.

That carrier is closed by this change rather than by the veto. For a cluster with a local shard, both
forms resolve the nested function under the creating user's context, through
`getStructureOfRemoteTableInShard` -> `getActualTableStructureWithAccess`, which is the seam the check
was added to. Measured on a build of this branch: with every privilege the carrier itself needs already
granted, and none on the source table, both forms answer `ACCESS_DENIED`; the same shape over
`mergeTreeIndex`, whose check is added in #116793, creates the table.

Four arms, one per form and per privilege tier: `SELECT` when only one column of the source table is
granted, and `SHOW TABLES` when the source table is one the user may not see at all. A fifth arm pins
that no destination table is left behind. The privilege each attempt demanded is reported next to the
error code, so an arm cannot pass on a refusal that came from the carrier instead of the source table.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 14, 2026
Merged via the queue into master with commit db6be8a Sep 14, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the mergetree-codec-block-counts-access-check branch September 14, 2026 16:26
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
PedroTadim added a commit that referenced this pull request Sep 17, 2026
Cherry pick #116647 to 26.8: Check access to the source table when resolving the structure of `mergeTreeCodecBlockCounts`
robot-clickhouse added a commit that referenced this pull request Sep 17, 2026
…ving the structure of `mergeTreeCodecBlockCounts`
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 17, 2026
Backport #116647 to 26.8: Check access to the source table when resolving the structure of `mergeTreeCodecBlockCounts`
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]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 3, 2026
`compact_theta_sketch_parser::parse` verifies that the buffer holds 8 bytes and
then, for serial versions 1, 2 and 3, reads `num_entries` at offset 8 and `theta`
at offset 16 before it checks the size again. `ThetaSketchData::read` hands it
the exact size, so a short state is rejected - but only after those reads have
already happened, and any `CAST` from a string can hand it 8 bytes:

    SELECT CAST(char(8, 0, 1, 3, 0, 0, 0, 0, 0), 'AggregateFunction(uniqTheta, UInt64)');
    -- Cannot deserialize Theta sketch state: at least 86160 bytes expected, actual 8
    -- Cannot deserialize Theta sketch state: at least 2072 bytes expected, actual 8

An ASan build reports the read as a heap-buffer-overflow; a release build spells
whichever size the neighbouring bytes happen to hold, which is why the same query
answers differently from run to run.

Pad the buffer to the largest offset the parser reads before validating anything,
while still declaring the true length to it: the premature header reads stay
inside the allocation and the parser's own size check rejects the state. The
upstream fix is to move each `check_memory_size` before the field it guards; the
padding is what keeps the read in bounds for every version of `datasketches-cpp`
this repository pulls in.

Found by the AST fuzzer on an unrelated pull request (ClickHouse#116647, STID 1740-4c22).

Closes: ClickHouse#119595
Ergus pushed a commit to Ergus/ClickHouse that referenced this pull request Nov 3, 2026
… 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements 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 v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants