Skip to content

Check the target engine's grant when ATTACH carries a URL engine definition - #115914

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-attach-url-dispatch-engine-grant
Aug 22, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-attach-url-dispatch-engine-grant

Conversation

@groeneai

@groeneai groeneai commented Aug 22, 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 ATTACH TABLE carrying an ENGINE = URL(...) definition did not check the TABLE ENGINE grant of the engine the URL scheme dispatches to. A user holding only TABLE ENGINE ON URL could attach and then read a File, S3, AzureBlobStorage or HDFS backed table, which CREATE TABLE correctly rejects.

Description

ENGINE = URL(...) dispatches by URL scheme to File/S3/AzureBlobStorage/HDFS and re-checks TABLE ENGINE on that target. The re-check ran only for LoadingStrictnessLevel::CREATE, so a full-definition ATTACH skipped it:

GRANT URL ON *.* TO urlonly;
GRANT TABLE ENGINE ON URL TO urlonly;    -- no FILE grant

-- denied, correctly
ATTACH TABLE t (s String) ENGINE = File('LineAsString', '/var/lib/clickhouse/user_files/secret.csv');

-- allowed: same engine, reached through the URL scheme
ATTACH TABLE u UUID '...' (s String) ENGINE = URL('file:///var/lib/clickhouse/user_files/secret.csv', 'LineAsString');
SELECT * FROM u;   -- reads the file with no FILE grant

Its comment claimed it mirrored the outer engine check, but neither outer site (InterpreterCreateQuery.cpp:772, :3522) consults the mode. No read-time gate exists, so the table stays readable. Reachable on Atomic via ATTACH TABLE t UUID '<uuid>' <definition>.

The fix uses the fresh-definition predicate already used by StorageDistributed, StorageBuffer, StorageNATS and DatabaseBackup: check whenever a definition is introduced now, skip only when replaying one stored on this server (startup, short ATTACH TABLE t, ATTACH DATABASE), so existing tables stay loadable after a revoke.

That also covers RESTORE, matching the ruling at StorageDistributed.cpp:2675-2691. Exempting it is one extra term if you prefer.

The attach_short_syntax flag the predicate reads is also settable through the default-off enable_json_ast_dialect path, which five existing master gates trust the same way. #114171 closes that at the deserializer, so nothing for it is included here.

Coverage extends the existing 04401_url_engine_s3_dispatch_engine_grant: file:// and az:// ATTACH denials, a RESTORE deny/grant pair, an http:// positive control, and a short-ATTACH arm pinning the exempt half. The new arms fail on master and pass here. Denial assertions now anchor on the privilege message rather than the engine name alone.

@PedroTadim found this and asked me to fix it here. My open #113073 touches the same function for a separate ON CLUSTER defect.


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

…nition

ENGINE = URL(...) dispatches by URL scheme to File/S3/AzureBlobStorage/HDFS and
re-checks TABLE ENGINE on that target inside the storage creator. The re-check was
gated on LoadingStrictnessLevel::CREATE, so an ATTACH carrying a full definition
skipped it: a user holding only TABLE ENGINE ON URL could attach a File-backed
table and read it, while the equivalent CREATE was correctly denied.

The gate's comment justified itself by claiming it mirrored where the outer engine
privilege is checked. That premise was false. Neither outer site
(InterpreterCreateQuery.cpp:772 and :3522) consults the mode, which is exactly why
ATTACH ... ENGINE = File(...) is denied while the same engine reached through
ENGINE = URL('file://...') was not: the outer check sees only URL, which the user
holds, and the inner check that would have seen File did not run. No source check
exists at read time, so the table remained readable afterwards. The bypass is
reachable on Atomic, the default database engine, through the
ATTACH TABLE t UUID '<uuid>' <definition> form.

Use the fresh-definition predicate that already answers this question in
StorageDistributed, StorageBuffer, StorageNATS and DatabaseBackup, rather than a
mode equality: authorize whenever a definition is introduced now, and skip only
when replaying one already stored on this server. A bare
!isLoadingFromExistingMetadata would not do, because short ATTACH TABLE t and the
tables loaded by ATTACH DATABASE run at mode ATTACH rather than FORCE_ATTACH and
would newly be denied; attach_short_syntax is what separates those.

This also authorizes SECONDARY_CREATE. For replicated-database DDL replay that is a
no-op, since the DDL worker context carries no user and so has full access. For
RESTORE it is a deliberate behaviour change, matching the ruling in
StorageDistributed.cpp:2676-2691 that a restore introduces a definition under a
possibly different user and must be validated like a CREATE.

Extend 04401_url_engine_s3_dispatch_engine_grant with the ATTACH side: file:// and
az:// denials, an http:// positive control, and a short ATTACH arm that pins the
exempt half, so a later simplification to the bare predicate cannot pass. Anchor
the denial assertions on the privilege sentence as well; the previous pattern could
match the failing query echoed back by the client, which contains both the engine
name and the word grant, and so would have accepted a query that was never denied.
The two arms asserting an ATTACH was permitted inferred that from the absence of a
denial in the output. Every other failure leaves the same empty match, so a parse
error, a UUID collision or any storage-construction throw printed the allowed label;
the script has no set -e and the trailing DROP TABLE IF EXISTS succeeds either way,
so nothing downstream exposed it. Measured on the same binary with a failure
injected into each arm: the previous form reported OK while the ATTACH it was
asserting had failed with TABLE_ALREADY_EXISTS, and with CANNOT_GET_CREATE_TABLE_QUERY
for the short ATTACH. Both arms now also assert the table is present in
system.tables, and an unrelated failure prints a third label that is absent from the
reference file, so it surfaces as a mismatch rather than picking either existing
label. This matters most for the short ATTACH arm, which is what pins the exempt
half of the predicate; the mutation dropping that half still reddens it, through the
denial branch rather than the new failure branch.

RESTORE is the one deliberate behaviour change here and had no arm of its own. Add
one following the structure of 04401_remote_storage_engine_restore_access, which
covers the equivalent ruling for the Remote engine: deny without the target engine
grant, assert nothing was created, grant it, then succeed. On the pre-fix binary the
first two invert, so the arm is not vacuous, while the granted retry passes on both
and shows this is a grant requirement rather than a hard break.

The backup destination carries the shell's pid. A destination may not be written
twice and no statement deletes one, and a fixed --database stops the unique name from
varying between runs of a single test, so without the suffix a repeated run fails
BACKUP_ALREADY_EXISTS: measured 1 of 3 runs passing without it against 3 of 3 with it.
The delegate engine check in the URL scheme dispatcher treats
attach_short_syntax as proof that the definition it is about to build came
from this server's own metadata, and therefore skips the target TABLE ENGINE
grant. That inference is sound for every parsed query: no parser sets the
flag, and all of its setters run after parsing, where the interpreter is
replaying a definition it already stored.

It is not sound for a clickhouse_json payload, where the flag is an input the
user supplies directly. readJSON rejected it only when the query was not an
ATTACH, so an ATTACH payload could set it freely, keep its own storage clause
(the interpreter replaces the query from stored metadata only when no storage
definition is present), and reach DatabaseOnDisk's short-syntax early return
with a user-supplied file:// definition marked as replayed metadata. That is
reachable on Atomic, the default, because DETACH only nulls the value in the
UUID map while the mapping check tests for the key: create an http:// table
with a known UUID, detach it, then submit the forged definition under that
UUID.

Reject the flag unconditionally instead, generalizing the guard that was
already there rather than adding a second mechanism. Nothing legitimate
regresses: writeJSON emits the field unconditionally, so every
parseQueryToJSON round trip carries false, and the interpreter paths that do
set it never serialize to JSON on the request path.

The existing AST JSON validation test gains the ATTACH analogue of its
CREATE arm.
… to exist

The arms asserting a statement was permitted checked that the table is
present afterwards. A table left behind by an interrupted run satisfies that
without the statement having run at all: the ATTACH fails
TABLE_ALREADY_EXISTS, the failure does not match the denial pattern, and the
arm prints the label that is supposed to mean the grant was accepted. Measured
on one binary with a leftover holding the arm's name and UUID, the arm passed
with output byte-identical to the reference while its ATTACH had returned 57.

Reachable because the unique name only varies with the database name, and the
stress runner passes a fixed one, so repeated runs of a test reuse the same
table names.

Clear each target first, so its presence afterwards is attributable to the
statement under test, and require exit status 0 in addition to the absence of
a denial. The count probe now reports a failure of its own query rather than
returning it as absence, which the arms asserting nothing was created would
otherwise accept as their pass.
…ape"

This reverts commit 10b0d3b.

PR ClickHouse#114171 already closes the same hole in a stronger form: it rejects the
key's presence rather than only a true value, and stops writeJSON emitting
the field at all, so there is no forgeable input left. Its hunks touch these
exact lines and conflict only with this commit, and its removal of the field
would silently void the test arm added here (the arm injects into a needle
that leaves the payload).

The URL delegate engine check this branch is about does not depend on the
revert: attach_short_syntax remains a sound provenance signal for every
parsed query, which is the only shape reachable without the default-off
enable_json_ast_dialect setting.
…denied

The http CREATE arm read "no access-denial text matched" as success. It captured no
exit status and did not check that the table was there, so a parse error, a table left
by an interrupted run, a host-filter refusal or any other non-access failure printed
the permitted label and the test passed.

That arm is the file's only guard against the four denial arms passing for the wrong
reason: a user holding no engine grant at all is denied everywhere, and only this arm
would notice. A vacuous positive control therefore lets a regression that breaks
URL-engine CREATE outright show all-green.

It now uses the shape the ATTACH http arm already uses on the same statement: the
target is dropped first as the admin, so its absence makes the presence afterwards
attributable to this statement, and the permitted label requires exit status 0 and the
table's presence in addition to the absence of a denial. The reference file is
unchanged; the new failure label is absent from it, so it surfaces as a diff.

Reproduced before fixing: with a leftover table holding the arm's name, on one binary,
the old shape passes while the new one reports rc=57 TABLE_ALREADY_EXISTS.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 5 rounds (5 accepted, 3 declined with evidence)

An independent model re-reviewed this change cold against the PR contract at each round. The final
round returned no findings. Accepted findings are fixed in the commits above.

Finding Verdict
⚠️ The absence of a denial is not success: an unrelated failure leaves the same empty match accepted - denial assertions are anchored on the privilege sentence, and every permitted arm asserts an attributable table
⚠️ A positive arm asserts the table is present, not that its own statement created it, so a leftover table from an interrupted run prints the allowed label accepted - permitted arms now require exit status 0 and an absent target beforehand; the presence probe reports its own failure instead of returning it as absence
⚠️ RESTORE is the one deliberate behaviour change and had no regression arm accepted - added a deny / nothing-created / grant-and-succeed triple, following 04401_remote_storage_engine_restore_access
⚠️ The pre-existing http:// CREATE control was left on the loose shape, so it still printed its allowed label on any non-access failure accepted - now requires exit status 0 and an attributable table like the arms added here. The arm is unchanged from master, but the comment added here claims that property for every permitted arm, and it is the file's only guard against the denial arms passing because the user holds no engine grant at all.
❌ attach_short_syntax is an input of the JSON AST deserializer, so a dialect = clickhouse_json payload could set it and skip a check that reads it as proof the definition came from stored metadata accepted as a defect, dropped from this PR. #114171 already fixes it on the same lines and more strongly: it rejects the key's presence rather than only the value true, and removes the field from writeJSON. My weaker version conflicted with it, and its test arm would have gone silently vacuous once that lands, so I reverted it. The flag is read the same way by StorageDistributed, StorageBuffer, StorageNATS and DatabaseBackup on master, so this is a property of the shared predicate rather than of this change, and the dialect is off by default.
❌ A short ATTACH can resolve a named collection to a different target engine than the one authorized and skip that engine's grant declined. The exemption there is not new: pre-change the gate was mode == CREATE and a short ATTACH runs at mode ATTACH, so that path was already skipped, named collection or not. Behaviour is identical before and after. The drift also needs ALTER NAMED COLLECTION (NAMED_COLLECTION_ADMIN, parent ALL), not the URL-only user, and the exemption is required rather than merely intended: dropping it makes an existing table unattachable after a revoke, which the short-ATTACH arm pins.
❌ Wait for #114171 to merge, then rebase this change onto it declined. Once the JSON commit is reverted, ASTCreateQuery.cpp and 04494 leave this diff entirely, so there is no shared line to rebase onto. The two changes are independent.
💡 Comment block above the predicate exceeds the per-block comment budget declined - it replaces a four-line comment of the same size whose stated premise was false, and both halves are standing invariants rather than notes about the fix

Also noticed and not raised: a full-definition ATTACH ... ON CLUSTER reaches tryEnqueueReplicatedDDL
before this creator, so it is unaffected by this change in either direction. That is the separate
initiator-side gap in my #113073, and both enqueue returns are mode-blind, so plain CREATE ... ON CLUSTER
has it too.

@clickhouse-gh clickhouse-gh Bot closed this Aug 22, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e528ac5]

Summary: ✅


AI Review

Summary

This PR fixes the local ATTACH/RESTORE privilege gap for ENGINE = URL(...) by re-checking the dispatched backend engine instead of limiting that check to CREATE. The local Atomic path looks correct, but the same invariant is still bypassable through clickhouse_json and through replicated / clustered DDL, so I do not think this is ready to merge as a complete security fix.

Findings

❌ Blockers

  • [src/Storages/StorageURL.cpp:2495] attach_short_syntax is still accepted from clickhouse_json ATTACH payloads and executed directly, so a user can forge "attach_short_syntax": true on a full-definition ATTACH ... ENGINE = URL('file://...') and skip the new target-engine TABLE ENGINE check.
  • [tests/queries/0_stateless/04401_url_engine_s3_dispatch_engine_grant.sh:6] The new check only protects local table creation. Replicated / Shared databases and ... ON CLUSTER still authorize only the outer URL engine on the initiator and then execute creation under an internal DDL context by default, so the dispatched backend grant is still not enforced there.
Final Verdict

❌ Changes requested. The local Atomic regression is covered, but the security invariant is still broken for clickhouse_json and replicated/distributed DDL paths.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.10% 87.00% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · 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 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One ATTACH TABLE t UUID '<uuid>' (s String) ENGINE = URL('file://<user_files>/secret.csv', 'LineAsString') as a user holding only TABLE ENGINE ON URL; the following SELECT returns the file contents. 100% reproducible, not rate-based.
b Root cause explained? Yes. The delegate TABLE ENGINE re-check in tryDispatchURLEngineByScheme ran only for LoadingStrictnessLevel::CREATE. Its comment claimed to mirror the outer engine check, but neither outer site (InterpreterCreateQuery.cpp:772, :3522) consults the mode, so on ATTACH the outer check sees only URL (held) and the inner check that would see File is skipped.
c Fix matches root cause? Yes. The mode gate is the defect, and it is replaced in place with the fresh-definition predicate. No widened bound, no guard at a downstream site, no defensive check masking it.
d Test intent preserved / new tests added? Yes. Seven arms added to the existing 04401_url_engine_s3_dispatch_engine_grant (four ATTACH, three RESTORE; no new file); existing arms keep their intent and get stronger. No assertion weakened, no no-parallel tag added. Every arm asserting a statement was permitted (including the pre-existing http:// CREATE control, tightened here to the same shape) requires exit status 0 and an attributable table (the name is cleared first, so its presence afterwards is evidence this statement created it), so neither an unrelated failure nor a table left by an interrupted run can be read as the allowed outcome; each guard was checked by injecting a failure and confirming it flips the arm where the previous shape stayed green.
e Both directions demonstrated? Yes. Same test, same fixture, only the binary differs: [ FAIL ] on base 8d95348777d2048e, [ OK ] on fix d24e031ab4c378ab. On base the two ATTACH denial arms print NOT DENIED and the RESTORE arm prints NOT DENIED / RESTORED ANYWAY, so no added arm is vacuous. The RESTORE-once-granted arm passes on both by design: it is the positive control showing this is a grant requirement, not a hard break.
f Fix is general across code paths? Yes. One predicate governs all four dispatch targets (File/S3/AzureBlobStorage/HDFS); the test covers File, S3, Azure. This is the only TABLE_ENGINE check in src/Storages/. Swept every other mode == CREATE gate in src/Storages/ and src/Databases/: StorageMerge.cpp:2254 already uses the correct fresh-definition predicate, and StorageAlias.cpp:499 gates argument validation rather than access control.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, along the axis that applies: the statement/mode matrix. CREATE, full ATTACH (with UUID on Atomic), short ATTACH, ATTACH DATABASE, server startup, UNDROP, RESTORE and replicated-DDL replay are each covered or reasoned, four of them asserted in the test. Type wrappers do not apply; the input is a URL scheme, and every scheme resolves to one of the four targets or to URL (http still allowed, asserted).
h Backward compatible? (maintainer-approved exception only) No setting, serialization, format or default change, so no SettingsChangesHistory.cpp entry. Previously-created tables stay loadable after a revoke, pinned by the short-ATTACH arm. One intentional change is disclosed in the description: RESTORE now requires the target engine grant, matching the ruling at StorageDistributed.cpp:2675-2691.
i Invariants and contracts preserved? Yes. The check runs on the same path that already performed it, before any storage is constructed, so no partial-construction or early-return path is introduced. One bool local and one branch; no locks, allocation or concurrency surface touched. Restart re-entry is FORCE_ATTACH and stays exempt, so no table becomes unloadable after a restart.

Verification: 50/50 runs with randomized settings, 50/50 with enable_analyzer=1, 8/8 across 4 concurrent jobs, and 3/3 under a fixed --database (the shape that makes the unique name stable between runs) (the arms are parallel-safe; each ATTACH UUID derives from CLICKHOUSE_TEST_UNIQUE_NAME, and the backup destination also carries the pid, since a fixed --database makes that name stable across repeated runs and a backup destination may not be written twice). All 27 stateless tests referencing ENGINE = URL plus 02184_table_engine_access, 02561_temporary_table_grants and 04401_remote_storage_engine_restore_access were run: every ATTACH-using one passes, and the three failures were reproduced identically on the pristine base binary (two need S3 credentials this sandbox lacks, one is a pre-existing TRUNCATE arm).

Anti-vacuity: dropping || args.query.attach_short_syntax reddens the short-ATTACH arm and only that arm, through the denial branch rather than the failure branch, so the exempt half is genuinely tested rather than assumed, and the arms stayed live after the oracles were tightened (the base-binary control still inverts the same four lines). The denial assertions are anchored on the privilege sentence, because the previous pattern also matched the query echoed back in an unrelated error.

Session id: cron:clickhouse-impl-slot-6:20260822-105600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit, could you review the authorization side of this? The URL engine re-checks TABLE ENGINE on the engine its scheme dispatches to, but the check was gated on mode == CREATE, so a full-definition ATTACH skipped it while the outer engine check (which is mode-blind) saw only URL. It now uses the fresh-definition predicate the other storages use, which also makes RESTORE require the target grant.

/// the scheme is the user's choice, and it selects the engine. A definition replayed from this
/// server's metadata (startup, short `ATTACH TABLE t`, `ATTACH DATABASE`) was already validated
/// and must stay loadable after a revoke; every other statement introduces one to check.
const bool from_existing_metadata = isLoadingFromExistingMetadata(args.mode) || args.query.attach_short_syntax;

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.

from_existing_metadata now trusts args.query.attach_short_syntax, but that bit is still user-forgeable on ATTACH JSON ASTs. ASTCreateQuery::readJSON only rejects attach_short_syntax for non-ATTACH payloads (src/Parsers/ASTCreateQuery.cpp:563-574), so a user can enable clickhouse_json, send a full-definition ATTACH TABLE ... ENGINE = URL('file://...') with "attach_short_syntax": true, and reach this branch with args.mode == ATTACH. That skips the new target-engine TABLE ENGINE check again, so the privilege bypass is still open through the JSON entrypoint even though the SQL path is fixed.

Please either harden the deserializer in this PR or avoid using attach_short_syntax as trusted provenance until that hardening is already in the base.

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.

The bypass is real and the PR description already flags it. It is out of scope here on two grounds.

It is already fixed, more strongly, in #114171: that PR rejects the presence of the key (if (r.has("attach_short_syntax")) throw) rather than only the value true, and deletes w.writeBool("attach_short_syntax", ...) from writeJSON, so no legitimate payload carries the field and there is nothing left to forge. I had that hardening in this branch and reverted it in 403df7c after measuring that theirs covers it: my hunks conflicted with theirs on the same lines, and removing the field from writeJSON would have made my test arm silently vacuous, since it matched the needle '"attach_short_syntax":false'. They rewrote the same 04494 arm to '"replace_table":false' for that reason. src/Parsers/ASTCreateQuery.cpp at this head is byte-identical to my merge base, so this PR ships nothing there.

Your alternative, dropping attach_short_syntax as provenance, would be a regression rather than a hardening. DatabaseOnDisk.cpp:102 sets that flag for every definition read back from this server's stored metadata, including ATTACH DATABASE and dropped-table recovery, and :169 then creates the storage at mode ATTACH. Without the term an existing table stops loading once the grant is revoked; the PR has a mutation arm pinning that exempt half.

The predicate is also not novel here: five gates on master trust the same bit identically (DatabaseBackup.cpp:540, StorageNATS.cpp:1201, StorageBuffer.cpp:1541, StorageDistributed.cpp:2307, :2692), and :2692 is the access-check ruling this change follows, from b9c3141. Fixing the deserializer once closes it for all six; special-casing this one site would leave the other five open and break metadata loading here.

/// the scheme is the user's choice, and it selects the engine. A definition replayed from this
/// server's metadata (startup, short `ATTACH TABLE t`, `ATTACH DATABASE`) was already validated
/// and must stay loadable after a revoke; every other statement introduces one to check.
const bool from_existing_metadata = isLoadingFromExistingMetadata(args.mode) || args.query.attach_short_syntax;

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.

attach_short_syntax is still user-controlled through clickhouse_json, so this new provenance check is bypassable.

ASTCreateQuery::readJSON only rejects attach_short_syntax for non-ATTACH payloads (src/Parsers/ASTCreateQuery.cpp:570-580), and clickhouse_json executes the deserialized AST directly instead of formatting it back to SQL first (src/Interpreters/executeQuery.cpp:2318-2355, tests/queries/0_stateless/04829_view_table_function_json_execution.sh). A user who can turn on enable_json_ast_dialect can therefore send a full-definition ATTACH ... ENGINE = URL('file://...') JSON AST with "attach_short_syntax": true, hit this branch as from_existing_metadata, and skip the new TABLE ENGINE ON File check again. Until that flag stops being accepted from user input, this fix is still bypassable.

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.

Same finding as your comment above; answered there. Both citations check out at this head, including the clickhouse_json path executing the deserialized AST directly.

Short version: enable_json_ast_dialect defaults to false, the flag is trusted identically by five existing gates on master, and #114171 closes it at the deserializer by rejecting the key's presence and removing the field from writeJSON. I implemented that hardening here and reverted it in 403df7c because it duplicated theirs on the same lines and would have left my test arm vacuous once their change landed.

/// server's metadata (startup, short `ATTACH TABLE t`, `ATTACH DATABASE`) was already validated
/// and must stay loadable after a revoke; every other statement introduces one to check.
const bool from_existing_metadata = isLoadingFromExistingMetadata(args.mode) || args.query.attach_short_syntax;
if (!from_existing_metadata)

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 skip is documenting a still-open privilege gap, not just a coverage limitation.

For Replicated / Shared databases and ... ON CLUSTER, the actual storage is created under an internal DDL context by default, so the new creator-side checkAccess(AccessType::TABLE_ENGINE, engine_name) does not run under the initiating user's grants. The initiator-side checks still only see the outer URL engine (src/Interpreters/InterpreterCreateQuery.cpp:772, :3521-3522) before the query is enqueued (src/Interpreters/InterpreterCreateQuery.cpp:1966-1978), and preserving the initiator's user/roles on workers is behind distributed_ddl_use_initial_user_and_roles, which defaults to false (src/Core/ServerSettings.cpp:1143, src/Interpreters/DDLTask.cpp:315-354). So the same TABLE ENGINE ON File/S3/AzureBlobStorage/HDFS bypass remains reachable on the default clustered path unless the target-engine check is also enforced before the DDL is replicated.

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.

The mechanism is right, and I verified every citation. What I disagree with is that this PR changes it.

The gap is mode-independent, so it is not reachable by widening this predicate. Pre-fix the guard was args.mode == LoadingStrictnessLevel::CREATE. On a Replicated worker the mode is SECONDARY_CREATE (InterpreterCreateQuery.cpp:1691, derived from getZooKeeperMetadataTransaction() && !isInitialQuery(), which DatabaseReplicatedTask::makeQueryContext establishes at DDLTask.cpp:713), so the inner check did not run there before this change either. On plain CREATE ... ON CLUSTER it did run, and it was still a no-op for the reason you name: with distributed_ddl_use_initial_user_and_roles false there is no setUser, so Context.cpp:2349 computes full_access = !user_id and ContextAccess.cpp:690 returns true before any grant is consulted. Both enqueue returns are mode-blind, as is shouldReplicateQuery. So the clustered behaviour is identical before and after this PR, for CREATE and ATTACH alike.

It also needs a different fix than a predicate. Your own remedy, enforcing the target check before the DDL is replicated, is my open #113073, "Authorize the table engine's target on the initiator of an ON CLUSTER CREATE", which this PR's description links. That PR does not reach the URL dispatcher yet, so the two halves are separate work rather than one omission. The worker-side half, where the replayed DDL runs with no user at all, is #111561, and it is an open design question rather than a local change: authorizing on one host makes replicas diverge because isGranted also shapes results, authorizing on all hosts is what distributed_ddl_use_initial_user_and_roles already does, and the third option is refusing to execute.

I would rather land the single-node ATTACH bypass, which is what @PedroTadim reported, than widen this PR into that fork.

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.37 MiB 702.35 MiB -3.02 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov this one is important

@PedroTadim PedroTadim self-assigned this Aug 22, 2026
@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 22, 2026
@alexey-milovidov alexey-milovidov self-assigned this Aug 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 22, 2026
Merged via the queue into ClickHouse:master with commit 2977132 Aug 22, 2026
358 of 361 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 22, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 22, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 23, 2026
… carries a URL engine definition

The URL engine dispatches by scheme to File/S3/AzureBlobStorage/HDFS. The
delegate's TABLE ENGINE privilege was re-checked only when the mode was
CREATE, so a user holding TABLE ENGINE ON URL alone could ATTACH a table with
a full URL('file://...') definition and then read it, while the equivalent
CREATE and a direct ENGINE = File(...) ATTACH were both denied. The outer
engine check is not mode-gated, so the inner one was the only gap.

The predicate now exempts only a definition replayed from this server's own
metadata: server startup, force-restore, a short ATTACH TABLE t, and the
tables an ATTACH DATABASE loads. Those were validated when the table was
created and must stay loadable after a revoke. Every other statement, ATTACH
with a definition and RESTORE included, supplies a fresh definition and is
checked.

The cherry-pick #115950 conflicts only because master renamed
04401_url_engine_s3_dispatch.sh to 04401_url_engine_s3_dispatch_engine_grant.sh,
which makes the pair a modify/delete on this branch. The source hunk applies
unchanged: tryDispatchURLEngineByScheme is byte-identical between master and
26.7. This is that resolved tree as a single commit on the 26.7 tip.

Validated in both directions on a server configured like the stateless one,
after asserting that table_engines_require_grant denies a no-grant user and
that the backups disk accepts a backup. Against the released 26.7.6.8 binary
the test fails on attach-file-engine-denied, attach-azure-engine-denied,
restore-file-engine-denied and restore-rejected-not-created, the same four
lines it inverted against pre-fix master; against the fixed build it passes
with no diff. The bypass itself reproduces on 26.7.6.8: ATTACH of a
URL('file://...') table is accepted and the following SELECT returns the file
contents, while both the CREATE and a direct File engine ATTACH are denied.

The four older branches are unaffected and need no backport: URL scheme
dispatch does not exist there, so a URL('file://...') read fails with
Code: 36, Unknown protocol in the URL.
clickhouse-gh Bot added a commit that referenced this pull request Aug 23, 2026
Backport #115914 to 26.7: check the target engine's grant when ATTACH carries a URL engine definition
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 24, 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-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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