Skip to content

Infer an omitted Buffer structure under the user's context - #113372

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-omitted-columns-access
Aug 7, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-buffer-omitted-columns-access

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

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 a case where CREATE TABLE ... ENGINE = Buffer(...) without a column list could reveal the structure of a destination table the creating user is not allowed to see. For a CREATE the local server executes itself, the structure is now inferred under the user's own context, so SHOW COLUMNS on the destination is required, as it already is for Merge and Remote. A CREATE replayed from the DDL queue (ON CLUSTER, or inside a Replicated database) is not covered.

Description

Related: #113220, the Distributed sibling. No related open issue; found while sweeping the engines that infer an omitted structure from a local table.

What breaks. A user with CREATE TABLE on its own database can learn the columns and types of any local table by creating a columns-less Buffer over it and describing its own table. Buffer declares no source_access_type, so TABLE ENGINE ON Buffer is auto-granted on a default server and is the only other privilege needed. The inferred columns are persisted, so it survives a restart. Reads and writes were already authorized, so this is disclosure-only.

Root cause. The constructor infers the structure from the destination's in-memory metadata (StorageBuffer.cpp:180-185), and neither DatabaseCatalog::getTable nor getInMemoryMetadataPtr checks access. It is handed args.getContext(), which StorageFactory::get asserts is the global context, so there is no user to check. Master's own 03631_buffer_access_check already records the bypass.

The change. The inference moves into registerStorageBuffer, where the user's context exists, with an unconditional SHOW_COLUMNS check -- the shape Merge (StorageMerge.cpp:213) and Remote (StorageDistributed.cpp:2592) already have. It is skipped for already-validated metadata (isLoadingFromExistingMetadata || attach_short_syntax), which has no user and stores no column list; the constructor keeps its branch for that path only. SHOW_COLUMNS is implied by SELECT, so readers are unaffected, and explicit-column creates are unchanged.

Scope. A queue-replayed CREATE reaches the engine with no user, so the check is a no-op there. ON CLUSTER sets one only with distributed_ddl_use_initial_user_and_roles on and distributed_ddl_entry_format_version at least 8 (default 5); a Replicated database records no initiator. Both want #113073.

Validation. New 04729_buffer_infer_columns_access covers the denial, inference after the grant, explicit columns, temporary tables and re-attach; it fails on master and 50 randomized runs pass here. 03631 gains a SHOW COLUMNS grant so its create still reaches its own unchanged assertions.

Version info

  • Backported to: 26.7.4.6, 26.6.3.15, 26.5.7.17, 26.3.18.9, 25.8.30.6

StorageBuffer's constructor infers an omitted structure from the destination
table's in-memory metadata (StorageBuffer.cpp:180-185). Neither
DatabaseCatalog::getTableImpl nor IStorage::getInMemoryMetadataPtr performs an
access check, and registerStorageBuffer hands the constructor
args.getContext(), which StorageFactory::get asserts is the global context
(StorageFactory.cpp:236). There is no user on that path, so nothing gates the
read: a user holding only CREATE TABLE on its own database could learn the
column names and types of any local table by creating a columns-less Buffer
over it and describing its own table. The inferred columns are written back
into the creator's own persisted metadata by
addColumnsDescriptionToCreateQueryIfNecessary
(InterpreterCreateQuery.cpp:2283), so the disclosure survives a restart. Reads
and writes were already authorized against the destination under the query
context (StorageBuffer.cpp:337, :778), so this is disclosure-only.

The bypass is recorded in master: 03631_buffer_access_check creates a
columns-less Buffer over a table its user has no rights on, and its reference
shows that CREATE succeeding.

Move the inference into registerStorageBuffer, where the user's context
exists, and check SHOW_COLUMNS on the destination there. This is the shape
Merge (StorageMerge.cpp:213, under args.getLocalContext()) and Remote
(StorageDistributed.cpp:2592) already have. The check is unconditional: Merge's
SHOW_TABLES pre-filter has no analogue here because a Buffer names exactly one
destination.

The predicate skips loading of already-validated metadata
(isLoadingFromExistingMetadata || attach_short_syntax), which is the guard
Remote uses. DatabaseOnDisk deliberately stores no column list for a
schema-inferring engine (DatabaseOnDisk.cpp:141-153) and sets
attach_short_syntax for every such load (:90-102); without the guard, loading
such a definition would try to authorize it under a context that has no user,
which is the regression 04601_remote_storage_engine_short_attach exists for on
the Remote side. It also skips a destination-less Buffer, keeping the existing
UNKNOWN_TABLE failure for that form byte-identical rather than turning it into
ACCESS_DENIED. The constructor keeps its inference branch, which now serves
only the loading path.

checkAccess runs before getTable, so a user without SHOW_COLUMNS on a missing
destination now gets ACCESS_DENIED instead of UNKNOWN_TABLE. That is the
standard ordering and is desirable: it avoids a table-existence oracle.

SHOW_COLUMNS is the narrowest privilege for the disclosure, and it is implied
by SELECT (ContextAccess.cpp:152-162), so no user who can already read the
destination is affected. Creates that carry an explicit column list are
unchanged, so this does not widen into Remote's SELECT+INSERT requirement.

03631_buffer_access_check gains a SHOW COLUMNS grant so its columns-less create
still succeeds and the test keeps reaching the read and write assertions it was
written for. Its reference is unchanged and no assertion was weakened.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds: own cold review + Gate B) -- click to expand

An independent reviewer read the resulting code cold, without the author's evidence, and a
second model (codex) then re-reviewed the whole change against the frozen PR contract.
Findings, verdicts and evidence below.

❌ Blockers

None.

⚠️ Major

1. The changelog over-claimed the fix's coverage. AGREE, fixed in the PR body before
publication.

The first draft said the disclosure is fixed, with no qualification. It is not fixed for a
CREATE replayed from the DDL queue: registerStorageBuffer then runs on
DDLTaskBase::makeQueryContext's context (DDLTask.cpp:292-331), which calls setUser only
when the server setting distributed_ddl_use_initial_user_and_roles is on (default false,
ServerSettings.cpp:1106) and the entry carries initiator_user, which
executeDDLQueryOnCluster.cpp:195-199 writes behind that same setting and which is serialized
only from DDL entry format version 8 (DDLTask.h:79) while distributed_ddl_entry_format_version
defaults to 5. DatabaseReplicated::tryEnqueueReplicatedDDL (DatabaseReplicated.cpp:1474-1480)
records a host initiator but never initiator_user, so no setting closes that path. A userless
context makes full_access = !user_id true (Context.cpp:2285-2288) and the new checkAccess
returns early.

The columns-less form genuinely reaches the queue: the initiator normalizes before dispatch
(InterpreterCreateQuery.cpp:1867, then :1925/:1943) and leaves properties.columns empty
for a schema-inferring engine, so no column list is serialized (ASTCreateQuery.h:83-87), and
getRequiredAccess asks only for CREATE_TABLE and TABLE_ENGINE, so the initiator does not
pre-check either.

The changelog entry and a Scope paragraph now state this explicitly, matching the wording
#113220 settled on.

💡 Nits (noted, not blocking)

2. Test case 3 does not exercise the attach_short_syntax half of the guard. AGREE.
addColumnsDescriptionToCreateQueryIfNecessary (InterpreterCreateQuery.cpp:2283) persists the
inferred columns, so a short ATTACH re-enters with a non-empty column list and
columns.empty() short-circuits before either guard term. Independently confirmed by the
author's mutant-A run, which is why the case asserts a lifecycle property rather than the guard.
Kept as regression coverage against a future re-attach break; the guard itself is pinned by a
manual probe on a stored definition that carries no column list.

3. No shipped arm covers the isLoadingFromExistingMetadata half. AGREE, and deliberately
not added. Reaching it needs a stored definition with no column list
(DatabaseOnDisk.cpp:135-146), i.e. writing table metadata out of band, which is prohibited in a
stateless test and belongs in an integration test.

Verified, no action

  • Carrier enumeration is closed by construction: exactly one StorageBuffer constructor call
    site, and all five StorageFactory::get entry points plus all five createTableFromAST
    callers were checked (the latter all default set_attach_flag true, so all are excluded by the
    guard). SYSTEM RESTART REPLICA cannot reach a Buffer at all.
  • Passing the user's context into the destination's getInMemoryMetadataPtr is strictly more
    restrictive for all five overrides, never less.
  • SHOW_COLUMNS is implied by any column grant (ContextAccess.cpp:152-162), so no reader loses
    access; a test case pins this.
  • The temporary-table arm is not confounded by the CREATE ARBITRARY TEMPORARY TABLE ladder:
    GRANT CREATE TABLE implies it (ContextAccess.cpp:125-133), so the arm reaches the engine and
    the denial it observes is the SHOW_COLUMNS one.
  • Test number 04729 is free on master, and check_gaps_in_tests_numbers (extracted from
    ci/jobs/check_style.py and executed) reports an identical gap set for master and for the
    merged tree.
  • Gate B round 1: 0 findings, engine=codex, reviewed the full change against the frozen
    contract. Confirmed cold (no prior-review state injected), so its agreement is independent.

Rounds: 1 own cold review + 1 Gate B. No fix round was needed: the only substantive finding was
in the PR contract, not the code.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test 04729_buffer_infer_columns_access. No randomization, no cluster, no timing dependency. By hand: a user granted nothing on the destination is denied DESCRIBE db.test_table with Code: 497 ACCESS_DENIED, then creates a columns-less Buffer over it and reads s String, secret_column UInt64, another_secret Decimal(18, 4) out of system.columns.
b Root cause explained? Yes. StorageBuffer's constructor infers an omitted structure from the destination's metadata (StorageBuffer.cpp:180-185); neither DatabaseCatalog::getTableImpl nor IStorage::getInMemoryMetadataPtr checks access, and registerStorageBuffer hands the constructor args.getContext(), which StorageFactory::get asserts is the global context (StorageFactory.cpp:236). There is no user on that path, so this is a missing check, not a mis-scoped one. The inferred columns are then persisted into the creator's own metadata (InterpreterCreateQuery.cpp:2283), so the disclosure survives a restart.
c Fix matches root cause? Yes. The inference moves to registerStorageBuffer, the one hop where the user's context exists, with an unconditional SHOW_COLUMNS check on the destination. This is the shape Merge (StorageMerge.cpp:213) and Remote (StorageDistributed.cpp:2592) already have. No guard at the disclosure site.
d Test intent preserved / new tests added? Yes. New 04729_buffer_infer_columns_access with 6 cases. 03631_buffer_access_check gains only a GRANT SHOW COLUMNS so its create still reaches the read and write assertions it was written for; its .reference is unchanged and no assertion was weakened or removed.
e Both directions demonstrated? Yes. 04729 FAILS on pristine 8c925c5b (cases 1 and 5 print 0, i.e. both creates succeeded) and passes with the fix. Independently, the UNMODIFIED 03631 passes on pristine and FAILS with the fix (ACCESS_DENIED ... SHOW COLUMNS), which proves the fix is not inert. Both arms on Build-ID-verified binaries (2c245099 vs 4fe9dc27), asserted against SELECT buildId().
f Fix is general across code paths? Yes. StorageBuffer has exactly one constructor call site and one inference site, so the carrier set is closed by construction. All four StorageFactory::get entries that can carry empty columns are dispositioned: ordinary CREATE/RESTORE fixed, both temporary-table paths fixed by the same creator code (case 5 covers one), metadata load deliberately excluded by the guard. SYSTEM RESTART REPLICA cannot reach a Buffer (doRestartReplica rejects a non-ReplicatedMergeTree before StorageFactory::get; measured: Code: 36 BAD_ARGUMENTS). Re-derived the 14-file supports_schema_inference sweep: Distributed is #113220, Merge is already correct locally, Alias is not a carrier, the other ten infer from external sources.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the parameter matrix: omitted vs explicit columns, temporary vs persistent, SHOW COLUMNS vs SELECT vs no grant, empty destination table name, nonexistent destination, and the short-ATTACH form. Type wrappers are not applicable (a context-plumbing fix, type-agnostic), but the inferred set deliberately includes a Decimal(18, 4) so a silently degraded inference would show in case 2 - the optimization-preserved half of the test.
h Backward compatible? (maintainer-approved exception only) A previously accepted CREATE now fails for a user lacking SHOW_COLUMNS on the destination; that is the fix itself. It is the narrowest privilege for the disclosure and is implied by SELECT (asserted by case 6), so no user who can read the destination is affected, and explicit-column creates are unchanged (case 4). No setting added or re-defaulted, so no SettingsChangesHistory.cpp entry. No serialization or format change.
i Invariants and contracts preserved? Yes. The check and the inference both run before the storage object exists, so a denial fails the CREATE with nothing to unwind. checkAccess precedes getTable, so a user without SHOW_COLUMNS now sees ACCESS_DENIED rather than UNKNOWN_TABLE for a missing destination, which is the standard ordering and avoids a table-existence oracle. For a full-access user both Buffer(db, '', ...) and a nonexistent destination keep their pre-existing Code: 60 UNKNOWN_TABLE code and message text. StorageMetadataHandle::operator-> is deleted on rvalues, so the handle is bound to a named local before use, as every other call site does.

Session id: cron:clickhouse-impl-slot-6:20260804-151700

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @pufit @azat, could you review this? A columns-less CREATE TABLE ... ENGINE = Buffer(...) inferred the destination's structure inside the storage constructor, which only ever holds the global context, so the read was never authorized; the inference moves to registerStorageBuffer under the user's context with a SHOW_COLUMNS check, matching Merge and Remote.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4425cff]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: ColumnBLOB should be converted to a regular column before usage (STID: 3059-3663) FAIL cidb, issue ISSUE EXISTS
Stress test (arm_tsan) FAIL
Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-457d) FAIL cidb IGNORED

AI Review

Summary

This PR moves omitted-schema inference for Buffer out of the StorageBuffer constructor path that only has the long-lived/global context and into registerStorageBuffer, where local CREATE-time validation can require SHOW_COLUMNS on the destination before persisting inferred columns. I did not find a remaining correctness or access-control issue in the current diff, and the tests match the stated scope, including the explicit out-of-scope DDL-queue / replicated-database path.

Final Verdict

✅ No review findings in the current patch.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 17/18 (94.44%) · Uncovered code

Full report · Diff report

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

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4425cff

Every failure below has an owner: a fixing PR (ours 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 (amd_debug) / ColumnBLOB should be converted to a regular column before usage, STID 3059-3663 pre-existing trunk bug: a local shard plan marshalled its blocks in a distributed query #111997 (ours, merged 2026-08-04) - this build predates the fix
Stress test (arm_tsan) / Shard number is greater than shard count, STID 5066-457d pre-existing trunk bug in prepareClusterForParallelReplicas #111973 (external, open)
Build (arm_release) / Post Hooks CI infra: the build_profile_hook telemetry INSERT fails with a LogCluster HTTP 500; non-gating hook, the build itself concluded success a fix task is created (investigating at full effort - fixing-PR link to follow here)
Bugfix validation (functional tests, aarch64 / amd64) / 03631_buffer_access_check not a failure: both jobs concluded success; these FAIL rows are the expected pre-fix arm that validates this PR's regression test -

Session id: cron:our-pr-ci-monitor:20260805-033000

@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 7, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 0e1f3dd Aug 7, 2026
177 of 180 checks passed
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 7, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 7, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
PedroTadim added a commit that referenced this pull request Aug 7, 2026
The backported code calls `isLoadingFromExistingMetadata`, which does not
exist on this branch, so add it next to the enum it tests. Nothing else
here calls it yet.

Identical to the addition in the backport of #113372 to this branch, so
whichever merges second is not a conflict.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
clickhouse-gh Bot added a commit that referenced this pull request Aug 7, 2026
Backport #113372 to 26.6: Infer an omitted Buffer structure under the user's context
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 7, 2026
Backport #113372 to 26.7: Infer an omitted Buffer structure under the user's context
PedroTadim added a commit that referenced this pull request Aug 7, 2026
Backport #113372 to 26.5: Infer an omitted Buffer structure under the user's context
PedroTadim added a commit that referenced this pull request Aug 7, 2026
Backport #113372 to 25.8: Infer an omitted Buffer structure under the user's context
PedroTadim added a commit that referenced this pull request Aug 7, 2026
Backport #113372 to 26.3: Infer an omitted Buffer structure under the user's context
auto destination = DatabaseCatalog::instance().getTable(destination_id, args.getLocalContext());
auto destination_metadata = destination->getInMemoryMetadataPtr(args.getLocalContext(), false);
columns = destination_metadata->getColumns();
}

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.

Same as in #113220 (comment), let's move resolving from the ctor into register method as well

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.

Will do, same shape as #113220. The register method already resolves under the user's context, so what is left is dropping the ctor fallback and covering the metadata-loading path in the register method too (no access check on that branch, there is no user there). I will follow up here with the PR.

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: #114203. The ctor is now a plain setColumns(columns_); the register branch covers the stored-metadata callers too, with no access check there since they carry no user, resolving with args.getContext(), which is the context the ctor used on those paths.

I left Distributed out: that ask is on @ PedroTadim's thread in #113220, and getStructureOfRemoteTable over a cluster is a much larger change than Buffer's local metadata read.

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants