Repository navigation
Check access to the source table in the MergeTree introspection table functions - #116793
nikitamikhaylov merged 19 commits into
Conversation
… 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
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
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260827-202000 |
Pre-PR validation gate (click to expand)
Also run: 27 existing tests covering these functions, including all 13 that use Five mutations, each reddening a disjoint and narrow set: Session id: cron:clickhouse-impl-slot-40:20260827-190100 |
|
Workflow [PR], commit [c454021] Summary: ✅
AI ReviewSummaryThe PR adds source-object authorization to table-function structure resolution and execution, including delegated checks for Missing context / blind spots
Findings❌ Blockers
Tests
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. |
|
cc @pufit @nikitamikhaylov, could you review this? It adds one virtual to |
Build profile diff (arm_release)Commit 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 looks good to me, but this is API change to |
|
Review is already requested for exactly that reason: #116793 (comment) (2026-08-27 21:12Z) asks @ pufit and @ nikitamikhaylov and calls out the 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,
|
CI finish ledger - 16339a3Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link 175 check-runs, 0 incomplete,
Session id: cron:our-pr-ci-monitor:20260828-123000 |
|
Fixing PR for the |
`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]>
|
@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]>
|
The only red check is All
Re-running a single job needs write access, which I do not have, and the hourly One caveat: |
CI finish ledger - 181e0b3Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
None of the rows above is caused by this pull request. On the On the Session id: |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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. |
…tion-source-object-access
| 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); |
There was a problem hiding this comment.
❌ [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.
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]>
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]>
Cherry pick #116793 to 26.9: Check access to the source table in the MergeTree introspection table functions
…geTree introspection table functions
Cherry pick #116793 to 26.10: Check access to the source table in the MergeTree introspection table functions
…rgeTree introspection table functions
…geTree introspection table functions
Related: #116647
Related: #116647 (comment)
Related: #120529
Changelog category (leave one):
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,viewIfPermittedandlooptable functions. Resolving their structure, for example withDESCRIBE, required no privilege on the source table, anAliassource was read with no privilege on its target, and a source that did not exist or had another engine was named in the error.viewIfPermittedresolved anELSE executable(...)with noTABLE ENGINEgrant. Reading them was already checked.Description
Follow-up to #116647.
ITableFunctionhad no way to say a function reads another object's metadata, so each checked for itself; five did not.getActualTableStructureWithAccesschecked only the source kind (READ ON S3), never a source object, soDESCRIBE mergeTreeIndex(db, t)returned the primary key and every per-substream mark name of a table the caller cannotDESCRIBE, andmergeTreeProjectiona projection's columns.executechecked nothing either.I add one virtual,
checkSourceObjectAccess, called from both seams. Resolving a structure requiresSHOW COLUMNS, whatDESCRIBEof that table needs; execution requiresSHOW TABLES, which still reveals whether a named index or projection exists. Neither is chosen:02947_merge_tree_index_table_3forbidsSHOW COLUMNSthere,04514is the merged precedent.StorageAliasforwards metadata to its target unchecked, so the check binds that target too, at the seam and each consuming site.loopgot it on its structure path, a contract04411and04945assert.viewIfPermittednow 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 withoutREAD ON URL, nor resolves anELSE executable(...)without aTABLE ENGINEgrant.Not covered:
mergeTreeAnalyzeIndexesUUID(a UUID names nothing) anddictionary(its own privilege decision). Residuals:viewandevalresolve a structure through the analysis-only planner path, which checks no table-function node, soDESCRIBE view(SELECT * FROM mergeTreeIndex(db, t, with_marks = true))needs onlySHOW TABLES; closing it means checking table functions in the planner. A read of no rows throughloopstill reports anAliastarget's columns. ReadingmergeTreeProjectionthrough anAliasfails an internal cast; unwrapping or rejecting is separate.Complements #116629 (same class,
timeSeries*).Workflow [PR]
Sync PR [sync-upstream/pr/116793]
Version info
26.11.1.1224-master(included in26.11and later)