Skip to content

Require the privilege on every table in an Alias chain - #118967

Merged
nauu merged 10 commits into
ClickHouse:masterfrom
groeneai:alias-chain-target-grant
Sep 24, 2026
Merged

nauu merged 10 commits into
ClickHouse:masterfrom
groeneai:alias-chain-target-grant

Conversation

@groeneai

@groeneai groeneai commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117702 (comment)
Related: #117490
Related: #117448

Changelog category (leave one):

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

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

Fixed metadata disclosure through a chain of Alias tables. DESCRIBE, hasColumnInTable, system.columns, system.tables, system.projections, system.constraints and system.data_skipping_indices now require the privilege on every table an Alias resolves through, as reading its rows already did; previously only the table named in the alias's own definition was checked, so a user granted on outer and inner but not on the final table could read that table's schema. SHOW CREATE TABLE and system.tables's create_table_query, engine_full and as_select expose only the alias's own definition and still require the privilege on the declared target alone.

Description

StorageAlias::isTargetTableGranted authorized only the name in the alias's own definition, while getInMemoryMetadataPtr resolves through nested aliases. A chained state is reachable and must stay loadable: registerStorageAlias rejects an Alias target 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. isTargetTableGranted keeps 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 the TOO_DEEP_RECURSION the 8 row-filtering system.* sites cannot take. The extracted one-hop body becomes isDeclaredTargetGranted for 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 = Alias stateless tests stay green, and system.columns over 200 alias tables to local targets costs the same (0.08 s).

Separately owned, not fixed here: lazy_load_tables hides the engine from these checks (#117490); Alias row policies are still combined one hop deep, which #118668 refactors; MySQLHandler::comFieldList and TableFunctionLoop::getActualTableStructure do not reach the guard at all.


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

Version info

  • Merged into: 26.10.1.575-master (included in 26.10 and later)

groeneai and others added 3 commits September 8, 2026 18:56
`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author
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
passes (engine: codex) across six fix rounds, 25 findings adjudicated. Rounds 1-3 were test-only, with
the source byte-identical from the first review; rounds 4-6 also moved the per-column callers to one
chain resolution per table.

Six fix rounds are all this process funds, and the sixth is spent, so row 25 is published as a known
residual instead of being fixed here. It is a cost residual on a chained alias whose final table lives
in a schema-fetching database; no disclosure path is left open by it, and nothing else in the final
round's read or gate pass was a blocker or a major.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test could not detect a predicate that checks the declared target and the final table but skips intermediate hops AGREE, fixed New arm: a second user granted on the outer alias, the declared target and the final table, nothing on the middle alias. A mutant implementing that weaker rule reddens this arm alone; non-vacuity measured (the statement succeeds once the middle hop is granted)
2 ⚠️ Four surfaces the changelog names (hasColumnInTable, system.projections, system.constraints, system.data_skipping_indices) were pinned only at one hop, where the two predicates are indistinguishable AGREE, fixed The fixture now carries an index, a projection and a constraint and asserts all four surfaces before and after the missing grant; all four redden on master
3 ⚠️ system.tables.create_table_query was asserted only non-empty AGREE, fixed Now asserted by content: the declared target appears, the final table and its column names do not, engine_full pinned alongside. Justified by what that row stores, not by any claim that an Alias definition is columnless (it is not, when its target exists at creation)
4 ⚠️ The SHOW CREATE TABLE arm kept only the two allowed tokens, so appended resolved metadata would pass it AGREE, fixed Same content form as row 3, over the one call site whose predicate this diff switches, plus a control over a definition that does name its target so the absence assertion is not vacuous
5 ⚠️ The chain walk re-resolves every hop once per column, so system.columns and system.completions turn one schema fetch into N for a target in a Remote, PostgreSQL or SQLite database AGREE, fixed Real and this change's own: the walk resolves through the global context, which never has a query context, so DatabaseCatalog::tryGetTable skips its per-query cache. Measured 201 remote DESCRIBE round trips for a 200-column target, 2 after the fix
6 ⚠️ Nothing asserted that chain-derived system.tables metadata becomes visible once every hop is granted AGREE, fixed It was the one named surface with no over-denial arm at chain depth, and this change adds a weaker sibling flag next to can_expose_metadata in the same function. New post-grant arm asserts sorting_key and total_rows, which the pre-grant arm sees suppressed, so the pair is a measured before/after
7 ⚠️ Nothing exercised the visited set that stops the new walk from looping forever on a loadable cyclic definition AGREE, fixed DESCRIBE consults the predicate before resolving metadata, so a cyclic alias enters the walk, whose only exit there is the repeated-name check. Added a bounded DESCRIBE assertion to the existing cycle test, which already owns that fixture, so the new test stays parallel-safe. It is a regression pin, not a master discriminator: master's one-hop predicate cannot loop
8 ❌ Authorization and metadata resolution can observe different chains, so a concurrent EXCHANGE TABLES bypasses the final-table check DISAGREE Unchanged by this diff: the old predicate was purely name-based and its caller resolved afterwards through the same global-context path, so the window is identical. And arranging the swap means creating an ENGINE = Alias to the hidden table, which registerStorageAlias gates on SHOW COLUMNS on that target (StorageAlias.cpp:576)
9 ⚠️ Declared-only system.tables columns now resolve the chain and can propagate a downstream error DISAGREE StorageSystemTables.cpp:828-830 already resolves unconditionally for granted alias rows through the same tryGetTable, with no column-mask guard; per row this diff resolves the same hops or fewer
10 💡 hasColumnInTable's docs still equate its grant with DESCRIBE and SHOW CREATE TABLE DISAGREE The DESCRIBE half stays exact; the other half is imprecise only for a chained alias, where behaviour errs strict. The sentence is mirrored verbatim in a generated docs page, so correcting it edits two untouched files on a security change. Declined, not deferred
11 💡 Use Critical Bug Fix (crash, data loss, RBAC) DISAGREE Not self-applied; asked in the review request instead, so the owner decides
12 💡 --multiquery is obsolete and does nothing DISAGREE True, and inert: the sibling 03636 test passes it four times and 74 stateless tests use it. Churn on a security diff
13 💡 StorageMerge.cpp:1126 reads a matched table's metadata with no alias guard while :2038 checks SELECT against the alias name DISAGREE, recorded A pre-existing one-hop gap in an untouched file, out of this change's contract. No repro was run, so no claim is made about it and no follow-up is promised
14 💡 Alias row policies are still combined one hop deep AGREE, out of contract Different mechanism, and #118668 rewrites those three sites; disclosed in the description rather than fixed here
15 💡 Changelog named only create_table_query where the diff moves engine_full and as_select with it; description over the length budget; the unguarded loop() path attributed to the statement shape rather than the function AGREE, fixed All three named; description condensed; the residual now names TableFunctionLoop::getActualTableStructure, where the guard is genuinely absent (executeImpl has it)
16 ⚠️ Row 5's class again, in the two loops that fix left behind: checkAccessRights (new analyzer) and TreeRewriterResult::collectUsedColumns (old analyzer) also authorize every column when the query names none AGREE, fixed Twice raised, and reachable: SELECT count() over an Alias to a Remote database made 220 remote schema fetches (431 with the old analyzer) for a 200-column target, 21 and 33 after. A query that names its columns does not enter either loop and is unchanged at 14
17 ⚠️ system.completions was the one changed surface with no arm at chain depth, and the sibling one-hop test cannot tell the two predicates apart AGREE, fixed Three arms added (through the chain, with a column-level grant on the final table, and after the final grant). A mutant pointing that caller at the declared-only predicate restores the disclosure and reddens the new arms while the pre-round test stays green
18 💡 A four-line comment block over the per-block budget, and a comment whose meaning came from another file's comment AGREE, fixed One identical invariant line at each site instead; the cost motivation lives in the commit message
19 💡 The description claimed "15 of 18 call sites untouched" while six call expressions had changed AGREE, fixed Falsifiable by anyone diffing the PR. Replaced with what is actually invariant: every other call site keeps the strict predicate
20 ⚠️ Rows 5 and 16 fixed only the table-level case: a user whose privilege on a hop is column-scoped still takes the per-column path, which resolves the chain again for every granted column AGREE, fixed Third raise of the class, and the sharpest: an empty column name routes to the strict table-level probe, which a column-scoped grant makes false, so the fallback ran per column and the earlier fix was fully defeated at K of N granted columns. Now one traversal takes the caller's whole column list and returns the surviving subset, so at each of the four loops that need every column's answer the chain resolves once per table for every grant shape, and isTargetTableGranted is a one-line wrapper over that same traversal, so the strict rule has a single implementation
21 💡 Nothing pinned the per-column path in the one grant shape where a table-level answer and a per-column answer can differ: a table grant with a column revoke AGREE, fixed New arm: a fourth user granted on every table in the chain with one column revoked on the final one, so the per-column check is what answers. It reddens on master too
22 💡 The walk allocates a set per call, including the one-hop case where master's predicate allocated nothing DISAGREE Measured: system.columns over 200 alias tables x 50 columns is 0.08 s median on both binaries, and every call that allocates also performs a catalog lookup costing orders of magnitude more. Row 20 additionally reduces those calls to one per table
23 💡 Row 20's class in the two loops it deliberately left: checkAccessRightsForSelect and StorageAlias::supportsTrivialCountOptimization still call the per-column predicate in a loop DISAGREE, recorded Bounded by construction, unlike rows 5, 16 and 20: both loops stop at the first granted column, an ENGINE = Alias table cannot live in a schema-fetching database, so every intermediate hop is a local catalog probe, and the walk erases a denied column before resolving anything past it, so the one lookup that can be a remote schema fetch is reached only by a column granted at every hop, after which the loop leaves. Worst case is therefore one fetch per query, not one per column. Stated in the commit message as well
24 💡 system.columns now runs the walk for an alias table before the SHOW_TABLES shortcut can skip that table, so a user who cannot list it still pays the resolution DISAGREE, recorded The column list the filter needs is only available inside the lock scope, above that shortcut, and the pre-existing needs_column_metadata probe sits there too. Bounded at the chain's local probes per hidden alias table, and the final table is resolved only for a user granted through the whole chain, which is what a visible row would have cost anyway
25 ⚠️ StorageAlias::totalRows, totalBytes and supportsTrivialCountOptimization ask the chain question and then delegate to their immediate target, which re-enters the same method when that target is another Alias, so the walk is repeated at every hop AGREE, published as a residual Real, and this change's own: master's one-hop predicate did no lookup, so the recursion cost one resolution of the final table, where this walk costs one per hop (a1 -> a2 -> a3 -> t resolves t four times, and system.tables asks twice, once per statistic). It matters only where a lookup is a schema fetch, i.e. a chained alias onto a Remote, PostgreSQL or SQLite database; for a local target every extra lookup is a catalog probe, which is why the fixture cannot show it. Cost only: the authorization answer, and the set of columns disclosed, are identical either way. The shape that removes it is to thread the resolved terminal storage through the delegation rather than re-deriving it, which is a larger change than a metadata-disclosure fix should carry at this point. Not measured here, so no number is claimed and no follow-up is promised

The changelog names the seven surfaces whose disclosure it fixes; system.completions is an eighth,
fixed by the same change and pinned at chain depth by the same test, so the list understates rather
than overstates what the change covers.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding.

Session id: cron:clickhouse-review-slot-11:20260909-060300

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3a70cb7]

Summary: ✅


AI Review

Summary

This PR tightens Alias chain access checks across the metadata/query surfaces it touches, and the newer tests do a good job covering the one-hop vs whole-chain grant cases. I am still requesting changes because two touched entrypoints, system.columns and system.completions, still resolve the alias target metadata before the new chain check runs, so an unprivileged user can still observe target-side failures instead of an access denial or an empty result.

Findings

❌ Blockers

[src/Storages/System/StorageSystemColumns.cpp:172, src/Storages/System/StorageSystemCompletions.cpp:95] system.columns and system.completions still fetch alias metadata before the chain check. For a loadable cycle such as a1 -> a2 -> a1, an unprivileged query reaches StorageAlias::getInMemoryMetadataPtr first and throws TOO_DEEP_RECURSION, so these entrypoints still disclose target-side metadata/error text without the required grant.
Suggested fix: move the access-aware precheck ahead of getInMemoryMetadataPtr for these surfaces, or introduce a helper that resolves alias metadata only after the chain grant is established; add a focused negative test for the cyclic-alias case on both entrypoints.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions: close the pre-getInMemoryMetadataPtr leak on system.columns / system.completions, and add a regression arm proving those entrypoints deny or filter rather than surfacing target-side exceptions to a user missing one hop of the alias chain.

LLVM Coverage Report

Measured on commit 3a70cb7.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 118/130 (90.77%) · Uncovered code

Full report · Diff report

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

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nauu @pufit, could you review this? isTargetTableGranted authorized only the name written in the alias's own definition while getInMemoryMetadataPtr keeps resolving through nested aliases, so a chained Alias disclosed the final table's schema at every metadata surface; the predicate now walks the chain, and the two surfaces that render only the stored definition keep the one-hop check. I chose Bug Fix over Critical Bug Fix (crash, LOGICAL_ERROR, data loss, RBAC) because I do not self-apply the critical category, so please say if you want it changed.

@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 9, 2026
@PedroTadim

Copy link
Copy Markdown
Member

cc @nauu

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 3a70cb75d2ec61a1e0272373fbdc9afc0f7fad13 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b497f15

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

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: Reading from materialized CTE 'a' before its materialization completed, DelayedPortsProcessor gate is missing in the query plan (STID: 2467-2c2d) trunk LOGICAL_ERROR, raised in MemorySource::generate() (ReadFromMemoryStorageStep.cpp:87) when the plan optimizer leaves out the gate above a materialized CTE reader. Breadth on the STID over 30 days: 57 rows across 37 distinct pull requests and 5 true-master runs, in 10 distinct checks, since 2026-08-10. This branch touches only Alias privilege checks, so it cannot reach the query-plan optimizer #117311 (mine, open)

Session id: cron:our-pr-ci-monitor:20260909-113112

@nauu

nauu commented Sep 21, 2026

Copy link
Copy Markdown
Member

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

Copy link
Copy Markdown
Collaborator Author

On it. All three reds on d0e803bd71fa are off this PR's diff; the other 152 checks passed. Per failure, measured just now:

Stress test (arm_debug): trunk LOGICAL_ERROR "Unexpected return type from plus. Expected UInt64. Got Int64", raised from ExpressionActions::execute under ExecutableFunctionExpression::executeImpl, i.e. inside a lambda body. CIDB over 30 days: 18 rows, 14 distinct PRs, 4 true-master rows, 8 stress flavours, first seen 2026-09-19. Owner: #121230 (a lambda argument shadowing an outer column). I closed my own #115005 for the same defect as superseded by it.

Storage memory check / 04_add_projection.sql: master=+36,784 bytes, PR=+37,840 bytes, change=+1,056 bytes (2.9%). That exact +1,056 byte delta also fired on #120702, #118585, #109377 and #119848 this week, and the scenario fails on 12 of 1,109 runs across 613 PRs in the last 3 days, so it is a property of the check rather than of a diff. It is the residue my merged #120487 did not cover, and extending that fix is mine.

Build profile diff: the job retried the CI logs cluster from 05:27:37 to 05:37:40, every read timed out (LogCluster select failed with exception, ReadTimeout against t6h0zvqlgy...clickhouse-staging.com), then it exited 1. That is #120462, currently erroring on 197 of 379 heads in the last 24 hours. Owners: #121048 and my #118708.

I cannot re-run individual jobs, so I merged master to roll CI again; the head is now 68ef8e32eb92. The second commit is one optimization in the same direction as your Utils.cpp hoist: totalRows and totalBytes authorized the whole chain and then delegated to a target that authorized the rest of it again, so a system.tables scan reading both statistics did O(depth^2) catalog lookups per alias row. The table-level answer composes over the delegation, so the declared target alone is enough. With a 128-deep chain, one such scan went from 1.30 s to 0.22 s, against 0.25 s on master. Behaviour is unchanged in both directions (middle hop of outer -> hop -> base not granted: NULL total_rows and total_bytes; granted: both visible), and the 19 storage_alias stateless tests pass locally. The chain-wide check stays at the per-column sites and in supportsTrivialCountOptimization, where the answer does not compose.

The two random reds should clear on this roll. Build profile diff stays a coin flip until #121048 lands; if it comes back red I will report it here rather than re-rolling repeatedly.

@nauu

nauu commented Sep 23, 2026

Copy link
Copy Markdown
Member

@groeneai please check the pending review comments

@groeneai

Copy link
Copy Markdown
Collaborator Author

I checked both review surfaces on this PR and there is nothing of yours visible to me.

Here: one review thread, the bot's lazy_load_tables comment on src/Interpreters/InterpreterShowCreateQuery.cpp from 2026-09-09, answered the same day and resolved. Two submitted reviews, the bot's and mine, both 2026-09-09. Nothing else through the REST or the GraphQL review surface, re-checked just now.

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 getStructureOfRemoteTable.cpp:75, StorageBuffer.cpp:1555 and DatabaseRemote.cpp:427, and I never replied. My miss, and all three are answered there now. They are one finding, the one this PR fixes: each of those sites calls alias->isTargetTableGranted(..., AccessType::SHOW_COLUMNS, {}), and this PR keeps that function's name while making it walk every hop of the chain, so the three inherit the chain-wide check when this merges, with no change of their own.


/// 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;

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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())

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.

We can avoids checks here for fully granted tables

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.
@groeneai
groeneai requested a review from nauu September 23, 2026 16:12
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Sep 23, 2026
…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);

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.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants