Repository navigation
Check the target engine's grant when ATTACH carries a URL engine definition - #115914
Conversation
…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.
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
Also noticed and not raised: a full-definition |
|
Workflow [PR], commit [e528ac5] Summary: ✅
AI ReviewSummaryThis PR fixes the local Findings❌ Blockers
Final Verdict❌ Changes requested. The local LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Verification: 50/50 runs with randomized settings, 50/50 with Anti-vacuity: dropping Session id: cron:clickhouse-impl-slot-6:20260822-105600 |
|
cc @pufit, could you review the authorization side of this? The |
| /// 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units8 translation units recompiled, 19 s compile time in total, 8 of them have a recent master baseline. |
|
@alexey-milovidov this one is important |
2977132
… 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.
Backport #115914 to 26.7: check the target engine's grant when ATTACH carries a URL engine definition
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a case where
ATTACH TABLEcarrying anENGINE = URL(...)definition did not check theTABLE ENGINEgrant of the engine the URL scheme dispatches to. A user holding onlyTABLE ENGINE ON URLcould attach and then read aFile,S3,AzureBlobStorageorHDFSbacked table, whichCREATE TABLEcorrectly rejects.Description
ENGINE = URL(...)dispatches by URL scheme toFile/S3/AzureBlobStorage/HDFSand re-checksTABLE ENGINEon that target. The re-check ran only forLoadingStrictnessLevel::CREATE, so a full-definitionATTACHskipped it: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 onAtomicviaATTACH TABLE t UUID '<uuid>' <definition>.The fix uses the fresh-definition predicate already used by
StorageDistributed,StorageBuffer,StorageNATSandDatabaseBackup: check whenever a definition is introduced now, skip only when replaying one stored on this server (startup, shortATTACH TABLE t,ATTACH DATABASE), so existing tables stay loadable after a revoke.That also covers
RESTORE, matching the ruling atStorageDistributed.cpp:2675-2691. Exempting it is one extra term if you prefer.The
attach_short_syntaxflag the predicate reads is also settable through the default-offenable_json_ast_dialectpath, which five existingmastergates 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://andaz://ATTACH denials, aRESTOREdeny/grant pair, anhttp://positive control, and a short-ATTACHarm 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 CLUSTERdefect.Workflow [PR]
Sync PR [sync-upstream/pr/115914]