Repository navigation
Require the privilege on every table in an Alias chain - #118967
Conversation
`StorageAlias::isTargetTableGranted` authorized the name written in the alias's own definition, while `StorageAlias::getInMemoryMetadataPtr` resolves through nested aliases. The one-hop contract holds only under an invariant that CREATE establishes and nothing maintains: `registerStorageAlias` rejects an `Alias` target only for a freshly supplied definition and only when that target already exists, so an outer alias created while the inner name is still absent stores a chain the check never saw, and rejecting it at metadata-load time is not an option because a rejection there fails the whole load. The read path does not have the bug: it is recursive, so every hop authorizes its own target before delegating. A user holding SHOW COLUMNS on `outer` and `inner` and nothing on the final table therefore read that table's schema through DESCRIBE, hasColumnInTable, system.columns, system.tables, system.projections, system.constraints and system.data_skipping_indices. One rule, two predicates. `isTargetTableGranted` keeps its name, so a call site added later inherits the strict check, and now walks the chain iteratively, requiring the privilege at every hop. The walk is iterative rather than recursive and carries a visited set because a cyclic definition is loadable state, and 8 of the call sites are system table row filters that skip a row instead of throwing: a recursive walk would reach checkStackSize and throw TOO_DEEP_RECURSION there. The set is keyed on StorageID::DatabaseAndTableNameHash rather than getFullTableName(), which throws UNKNOWN_DATABASE on an empty database name. The two system table callers that authorize per column ask the chain question once per table and fall back to the per-column check only when the caller relies on column-level grants: a table-level grant covers every column of that table, so the hoisted answer is exact, and it keeps a granted read from paying an uncached catalog lookup per hop for every column. The extracted one-hop body becomes `isDeclaredTargetGranted` for the two surfaces that expose only the alias's own stored definition and resolve nothing through it: SHOW CREATE TABLE, and create_table_query / engine_full / as_select in system.tables. Walking the chain there would turn a legal read into ACCESS_DENIED for a user granted on the declared target. Every other system.tables column stays on the chain predicate, including parameterized_view_parameters, whose value comes from getInMemoryMetadataPtr and not from the stored CREATE text. The new test builds a three-hop chain, so a fix that unrolls one extra hop does not pass it, and pins both halves of the rule: the disclosure arms redden if the walk is removed, and the SHOW CREATE TABLE and create_table_query arms redden if the two predicates are collapsed back into one. It also pins the hops in between: one arm denies a second user who holds the privilege on the declared target and on the final table but not on the alias between them, because a check of those two endpoints alone passes every other arm. All three properties were verified by mutating the fix. Three further arms pin what a green test would otherwise leave free: a third user whose grant on the final table is column-level, so the hoisted check is false and the per-column fallback is what answers; a system.tables arm taken after the final grant, so a caller that suppressed its resolved fields unconditionally reddens instead of passing; and, in 04946_storage_alias_attach_stored_definition, a bounded DESCRIBE of a cyclic definition, the only test that enters the walk with a cycle, so removing the visited set turns a prompt TOO_DEEP_RECURSION into a hang. Every surface named above is pinned at chain depth by that test, rather than only at one hop by 03636_storage_alias_metadata_access_rights, where the declared target is the final table and the two predicates are indistinguishable by construction. hasColumnInTable, system.projections, system.constraints and system.data_skipping_indices each get an arm through the chain and an over-denial arm taken after the final table is granted, so pointing any of those callers at the declared predicate reddens the test instead of passing it. Both declared surfaces are asserted by content rather than by non-emptiness: the rendered SHOW CREATE TABLE text and create_table_query must name the declared target and must contain neither the final table's name nor any of its column names, and the same filter is run over a definition that does name it, so the absence is measured. A renderer that began resolving the chain would redden those arms even though its output would still be non-empty. Co-Authored-By: Claude Opus 5 <[email protected]>
`checkAccessRights` (new analyzer) and `TreeRewriterResult::collectUsedColumns` (old analyzer) authorize every column of the table when the query names no column, which is what `SELECT count() FROM al` and `SELECT 1 FROM al` do. Each per-column `isTargetTableGranted` resolves the chain through `DatabaseCatalog::tryGetTable` on the storage's global context, and that path consults the per-query storage cache only for a context that has a query context, which a global one never has. So for a target in a Remote, PostgreSQL or SQLite database every hop is a fresh schema fetch, once per column, where the same query over a plain table fetches nothing. Both loops now ask the chain question once per table and fall back to the per-column call only when that answer is false, which is exact because a table-level grant covers every column of the table. `SELECT count()` over a 200-column target in a Remote database: 220 remote DESCRIBE round trips and 511 ms before, 21 and 117 ms after; with the old analyzer 431 and 968 ms before, 33 and 147 ms after. A query that names its columns does not enter either loop and is unchanged at 14 round trips. `supportsTrivialCountOptimization` in InterpreterSelectQuery and StorageAlias leave the loop on the first granted column, so a granted user already pays about one lookup there and hoisting would only add one. Three arms in the new test pin `system.completions`, the one surface this change touches that the test did not query. Its two checks were covered only by 03636_storage_alias_metadata_access_rights, where the alias points straight at the final table so the strict and declared predicates cannot be told apart: pointing either of them at the declared predicate restored the disclosure and left every test green. The pre-grant arm counts the columns visible through the chain, the column-level arm makes the per-column fallback answer rather than the hoisted check, and the post-grant arm reddens a caller that suppresses the rows unconditionally. Each runs as a restricted user, because `belongs` carries no database qualifier and only a restricted user reaches the SHOW_TABLES filter that keeps a concurrently running copy of the test out of the result. Co-Authored-By: Claude Opus 5 <[email protected]>
dca2802 hoisted one table-level `isTargetTableGranted(..., {})` out of the four per-column authorization loops and fell back to the per-column call when that answer was false. That fallback is reached whenever the user's privilege on a hop is column scoped, because an empty column name routes to the three-argument `AccessRights::isGranted`, whose table node check requires the flags on the table and on every tracked column of it. A user granted K of N columns therefore took the fallback at all four sites and resolved the chain again for each surviving column, once per hop and uncached, because `StorageAlias` binds `WithContext` to the global context and `DatabaseCatalog::tryGetTable` consults the per-query storage cache only for a context that has a query context. Column level grants are a supported RBAC shape and `system.columns` is what a client scans on connect, so this was a regression this change would have introduced where master's one-hop predicate performed zero catalog lookups. `filterColumnsGrantedThroughChain` replaces both predicates with one traversal that takes the caller's whole column list and returns the subset granted on every table the alias resolves through. No per-column fallback call is left: each of the four loops asks once per table, whatever the grants look like. `isTargetTableGranted` becomes a one element call into it, so the eight table granularity call sites keep their semantics byte for byte. The filtered set equals the per-column answer, column by column. A column survives iff every hop up to the chain's end granted it, which is the previous loop's exit condition; a column denied at the first hop is erased before any resolution, so a caller denied everywhere still resolves nothing; the visited set is column independent, so the cycle exit returns exactly the columns the per-column walk returned true for; and a null query context erases every column, because `isDeclaredTargetGranted` returns false for it. `SELECT count()` for a user holding table level rights on the alias and a column scoped grant on 199 of a 200 column target in a Remote database: 219 remote DESCRIBE round trips and 474 ms before, 21 and 111 ms after; with the old analyzer 429 and 876 ms before, 33 and 138 ms after; that user's `system.columns` scan 200 and 445 ms before, 2 and 74 ms after. The fully granted shape is unchanged at 21, 33, 14 and 2 round trips. `checkAccessRightsForSelect` in InterpreterSelectQuery, not `supportsTrivialCountOptimization`, is the loop dca2802's message meant: `supportsTrivialCountOptimization` is defined only in StorageAlias and is merely called from InterpreterSelectQuery. Both still leave their loop on the first granted column, so a filter call in either would only add work, and both keep their loops. One test arm covers the grant shape that distinguishes a table level probe from a per-column one: a table grant on the final table with one column revoked. Master shows that user both column names; the walk shows one. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model: seven cold reads of the resulting code and eight gate Six fix rounds are all this process funds, and the sixth is spent, so row 25 is published as a known
The changelog names the seven surfaces whose disclosure it fixes; Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20260909-060300 |
|
Workflow [PR], commit [3a70cb7] Summary: ✅
AI ReviewSummaryThis PR tightens Findings❌ Blockers
Final VerdictStatus: Minimum required actions: close the pre- LLVM Coverage ReportMeasured on commit 3a70cb7.
Changed lines: Changed C/C++ lines covered: 118/130 (90.77%) · Uncovered code |
|
cc @nauu @pufit, could you review this? |
|
cc @nauu |
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - b497f15Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260909-113112 |
|
@groeneai make the PR green |
`StorageAlias::totalRows` and `totalBytes` authorized the whole chain and then delegated to the target, whose own `totalRows` authorized the rest of the chain again, so one call did O(depth^2) catalog lookups and a `system.tables` scan that reads both statistics did that for every alias row. The table-level answer composes over the delegation: a hop returns a value only if its own declared target is granted, and the target is asked the same question when it is an Alias, so checking the declared target alone yields the same conjunction over the chain. Measured with a 128-deep chain and one `SELECT count(), countIf(total_rows IS NOT NULL), countIf(total_bytes IS NOT NULL) FROM system.tables` (`clickhouse local`, debug build, 3 runs each): master 0.24-0.25 s, this branch before this commit 1.29-1.35 s, after 0.21-0.23 s. The chain-wide form stays where the answer does not compose: the per-column sites, where a column may be granted at one hop and a different column at the next, and `supportsTrivialCountOptimization`, which asks whether ANY column is readable and would otherwise accept a chain whose hops grant different columns. Behaviour is unchanged, both directions: with the middle hop of `outer -> hop -> base` not granted, `system.tables` reports NULL `total_rows` and `total_bytes` for `outer`; granting `SHOW TABLES` on that hop makes both appear. The 19 `storage_alias` stateless tests pass.
|
On it. All three reds on
I cannot re-run individual jobs, so I merged master to roll CI again; the head is now The two random reds should clear on this roll. |
|
@groeneai please check the pending review comments |
|
I checked both review surfaces on this PR and there is nothing of yours visible to me. Here: one review thread, the bot's If you started a review, GitHub keeps its comments pending and visible only to you until you press "Submit review", which is why I cannot read them. Please submit it, or paste the file and line here, and I will answer straight away. The review comments I can find still open in this family are on #117572 (merged 2026-09-22): the bot left three on 2026-09-16, on |
|
|
||
| /// Same, for the target named in this alias's own definition only. For callers that expose that | ||
| /// definition and resolve nothing through it. | ||
| bool isDeclaredTargetGranted(ContextPtr query_context, AccessType access_type, const String & column_name) const; |
There was a problem hiding this comment.
Should we use isDeclaredTargetGranted in totalRows and totalBytes, so each Alias checks its direct target before delegating, so all hops remain checked without repeatedly for the entire chain
There was a problem hiding this comment.
That is what the current head already does, since 68ef8e32eb92c (pushed on 2026-09-21, after this comment was drafted): totalRows and totalBytes ask isDeclaredTargetGranted for their own declared target and then delegate, and the delegation re-enters the same method when the target is itself an Alias, so every hop asks its own one-hop question (src/Storages/StorageAlias.cpp:528 and :537). On a 128-deep chain, SELECT countIf(total_rows IS NOT NULL), countIf(total_bytes IS NOT NULL) FROM system.tables went from 1.34 s to 0.23 s, which is parity with master's 0.24 s.
The same composition does not hold for the per-column sites or for supportsTrivialCountOptimization: hop 1 may grant column x and hop 2 only column y, so a one-hop answer per hop would say yes where the chain-wide question says no. Those keep the full walk, and your other comment is what makes it cheap.
| /// Owns the storage `alias` points into, from the second hop on. | ||
| StoragePtr alias_holder; | ||
|
|
||
| while (!granted.empty()) |
There was a problem hiding this comment.
We can avoids checks here for fully granted tables
There was a problem hiding this comment.
Done in 9d05e41ff5b62. Where more than one name is left to test, the hop now asks one table-level question instead of running the per-column pass: a table node is granted only when the flags hold for the table and for all of its columns, so a granted table implies every column of it is granted. Where a single name is left, the question would replace a single check, and for the table-level callers it would be that same check asked twice, so it is not asked there.
Measured on a 32-hop stored chain over a 200-column table, with the user holding SHOW TABLES, SHOW COLUMNS on the whole database, one debug build per arm:
| query | before | after |
|---|---|---|
system.columns for one alias of the chain |
10 ms | 1 ms |
system.columns for all 33 tables |
145 ms | 6 ms |
The 200 rows visible through the chain are identical in both arms.
05137_storage_alias_chain_metadata_access_rights already carries the arm that reddens if the skip is taken when it must not be: one user holds SHOW COLUMNS on the final table with a single column revoked, another holds a column-level grant only. Removing the table-level question and skipping on name count alone fails that test and 03636_storage_alias_metadata_access_rights, with the revoked secret_payload appearing in three arms.
`filterColumnsGrantedThroughChain` asked the grant question once per column at every hop, so a caller that passes a whole column list paid hops x columns checks. `system.columns` is such a caller: it hands the alias the table's full column list so the chain is resolved once for the table rather than once per column. A table-level grant covers every column of that table, so where there is more than one name left to test, one table-level question answers the whole per-column pass for that hop. The answer is identical: a table node is granted only when the flags hold for it and for all of its columns, so a granted table implies every one of its columns is granted. Where only one name is left the question would replace a single check, and for the table-level callers it would be that same check asked twice, so it is not asked there. Measured on a 32-hop stored chain over a 200-column table, with the user holding SHOW TABLES and SHOW COLUMNS on the whole database, on one debug build per arm: system.columns for one alias 10 ms -> 1 ms (5 runs, min = median = max) system.columns for all 33 145 ms -> 6 ms (3 runs) The 33 rows visible through the chain are unchanged in both arms. 05137_storage_alias_chain_metadata_access_rights already carries the arm that reddens if the skip is taken when it must not be: one user holds SHOW COLUMNS on the final table with a single column revoked, another holds a column-level grant only. With the table-level question removed and the skip taken on name count alone, that test fails and the revoked `secret_payload` appears in three of its arms, together with 03636_storage_alias_metadata_access_rights.
…cenario `Storage memory check` fails unrelated PRs with a byte-constant `change=+1,056`. Since ClickHouse#120487 removed the one-time initialization offset, 9 heads had `+1,056` as their only failing scenario, on `03_add_secondary_indexes.sql` and `04_add_projection.sql`. A pooled thread that runs a mutation step attaches to the task's `ThreadGroup` through `ThreadGroupSwitcher`, and that attach constructs thread-local performance-counter state: `TasksStatsCounters`, a `ProcfsMetricsProvider`, and two `__cxa_thread_atexit_impl` registrations which by construction live until the thread exits. `GlobalThreadPool` keeps its threads, so those bytes stay live once a thread has participated, and the quantity the checkpoint diff measures is how many distinct pool threads have ever served the scenario. Which window a thread's first participation lands in is a scheduling draw. It is one cluster of 7 stacks costing exactly 528 bytes per participating thread: +384 `TasksStatsCounters::create`, -64 `ThreadGroup::SharedData::SharedData`, +64 `detachFromGroup`, +48 `make_shared<ProcfsMetricsProvider>`, +32 and +32 for the two `__cxa_thread_atexit_impl` registrations, +32 for the query-id string copy in `applyQuerySettings`. The gate is `absolute_change > 1024 AND percent_change > 1.0`, so one unit passes and two clear it by 32 bytes: the threshold sits inside the noise quantum. PR ClickHouse#120702 at `b48703670359` has rows for `04_add_projection.sql` at both 528 and 1,056, the same commit measured twice with different answers, so no threshold value could measure this quantity. Raising the threshold is the move that already failed: `150d1f2d0290b` raised this lane from the parser lane's 100 to 1,024 for this exact mechanism, and two units cleared it three days later. Waiting for background tasks to quiesce cannot work either, because this state is registered with `__cxa_thread_atexit_impl` and is not a teardown tail. Pinning the pools to one thread would be C++-side, and the master arm binary is downloaded from the merge base, so such a fix is asymmetric until it reaches master. Instead add the three thread attach/detach frames to the analyzer's existing `EXCLUDED_STACK_FRAME_PREFIXES`, which `compute_diff` already consults before a stack reaches the gated total. Both arms of a run are analysed by the same script from the same checkout, so the change applies symmetrically from the first run, and keying on the allocation site covers every pool at once rather than enumerating pools or settings. On the production reports for ClickHouse#118967, ClickHouse#120960, ClickHouse#121251 and ClickHouse#120702, removing this cluster takes every failing scenario's change to exactly 0, with the largest residual anywhere 64 bytes against the 1,024-byte threshold. Locally, 20 repeated two-pass runs of one binary reproduce the 528-byte unit with the same 7-row composition and a multiplicity that varies run to run; an injected 64 KiB-per-table allocation is still reported at full size; and reverting only these three prefixes restores the pre-fix numbers byte-for-byte. Two consequences are deliberate. The cluster rows also leave the HTML report, exactly as `dumpProfile` overhead already does, because a row the check must not gate on should not be presented as a finding. And thread-accounting regressions are no longer measured here, which the same-commit pair above shows was never possible anyway. `STORAGE_CHANGE_THRESHOLD_BYTES` is left at 1,024. Removing this noise is what would make lowering it toward the parser lane's 100 possible, but that is a calibration decision with its own data. Related: ClickHouse#120487 Related: ClickHouse#119480 Co-Authored-By: Claude Opus 5 <[email protected]>
05137_storage_alias_chain_metadata_access_rights covered the chain on the metadata surfaces and, on the query path, only the all-or-nothing denial of `SELECT count() FROM chain_a1` for a user holding nothing at all on the final table. Measured against a build whose chain walk stops after the declared target, which is the semantics this branch replaces, that arm is denied in both builds, so it cannot see the difference: `StorageAlias::read` re-checks its own declared target at every hop, and that recursion reproduces the chain check for any query that reads a column. The zero-column shape is the one whose authorization is decided by `checkAccessRights` alone. It is observable only where the chain grants no column at all, because with one column granted end to end the count is the same however far the walk goes. So `chain_sel_user` holds `SELECT(secret_payload)` on the three alias names and `SELECT(secret_id)` on the final table, leaving nothing granted through the whole chain. Measured on this tree, one debug build per arm: ACCESS_DENIED with the walk, row count 2 without it. The second arm grants the missing column on the final table and requires the count back, so the denial cannot pass by denying everything. The `optimize_trivial_count_query = 0` variant is deliberately absent: both builds deny it, the read path being what denies it, so it could not fail. The 19 `storage_alias` stateless tests pass, together with 05055_has_column_in_table_alias_access_check, 04402_grant_select_alias_column, 05153_alias_truncate_lock and 04324_alter_through_alias_exchange_race, and this test passes 10 out of 10 runs under randomized settings.
The same two lines stood above every batched `filterColumnsGrantedThroughChain` call, stating why the call sits outside the per-column loop. The hoisted code already shows that, and four copies of one motivation is noise in the diff. The reason belongs here: a chain walk costs one access question per hop, so asking it once for the whole column list instead of once per column keeps the per-column passes linear in the number of columns rather than quadratic in columns times hops.
| all_columns.reserve(columns.size()); | ||
| for (const auto & column : columns) | ||
| all_columns.push_back(column.name); | ||
| chain_granted = alias->filterColumnsGrantedThroughChain(context, AccessType::SHOW_COLUMNS, all_columns); |
There was a problem hiding this comment.
filterColumnsGrantedThroughChain only runs after storage->getInMemoryMetadataPtr above, so this surface still resolves the hidden target before the new chain check fires. A loadable cycle is the concrete trace: for a1 -> a2 -> a1, system.columns reaches StorageAlias::getInMemoryMetadataPtr, recurses until TOO_DEEP_RECURSION, and never gets to the filter, even for a user who lacks the grant on a2. StorageSystemCompletions has the same ordering (src/Storages/System/StorageSystemCompletions.cpp:95-104). That means these two entrypoints still disclose target-side metadata/error text instead of denying or filtering first.
The access precheck needs to happen before alias metadata is resolved on these surfaces, or the metadata fetch itself needs an access-aware helper. Please also add a focused negative arm that runs system.columns and system.completions against a cyclic alias as a user missing one hop of the chain and requires denial/no rows rather than TOO_DEEP_RECURSION.
Related: #117702 (comment)
Related: #117490
Related: #117448
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed metadata disclosure through a chain of
Aliastables.DESCRIBE,hasColumnInTable,system.columns,system.tables,system.projections,system.constraintsandsystem.data_skipping_indicesnow require the privilege on every table anAliasresolves through, as reading its rows already did; previously only the table named in the alias's own definition was checked, so a user granted onouterandinnerbut not on the final table could read that table's schema.SHOW CREATE TABLEandsystem.tables'screate_table_query,engine_fullandas_selectexpose only the alias's own definition and still require the privilege on the declared target alone.Description
StorageAlias::isTargetTableGrantedauthorized only the name in the alias's own definition, whilegetInMemoryMetadataPtrresolves through nested aliases. A chained state is reachable and must stay loadable:registerStorageAliasrejects anAliastarget only in a freshly supplied definition whose target already exists, so an outer alias created while the inner name is absent stores a chain the check never saw; rejecting it at load time would fail the load. The read path is unaffected: it is recursive, so every hop authorizes its own target.One rule, two predicates.
isTargetTableGrantedkeeps its name, so a call site added later inherits the strict check, and now walks the chain iteratively: the visited set lets a cyclic definition terminate, and iteration avoids theTOO_DEEP_RECURSIONthe 8 row-filteringsystem.*sites cannot take. The extracted one-hop body becomesisDeclaredTargetGrantedfor the two surfaces that render the stored definition and resolve nothing through it. Every other call site keeps the strict predicate. Callers that need every column's answer ask the chain question once per table, not once per column.The new stateless test builds a three-hop chain and asserts the disclosure is gone wherever the missing grant sits, the declared surface still works, and a granted user loses nothing; it fails on master. All 35
ENGINE = Aliasstateless tests stay green, andsystem.columnsover 200 alias tables to local targets costs the same (0.08 s).Separately owned, not fixed here:
lazy_load_tableshides the engine from these checks (#117490);Aliasrow policies are still combined one hop deep, which #118668 refactors;MySQLHandler::comFieldListandTableFunctionLoop::getActualTableStructuredo not reach the guard at all.Workflow [PR]
Sync PR [sync-upstream/pr/118967]
Version info
26.10.1.575-master(included in26.10and later)