Skip to content

Require SHOW COLUMNS on an Alias target in CREATE TABLE ... AS - #117702

Merged
nauu merged 4 commits into
ClickHouse:masterfrom
groeneai:alias-target-access-create-table-as
Sep 14, 2026
Merged

nauu merged 4 commits into
ClickHouse:masterfrom
groeneai:alias-target-access-create-table-as

Conversation

@groeneai

@groeneai groeneai commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117572
Related: #116793

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 CREATE TABLE dst AS src copying the schema of an ENGINE = Alias table's target for a user who holds SHOW COLUMNS on the alias but no privilege at all on its target. The statement now requires table-level SHOW COLUMNS on the target, the same grant that DESCRIBE of that target already requires.

Description

CREATE TABLE dst AS src checks SHOW COLUMNS on the name it is given, then copies that storage's
metadata columns into the new table. For an ENGINE = Alias row the metadata read returns the
target's columns, so a user holding SHOW COLUMNS on the alias and nothing on the target could
copy the protected table's schema into a table of their own and read it back with DESCRIBE. With an
explicit destination engine that copy is persistent. Both naming the target directly and DESCRIBE
of the alias are denied, so this spelling was the weakest of the three. Rows were never disclosed.

This adds the second-stage check the rest of the tree already uses, in the same shape as
InterpreterDescribeQuery, reusing StorageAlias::isTargetTableGranted. alias is nullptr for
every other storage, so nothing but Alias is affected, and the check is table-level because the
statement publishes every column. A table-level SELECT grant on the target implies
SHOW COLUMNS and keeps working.

Validated with a new stateless test that fails on the unmodified binary and passes with the fix
(50/50 under 8-way self-concurrency), a mutant check proving the table-level scope load-bearing, and
25 existing Alias and CREATE ... AS tests unchanged.

Answering the sibling-engine question from #117572: this seam is now closed at merge,
Distributed, Remote, remote, cluster, Buffer and DatabaseRemote by #117572, at
hasColumnInTable by #117621, at loop by #116873 and #116793, and at CREATE TABLE ... AS here.
The loop structure half listed as a residual on #117572 is already covered by #116793, so it is
not carried here. Gaps I am not carrying here: an Alias whose target is itself an Alias, a
lazy_load_tables proxy hiding the engine from as<StorageAlias> (#117490), and
MySQLHandler::comFieldList, which resolves the metadata after checking only the name it was given.

Measured: user holds SHOW COLUMNS on the alias only, nothing on its target
statement, as that user before after
DESCRIBE nl.al ACCESS_DENIED ACCESS_DENIED
CREATE TABLE own.copy AS nl.al ENGINE = Memory succeeds ACCESS_DENIED
DESCRIBE own.copy after it target's columns no such table
CREATE TABLE own.copy2 AS tgt.hidden ENGINE = Memory (target named directly) ACCESS_DENIED ACCESS_DENIED
same, but with SHOW COLUMNS on the target succeeds succeeds
same, but with only SELECT(one column) on the target succeeds ACCESS_DENIED

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

Version info

  • Merged into: 26.9.1.1474 (included in 26.9 and later)

`InterpreterCreateQuery::getTablePropertiesAndNormalizeCreateQuery` checks
`SHOW COLUMNS` on the database and table name the user typed, then reads that
storage's metadata and copies its columns into the new table. For an
`ENGINE = Alias` row those are two different tables:
`StorageAlias::getInMemoryMetadataPtr` resolves the target with
`tryGetTargetTable` and forwards the target's metadata with no privilege check
of any kind, so only the alias row was ever authorized.

A user holding `SHOW COLUMNS` on the alias and no privilege at all on its
target could therefore run

    CREATE TABLE own.copy AS nl.al ENGINE = Memory;

and read the protected table's schema back with `DESCRIBE own.copy`. With an
explicit destination engine the copy does not inherit `ENGINE = Alias`, so the
disclosure is persistent. Naming the target directly is denied, and so is
`DESCRIBE` of the alias, which is what made this spelling the weakest of the
three. Rows were never disclosed; only the structure crossed.

The metadata forward itself is deliberately left unchecked, because callers
legitimately reach it with a column-scoped entitlement and the `system` tables
need it to degrade gracefully rather than throw. That is why the invariant
lives at each consuming seam with its own `AccessType` and column scope. This
adds the missing seam check, in the same shape and with the same wording as
`InterpreterDescribeQuery`, reusing `StorageAlias::isTargetTableGranted`.

The scope is table level rather than a column name because the statement
publishes every column: a grant covering only some columns, or even an
exhaustive set of column grants, must not admit it. `DESCRIBE` of the target
is denied in exactly those states too, so the new check is neither stricter
nor looser than the gate it mirrors. It also runs before `lockForShare`, so a
denied statement no longer takes a share lock on the target.

One error code changes: for a user without the target privilege,
`CREATE TABLE d AS <alias>` with no explicit engine now reports
`ACCESS_DENIED` instead of `BAD_ARGUMENTS`, because it is refused earlier. An
authorized user still gets `BAD_ARGUMENTS` from the `Alias` creator. No
in-tree test asserts the old code for that spelling under a restricted user.

The new test covers three states of the same statement, differing only in the
grant on the target: none, column scoped, and table level. Arms one and two
fail on the unmodified binary. Changing the table-level scope to a column name
reddens the column-scoped arm alone, so that argument is covered rather than
assumed.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings), adjudicated against my
own cold review of the same diff. All three findings name a real mechanism; none of the three is a
defect of this change, and the two that are real gaps are already listed in the description.

# Sev Finding Verdict Evidence / action
1 ❌ lazy_load_tables wraps an Alias in StorageTableProxy, so as<StorageAlias>() is false and the new check is skipped DISAGREE, mechanism confirmed, wrong layer Confirmed: DatabaseOrdinary::shouldLazyLoad accepts an ENGINE = Alias definition, and StorageTableProxy::getInMemoryMetadataPtr forwards to the nested storage once materialized. Not fixed here. as<>() is a typeid_cast, so the proxy hides the engine from every existing consumer of that metadata forward, including the DESCRIBE gate this check mirrors, so this statement is not weaker than its own control. #117490 stops deferring an Alias at all, so no proxy is ever built around one, which covers this site and the others together; unwrapping here would add a second partial mechanism and leave the rest. Listed in the description. lazy_load_tables defaults to false. Same finding and same answer as #117572 (comment)
2 ❌ The check authorizes one hop, so a1 -> a2 -> target still reaches the final target's columns DISAGREE, mechanism confirmed, wrong layer Confirmed, including reachability: the creator's Alias-target rejection reads the catalog, so a chain is storable by defining the outer alias while its target does not yet exist, which is what 04946_storage_alias_attach_stored_definition.sh does, and a read then traverses it. Not resolved here. isTargetTableGranted is one hop by construction and is the shared predicate of the whole family, so DESCRIBE <outer> admits the same chain with no table function and no CREATE involved. That was measured in both directions on #117572 (comment): every two-hop cell is identical on the base and the fixed binary, two of them through InterpreterDescribeQuery and system.columns. Making the traversal recursive changes that shared predicate at every seam at once, which is a design decision for the engine rather than a hunk of a one-site fix. Listed in the description.
3 ❌ distributed_ddl_entry_format_version 1 or 2 enqueues the raw query before the check, and worker legs run with full access DISAGREE Refuted on a necessary step. That path returns at InterpreterCreateQuery.cpp executeQueryOnCluster before checkAccess(getRequiredAccess()), and getRequiredAccess asks for nothing on the AS source, so the pre-existing checkAccess(SHOW_COLUMNS, as_database_name, create.as_table) that this guard sits beside is bypassed by the same early return. On that path CREATE TABLE d AS <any table> ON CLUSTER c copies any schema and the Alias plays no part, so this is the general distributed-DDL authorization gap (#111561), not something this check creates or widens, and rejecting that legacy path would be a backward-incompatible change needing sign-off. The default is 5, above NORMALIZE_CREATE_ON_INITIATOR_VERSION, where the initiator materializes AS as the real user and the new check does apply.

My own cold review found one further seam of the same class, MySQLHandler::comFieldList, which
mirrors the SQL DESCRIBE check on the name it is given and then reads the metadata with no
alias-target guard. It is not fixed here either, and it is now named in the description rather than
left implied by an enumeration that read as complete. Two test nits (the denied arms assert the
error and not the absence of the destination table, and the fixture uses a multi-statement
--query) were left as they are, matching the existing sibling tests.

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

Session id: cron:clickhouse-review-slot-9:20260902-131300

@clickhouse-gh clickhouse-gh Bot closed this Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization and no timing. As a user holding SHOW COLUMNS on nl.al (ENGINE = Alias('tgt', 'hidden')) and nothing on tgt: CREATE TABLE own.copy AS nl.al ENGINE = Memory succeeds and DESCRIBE own.copy prints the target's columns.
b Root cause explained? InterpreterCreateQuery.cpp:876 checks SHOW COLUMNS on the database and table name the user typed, then :888 reads as_storage->getInMemoryMetadataPtr, which for an Alias returns the target's metadata (StorageAlias.h:124-131 resolves via tryGetTargetTable with no check of any kind). Those are two different tables and only the first was authorized, so :889 copies the target's columns into the new table.
c Fix matches root cause? Yes: the guard goes exactly at the seam between the two, between the getTable and the metadata read. It is the same guard the other callers of that unchecked forward already use (InterpreterDescribeQuery.cpp:255-257, InterpreterShowCreateQuery.cpp:168-174), with the same wording. No widened bound, no tag, no symptom masked.
d Test intent preserved / new tests added? New stateless test 05104_create_table_as_alias_target_access.sh, three arms differing only in the target-side grant. No existing test weakened, removed or retagged; 25 existing Alias and CREATE ... AS tests still pass.
e Both directions demonstrated? Yes, on Build-ID-asserted servers. Without the fix, arms 1 and 2 lose their ACCESS_DENIED, the statement succeeds and DESCRIBE prints the target's columns. With the fix, ACCESS_DENIED and system.tables shows no destination row, so nothing partial is left behind. Plus a mutant check (table-level {} changed to a column name reddens arm 2 only) and a guard-deleted negative control (arms 1 and 2 redden again).
f Fix is general across code paths? Fixed at the seam, not at the symptom. The shared root StorageAlias::getInMemoryMetadataPtr is deliberately not changed: in-tree references require that forward to keep working for a column-scoped entitlement (03636_storage_alias_metadata_access_rights.reference:30, 04945_..._access.reference:20) and six StorageSystem* sites require graceful degradation rather than an exception, which is why this invariant lives at per-seam checks with a per-seam AccessType and column scope. Sibling seams: #117572, #117621, #116873, #116793.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured as a matrix: 7 grant states on the target, each paired with a DESCRIBE <target> consistency control, and the two agree in all 7 (including the subtle state where column grants cover every column, where DESCRIBE is also denied); 3 alias spellings (Alias('db','tbl'), Alias('db.tbl'), Alias('tbl')); 7 destination shapes (Memory, MergeTree, CREATE TEMPORARY TABLE, CREATE OR REPLACE, IF NOT EXISTS, CLONE AS, no explicit engine); a dangling alias; and a non-Alias source, which is untouched.
h Backward compatible? (maintainer-approved exception only) One deliberate behaviour change: a user with only SHOW COLUMNS on the alias can no longer copy its target's schema. Defensible because the direct spelling CREATE TABLE x ENGINE = Alias(tgt) already requires SHOW COLUMNS on tgt (StorageAlias.cpp:551-552, 03636_storage_alias_metadata_access_rights.reference:1-3), so this removes an inconsistency rather than adding a restriction. No setting, no default, no serialization format, so no SettingsChangesHistory.cpp entry is owed.
i Invariants and contracts preserved? The guard is inserted before lockForShare, so it adds no lock and cannot reorder or widen any lock's scope; on the deny path nothing is constructed and no share lock is taken on the target, where previously one was. isTargetTableGranted is const, non-throwing and name-based, so a dangling target cannot turn the guard into an exception. properties is untouched on the throw path, and the pre-existing name check still runs first, so the new throw reveals nothing a caller could not already learn.

Session id: cron:clickhouse-impl-slot-7:20260902-114100

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ccc09f0]

Summary: ✅


AI Review

Summary

This PR closes the eager, one-hop Alias case in CREATE TABLE ... AS, but the promised contract is still violated in two supported states: lazily loaded aliases and stored Alias -> Alias chains. Because a user can still copy protected target schema through those paths without SHOW COLUMNS on the final target, the fix is incomplete and I would not merge it as a Bug Fix yet.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:978, src/Databases/DatabaseOrdinary.cpp:449] [dismissed by author -- https://github.com/Require SHOW COLUMNS on an Alias target in CREATE TABLE ... AS #117702#discussion_r3915316685] The new guard only fires when getTable returns a live StorageAlias. In a database with lazy_load_tables = 1, DatabaseOrdinary::shouldLazyLoad still wraps ENGINE = Alias tables in StorageTableProxy, so as<StorageAlias>() is false here and getInMemoryMetadataPtr later serves the target columns through the proxy. That means CREATE TABLE dst AS alias ENGINE = Memory can still copy the protected schema for a user who has SHOW COLUMNS only on the alias, which breaks the PR's stated contract on a supported setting.
    Suggested fix: either stop lazy-loading Alias tables in DatabaseOrdinary::shouldLazyLoad, or make this and the sibling alias-target checks proxy-transparent before any metadata is derived.
  • [src/Interpreters/InterpreterCreateQuery.cpp:978, src/Storages/StorageAlias.cpp:64, src/Storages/StorageAlias.h:124, tests/queries/0_stateless/04946_storage_alias_attach_stored_definition.sh:31] [dismissed by author -- https://github.com/Require SHOW COLUMNS on an Alias target in CREATE TABLE ... AS #117702#discussion_r3954240986] isTargetTableGranted authorizes only the first hop, but StorageAlias::getInMemoryMetadataPtr keeps resolving through nested aliases. A stored outer_alias -> inner_alias -> hidden chain is already accepted and reloadable today, so a user granted SHOW COLUMNS on the two aliases but nothing on hidden still passes this check and copies hidden's schema with CREATE TABLE ... AS outer_alias.
    Suggested fix: authorize the final non-Alias target (cycle-safe) before copying columns, or explicitly reject persisted Alias -> Alias definitions on load if that state is no longer meant to be supported.
Tests
  • ⚠️ The added regression in 03636_storage_alias_metadata_access_rights covers only the eager, one-hop path. It would stay green while both blockers above remain, so please add focused negative coverage for a lazy-loaded Alias and for the stored Alias -> Alias chain case (or remove/update 04946 if chained aliases become unsupported instead).
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Make the target-SHOW COLUMNS check survive StorageTableProxy when lazy_load_tables = 1.
  2. Make the guard authorize the final metadata-producing target for persisted alias chains, or stop those chains from loading.
  3. Add regression coverage for the supported states that remain.

LLVM Coverage Report

Measured on commit ccc09f0.

Metric Baseline Current Δ
Lines 89.10% 89.00% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.40% -0.10%

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

Full report · Diff report

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @pufit @davenger, could you review this? CREATE TABLE dst AS src checks SHOW COLUMNS on the name it is given, then reads that storage's metadata, which for an ENGINE = Alias row returns the target's columns. A user holding the grant on the alias and nothing on the target could therefore copy the protected schema into a table of their own, so this adds the missing target check at that seam, table level and in the same shape as InterpreterDescribeQuery.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@PedroTadim PedroTadim self-assigned this Sep 2, 2026

/// An `Alias` reports its target's metadata, so copying that metadata requires the privilege on the
/// target that describing the target requires.
if (const auto * alias = as_storage->as<StorageAlias>();

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.

This only catches a live StorageAlias. In a database with lazy_load_tables = 1, DatabaseOrdinary::shouldLazyLoad still wraps ENGINE = Alias tables in StorageTableProxy, so as<StorageAlias>() is false here while the proxy still serves the columns cached from the stored CREATE query. Because Alias persists its target columns into that stored definition, a user with SHOW COLUMNS on the alias but nothing on its target can still run CREATE TABLE dst AS alias ENGINE = Memory and copy the protected schema under that setting.

Please either include the #117490 lazy-load exclusion in this PR or make this check identify Alias through the stored definition / proxy before trusting getInMemoryMetadataPtr.

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.

Confirmed by measurement, and it is not specific to this statement.

On this PR's head, with CREATE DATABASE ... ENGINE = Atomic SETTINGS lazy_load_tables = 1 and the alias loaded from metadata after a restart (system.tables.engine reads TableProxy for the untouched alias, so the proxy is armed), for a user holding SHOW COLUMNS on the alias only and nothing on its target:

  • eager alias, same grants (control): DESCRIBE <alias> and CREATE TABLE dst AS <alias> ENGINE = Memory are both ACCESS_DENIED.
  • lazily loaded alias: DESCRIBE <alias> returns the target's two columns; CREATE TABLE dst AS <alias> ENGINE = Memory succeeds and DESCRIBE dst returns them; SHOW CREATE TABLE <alias> returns the stored definition including both columns; SELECT name, type FROM system.columns WHERE database = ... returns both. SELECT count() FROM <alias> stays ACCESS_DENIED, so rows are not disclosed.

So the proxy defeats the pre-existing DESCRIBE check this one mirrors (InterpreterDescribeQuery.cpp:255), plus InterpreterShowCreateQuery.cpp:171 and StorageSystemColumns.cpp:151. as<StorageAlias> is an exact typeid_cast and it is how all 14 alias-target privilege checks in src/ identify an alias, so unwrapping the proxy at this one site would close 1 of 14 and would not reduce the disclosure: the same user in the same database keeps reading the same schema out of three other statements.

#117490 fixes it where the proxy is created: DatabaseOrdinary::shouldLazyLoad returns false for ENGINE = Alias, so no proxy ever wraps one and all 14 sites see the real storage. Copying that hunk here would put the same change to shouldLazyLoad in two of my open PRs. Identifying the alias from the stored definition at this site instead is possible, but it reimplements per site what #117490 removes at the source and leaves the other statements disclosing. This gap is listed in this PR's description with the link, and if #117490 is not accepted I will carry a proxy-transparent fix for the whole family rather than for this site alone.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7a8fe66

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
Parser memory check / Resolve master binary master-side, not this diff: praktika's static S3 prefix gained an unconditional workflow-name segment in #110081, so this job's hand-spelled baseline key REFs/master/<sha>/build_arm_release/clickhouse-examples 403s on every tracked commit and the step errors No master clickhouse-examples artifact was found. 163 distinct pull requests carry it since 2026-09-02 10:14:18Z; the check has no true-master runs at all, so master cannot show it #117701 (mine, merged 2026-09-02T16:49:23Z). This tree predates the merge, so the red is expected here; the master merge that picks it up is deferred because it cannot turn the head green while the row below is open
LLVM Coverage / Generate LLVM Coverage Diff Report, then Print Uncovered Code as its cascade master-side, not this diff: the same #110081 prefix change orphaned the hand-spelled coverage baseline key, so the 100-commit baseline walk finds nothing and the uncovered-code step never runs. 67 distinct pull requests carry it since 2026-09-02 13:07:52Z, and 0 of 184 true-master runs of this check fail #117718 (external, open)

Fix presence for #117701 was probed at the tree that actually ran rather than inferred from
timing: pre-fix 15ab60d3151c = 0, at the fix d4f4f2a50e0f = 1, this head 7a8fe6630565 = 0
(ahead_by 1, behind_by 77).

Session id: cron:our-pr-ci-monitor:20260902-200000

@PedroTadim PedroTadim assigned nauu and unassigned PedroTadim Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 4, 2026
/// An `Alias` reports its target's metadata, so copying that metadata requires the privilege on the
/// target that describing the target requires.
if (const auto * alias = as_storage->as<StorageAlias>();
alias && !alias->isTargetTableGranted(getContext(), AccessType::SHOW_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.

isTargetTableGranted only authorizes one hop, but StorageAlias::getInMemoryMetadataPtr keeps resolving through nested aliases. A stored chain is a supported state today (04946_storage_alias_attach_stored_definition.sh): outer_alias -> inner_alias -> hidden loads successfully after ATTACH. For a user granted SHOW COLUMNS on outer_alias and inner_alias but nothing on hidden, this check passes and properties.columns = as_storage_metadata->getColumns() still copies hidden's schema into the new table.

The seam here is "authorize the table whose metadata we are about to publish", so the guard needs to resolve through alias chains (cycle-safe) or otherwise authorize the final non-Alias target before copying columns.

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.

Confirmed, and measured to the point where the measurement decides where the fix belongs.

Head 8882fecd, debug build 0fa1c881, server config carrying enable_access_control_improvements.xml. Chain ch.al_outer -> ch.al_inner -> tgt.hidden, built the way 04946_storage_alias_attach_stored_definition.sh builds it (the outer alias created while the inner name is still absent, the only order the constructor's Alias -> Alias rejection cannot see). The user holds SHOW TABLES, SHOW COLUMNS on the two alias databases and nothing at all on tgt:

statement, as that user result
DESCRIBE nl.al (one hop) ACCESS_DENIED
CREATE TABLE own.c1 AS nl.al ENGINE = Memory (one hop, this PR) ACCESS_DENIED
DESCRIBE ch.al_inner (one hop) ACCESS_DENIED
CREATE TABLE own.c2 AS ch.al_outer ENGINE = Memory (two hops) succeeds, and DESCRIBE own.c2 returns both columns
DESCRIBE ch.al_outer (two hops) returns both columns
SELECT name, type FROM system.columns WHERE database = 'ch' AND table = 'al_outer' returns both columns
SHOW CREATE TABLE ch.al_outer the alias definition only, no columns
SELECT count() FROM ch.al_outer ACCESS_DENIED

The first three rows are the armed-binary controls, and a user who does hold SHOW COLUMNS on tgt.hidden is denied nothing in any arm, so no cell is blind. Rows stay undisclosed at both depths.

Rows 5 and 6 are why I am not walking the chain in this hunk. They are InterpreterDescribeQuery.cpp:255 and StorageSystemColumns.cpp:215, which this diff does not touch, and they hand that user the same two columns with a shorter statement. Resolving the chain here would take nothing away from that user; it would only make CREATE TABLE ... AS stricter than a DESCRIBE of the same object, which is the asymmetry this family of changes exists to remove. isTargetTableGranted authorizes the name written in the alias's own definition, and that is the contract all 19 of its call sites are written against.

So I would rather close it once for the whole family than here, and that needs a design call I would rather not guess:

  1. Resolve to the final non-Alias target inside isTargetTableGranted, cycle-safe, so every site moves together. Constraints I measured: 8 of the 19 call sites are system.* row filters that skip a row rather than throw, so the walk has to stay non-throwing, and cycles are still constructible until Reject a RENAME DATABASE that would make an Alias table cyclic #117253 lands.
  2. Keep the check one hop and stop the chained state from existing, in the same spirit as Reject a RENAME DATABASE that would make an Alias table cyclic #117253. The constructor already rejects Alias -> Alias when the target exists; the remaining hole is the outer-created-first order, and rejecting it during metadata load would make stored definitions that load today fail to load.

I will take 1 unless you prefer 2. The gap is listed as a residual in the description.

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.

Opened #118967 for this: shape 1, the chain walk with a visited set, since the chained state has to stay loadable. It keeps the one-hop check for the two surfaces that render only the alias's own definition.

The three arms covering `CREATE TABLE dst AS <alias>` were in a dedicated
05104_create_table_as_alias_target_access.{sh,reference}.
03636_storage_alias_metadata_access_rights already builds the target table, an
`Alias` over it and a privilege ladder, so the arms now sit at the end of that
test and reuse its fixture, and the dedicated file is removed.

What they assert is unchanged: no privilege on the target and a column-scoped
`SELECT` on the target are both denied, a table-level `SHOW COLUMNS` on the
target copies the schema.

Verified against a server carrying config.d/enable_access_control_improvements.xml:
the test passes on this build, and with the guard deleted from
getTablePropertiesAndNormalizeCreateQuery both denial arms lose their
ACCESS_DENIED line while every other line of the test is unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Progress: the change is complete and was green. CREATE TABLE dst AS <alias> now requires table-level SHOW COLUMNS on the alias target before that metadata is copied. CI on the previous head 8882fecd7fbd finished 156 pass / 18 skipped / 0 fail with Mergeable Check green; the test move below was just pushed, so CI is running again on 63e2502. Both automated-review rounds are answered in-thread with measurements: the lazy_load_tables StorageTableProxy gap (real, but it defeats the pre-existing DESCRIBE check identically, so #117490 closes it at the root for every site instead of one), and the multi-hop Alias to Alias chain (real, but DESCRIBE and system.columns hand the same user the same columns with a shorter statement, so it is being fixed for the whole family rather than one hop at a time). Nothing else is outstanding on my side.

Test move: done in 63e2502 (63e2502). The three arms now sit at the end of 03636_storage_alias_metadata_access_rights and reuse its fixture (the target table, the Alias over it, the privilege ladder), so the dedicated 05104_create_table_as_alias_target_access.{sh,reference} is gone. Verified against a server carrying config.d/enable_access_control_improvements.xml: 10/10 green at -j 4, and with the guard deleted both denial arms lose their ACCESS_DENIED line while every other line of the test is unchanged.

One measurement from re-checking the diff, which this PR does not fix: a TimeSeries destination skips the AS-source authorization completely.

-- as a user holding nothing at all on `tgt`, plus TABLE ENGINE grants and
-- allow_experimental_time_series_table = 1
CREATE TABLE own.copy AS tgt.hidden_ts ENGINE = TimeSeries;   -- succeeds
DESCRIBE own.copy;   -- returns the source's 7 columns

normalizeTimeSeriesDefinition applies the AS clause from the source's stored CREATE query and materializes columns_list before the AS branch runs, and that branch is where both the pre-existing SHOW COLUMNS check on the named source and this PR's alias-target guard live. It is not Alias-specific: naming the target directly bypasses the pre-existing check in exactly the same way, and the controls separate the two (the same two statements with ENGINE = Memory are denied, asking for SHOW COLUMNS ON tgt.hidden_ts and reporting Not enough privileges to describe metadata exposed by nl.al respectively). Since the fix belongs in the TimeSeries normalization path rather than in this hunk, I am carrying it separately, but say so if you would rather have it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to the TimeSeries measurement in my previous comment: it is already fixed on master, so I am not carrying it separately after all. That probe ran on this branch (63e2502), whose base predates #118517 (merged 2026-09-08); commit 469fab8127140 added checkAccess(AccessType::SHOW_COLUMNS, ...) to the AS-source read in normalizeTimeSeriesDefinition, which is exactly the check I reported as missing. Re-measured on master 0d04f2bc27456: CREATE TABLE own.copy AS tgt.hidden_ts ENGINE = TimeSeries is denied with necessary to have the grant SHOW COLUMNS ON tgt.hidden_ts, and the Alias flavour stops even earlier with Cannot CREATE a TimeSeries table AS nl.al because it is not a TimeSeries table, which holding that grant does not change.

This PR's own guard is unaffected by that: on the same master binary CREATE TABLE own.copy AS nl.al_plain ENGINE = Memory still succeeds and DESCRIBE on the copy returns the target's columns.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 63e2502

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
Stateless tests (arm_binary, parallel) / 04365_cancel_insert_when_client_dies_distributed flaky, not this diff: only the third line of the reference flipped (1 to 0, the "was anything cancelled" guard) while both 500000-row data lines were correct, and the runner's own diagnosis re-ran it with the same randomized settings and it passed 2/2. This diff adds a SHOW COLUMNS check on an Alias target in CREATE TABLE ... AS and cannot reach the distributed insert-cancellation path. Breadth over 30 days: 7 rows / 5 pull requests / 3 true-master a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Mergeable Check, PR derivative, no independent failure: both aggregators report exactly the row above (Mergeable Check reads Failed: Stateless tests (arm_binary, parallel)) a fix task is moved to pending, the same one as the row above (fixing-PR link to follow on this PR)

My own merged #119778 ("Fix flaky 04365_cancel_insert_when_client_dies_distributed under host
load", merged 2026-09-13T15:47:58Z) is deliberately NOT linked as the owner. It is present in the
tree this job actually built, measured from the job's own execution trace rather than from
ancestry: the trace runs its post-fix code path (CLIENT_PID_FILE, printf %s <pid>, an O(1)
grep -Faq query_id=... /proc/$CANDIDATE/cmdline), not the machine-wide /proc/*/cmdline sweep it
replaced. The test failed with that fix in place, so it does not resolve this occurrence, and the
residual is recorded on the fix task instead.

CH Inc sync is green on this head, so no exempt row is owed here.

Session id: cron:our-pr-ci-monitor:20260914-073158

@nauu

nauu commented Sep 14, 2026

Copy link
Copy Markdown
Member

LGTM

@nauu
nauu enabled auto-merge September 14, 2026 08:35
@nauu

nauu commented Sep 14, 2026

Copy link
Copy Markdown
Member

@groeneai make the PR green

No content change. The only failure on 63e2502 was 04365_cancel_insert_when_client_dies_distributed in Stateless tests (arm_binary, parallel), where the runner's own re-run of the failing test passed 2/2 and reported the failure as not reproducible. That test does not touch access checks, so it cannot be reached by this diff.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI is running again on ccc09f08ac34b.

The single red on 63e2502 was 04365_cancel_insert_when_client_dies_distributed in Stateless tests (arm_binary, parallel); Mergeable Check and PR only rolled that one up. It is a transient flake and not reachable from this diff: both 500000-row data lines matched and only the "was anything cancelled" guard line flipped from 1 to 0, the runner's own diagnosis re-ran the failing test twice under the same randomized settings and passed both times ("the failure is not reproducible"), and CIDB has 0 failures of it on master over the last 14 days. This PR adds a SHOW COLUMNS check in InterpreterCreateQuery, which cannot reach a distributed insert cancellation.

ccc09f08ac34b is an empty commit because a push is the only re-trigger I have: I hold triage rights, so rerun-failed-jobs answers 403 Must have admin rights to Repository for me. If it comes back red on that same test, re-running just that one job from the Actions page is quicker than another push.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stateless tests (arm_binary, parallel) / 04365_cancel_insert_when_client_dies_distributed guard flip promised in the ledger above: #119948.

It reverts my #119778, which regressed that guard on this lane: 0 failures in 10251 runs of the previous test-file revision against 2 in 280 after it merged.

@nauu
nauu added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit d904941 Sep 14, 2026
177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
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-human PR origin: human review feedback 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.

5 participants