Repository navigation
Forbid to create a table as viewIfPermitted - #116885
alexey-milovidov merged 11 commits into
Conversation
viewIfPermitted(query ELSE f(...)) chooses between the query and the ELSE
function according to the current user. CREATE TABLE ... AS <table function>
resolves the function under the global context (InterpreterCreateQuery.cpp:2412
-> ITableFunction::execute:67), which has no user and is therefore full access,
so isPermitted always took the view branch.
From a user holding only GRANT CREATE TABLE on one database and nothing on the
source table, that had two consequences. The structure mismatch exception
reported the source table's complete column list and types to a caller that is
denied DESCRIBE on it with ACCESS_DENIED, which is exactly what the comment
above that comparison says must not happen ("We check that columns match only
if permitted (otherwise we could reveal the structure to an user who must not
know it)"). And with a matching ELSE structure the persisted object became the
view branch, so reading it raised ACCESS_DENIED where the direct call returns
the fallback.
The defect is not a missing access check but a missing identity: no check can
decide a per-user branch when there is no user to decide for. The only sound
alternatives are to refuse persistence or to invent a persisted representation
of the decision, and the latter needs a new base class extension point, changes
what SHOW CREATE TABLE reports, and lands the user in a state they could have
written by hand. Redacting the structures from the message is not sufficient
either: a guessed ELSE structure that is correct creates the table while a wrong
one errors, so the schema stays recoverable by search.
So refuse it through canBeUsedToCreateTable(), read at
InterpreterCreateQuery.cpp:2406 before anything is resolved. This is the
mechanism the *Cluster functions and eval already use, and
CREATE TABLE ... AS view(...) is already denied at create time, so
viewIfPermitted was the outlier. Using the function in a query, where a user
exists, is unchanged.
Tables created before this change keep loading: DatabaseOnDisk does not consult
this virtual, so startup, ATTACH DATABASE and dropped table recovery are
unaffected. An explicit ATTACH TABLE of such a table is refused, the same as for
*Cluster and eval; a server restart re-attaches it.
Co-Authored-By: Claude Opus 5 <[email protected]>
The changelog entry promises that CREATE TABLE ... AS viewIfPermitted(...) now fails with BAD_ARGUMENTS, and no reference line pinned that code: every assertion matched message text only. Assert it in the arm that carries an explicit column list. That arm is the one where the assertion can fail, because its whole output is the refusal, and before the fix its CREATE succeeded silently and produced nothing. The arm above it captures a CREATE and a following SELECT together, so before the fix its capture already contained the disclosed exception's own BAD_ARGUMENTS and a code match there would hold in both directions. The message assertion stays: "cannot be used to create a table" occurs once in src/, so it pins the throw site more tightly than the code does. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 full passes, 4 findings, 2 fix
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260828-121800 |
|
Workflow [PR], commit [9549462] Summary: ✅
AI ReviewSummaryThis PR closes the Final Verdict✅ No new findings in the current head. LLVM Coverage ReportMeasured on commit 9549462.
Changed lines: Changed C/C++ lines covered: 31/31 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20260828-112400 |
|
cc @vitlibar @kssenii, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units87 translation units recompiled, 563 s compile time in total, 87 of them have a recent master baseline. |
|
Follow-up on the residual this description mentions, The carrier, pre-existing on master and not affected by this PR: from a user with no grant of any kind on SELECT * FROM remote('127.0.0.1:<own tcp port>', viewIfPermitted(SELECT * FROM s.t_secret ELSE null('...')))
SETTINGS prefer_localhost_replica = 0;returns the source table's full column list in a I planned to close it the way the local-shard check closes the named-table case, by refusing a target whose result is an access-denied fallback. Reviewing that plan showed the approach does not converge:
The common cause is that the initiator and the executor are different principals. @alexey-milovidov, which of these do you want?
I would rather implement your choice than guess. You wrote the local-shard check ( |
CI finish ledger - ee55ffcCI is fully finished: 147 OK, 22 skipped, 1 failure. The failure has an owner.
Session id: cron:our-pr-ci-monitor:20260828-180000 |
…function The AI review found that `CREATE TABLE ... AS remote(..., viewIfPermitted(...))` persists the nested function too, and a later read on a local shard with `prefer_localhost_replica = 0` decides the guarded branch under the connection's credentials instead of the reader's grants, disclosing the guarded structure in the `BAD_ARGUMENTS` mismatch text or the guarded rows. Refuse a grant-dependent table function at any nesting depth in `InterpreterCreateQuery`, through a new `ITableFunction::dependsOnCurrentUserGrants` virtual that only `viewIfPermitted` overrides. An AST walk rather than a check inside `remote` argument parsing, because it also catches carriers such as `remote(..., loop(viewIfPermitted(...)))` and stays out of the files ClickHouse#110073 is rewriting; keyed on the new narrow predicate rather than `canBeUsedToCreateTable`, so `remote(..., clusterAllReplicas(...))` and other user-independent nested functions are not newly refused. The query form of the same disclosure, `SELECT ... FROM remote(..., viewIfPermitted(...))` with `prefer_localhost_replica = 0`, needs no table and is unchanged here; it is tracked separately.
…ate-table-as-view-if-permitted
CI finish ledger - ff2f3f4CI is fully finished at this commit: 170 checks, two failed jobs, and each has an owner.
Neither failure is attributable to this diff, which only refuses persisting Reports:
Session id: cron:our-pr-ci-monitor:20260831-053000 |
…gine argument `throwIfNestedTableFunctionDependsOnCurrentUserGrants` only ran on the `CREATE TABLE ... AS <table function>` path, so the same grant-dependent target was still persistable through the `Remote` / `RemoteSecure` engines, which store a nested table function in `remote_table_function_ptr`. An AST carrying `viewIfPermitted(SELECT ... ELSE ...)` in engine arguments (e.g. through the `clickhouse_json` dialect) therefore created a persisted table whose branch is later decided under the connection credentials instead of the reader's grants. Apply the same veto to the engine arguments, except when the definition is loaded back from already-validated metadata, so a table created before this check still attaches.
…ate-table-as-view-if-permitted
…sistable` The SQL parser only produces `viewIfPermitted(SELECT ... ELSE ...)` in table-expression position, so the engine-argument carrier is reachable through the `clickhouse_json` dialect, which executes a deserialized AST. The test splices the `viewIfPermitted` node into the engine arguments of a `parseQueryToJSON` output instead of writing the JSON by hand, so it follows the serialization format rather than pinning it, and checks a benign nested table function is still accepted.
CI finish ledger - 590b750Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
I deliberately did not merge master and re-push. @ alexey-milovidov holds this head (the last five Session id: cron:our-pr-ci-monitor:20260902-133000 |
…ate-table-as-view-if-permitted
…e is inferred
`createTable` calls `getTablePropertiesAndNormalizeCreateQuery` before
`doCreateTable`, and for `CREATE TABLE ... AS f(...)` without a column list
that helper resolves the table function through
`getActualTableStructureWithAccess` to infer the structure. The veto
(`canBeUsedToCreateTable` plus the nested `dependsOnCurrentUserGrants`
walk) ran only in `doCreateTable`, so on that path the inference happened
first: `remote('unreachable', viewIfPermitted(...))` connected to the shard
and failed with `NO_REMOTE_SHARD_AVAILABLE` instead of the promised
`BAD_ARGUMENTS`, and `viewIfPermitted(... ELSE remote(...))` analyzed the
`ELSE` arm before the refusal.
Both checks are now one helper, `throwIfTableFunctionCannotBeUsedToCreateTable`,
called right before the structure inference in
`getTablePropertiesAndNormalizeCreateQuery` and kept in `doCreateTable` for
the explicit-column-list form, which skips the inference. Persisted metadata
always carries a column list, so the early pass does not affect attaching an
existing table.
The comment avoids `<table function>`: clang's `-Wdocumentation-html` treats
it as an unterminated HTML tag.
…itted_not_persistable`
Two statements without a column list where a late veto would have side
effects: an outer `remote('127.0.0.1:1', viewIfPermitted(...))` and an
`ELSE remote('127.0.0.1:1', system.one)` arm. With the check still in
`doCreateTable` only, both fail on the connection attempt with a `519`
class error; the reference pins `BAD_ARGUMENTS` and no leaked identifier.
…ate-table-as-view-if-permitted
|
🕵 The sole red on |
…ool contention The test timed out in `ALTER TABLE t_shared APPLY PATCHES SETTINGS mutations_sync = 2`: the merge-selecting task refused to assign the mutation because the server-global pool was occupied by concurrent tests (`max_tasks_count (32) - occupied (25) < number_of_free_entries_in_pool_to_execute_mutation (8)`), and since the table had just been re-attached, `merge_selecting_sleep_ms` started near `max_merge_selecting_sleep_ms`, so the next attempt was scheduled only after 60000 ms and the `mutations_sync = 2` wait hit its 60 s limit. Set `number_of_free_entries_in_pool_to_execute_mutation = 0` on the table, as `02899_restore_parts_replicated_merge_tree` already does for the same reason. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116885&sha=76f996abfd704d65e2eeb35a9cc4de47ac9cf0ba&name_0=PR&name_1=Fast%20test PR: ClickHouse#116885 Co-Authored-By: Claude Fable 5.1 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Forbid
CREATE TABLE ... AS viewIfPermitted(...), includingviewIfPermittednested in another table function such asremote, which now fails withBAD_ARGUMENTS, as it already does forevaland the*Clustertable functions. The function chooses between itsSELECTquery and theELSEfunction according to the current user, but a persisted table is resolved with no user and therefore full access: reading one reported the source table's column names and types to a user with no grant on it, and theELSEfallback was unreachable. Tables created before this change keep loading; drop them to close the disclosure.Description
Related: #116793, where a review bot reported this (
discussion_r3878677312); my measurements are indiscussion_r3878897538. Pre-existing, not caused by #116793.CREATE TABLE ... AS <table function>resolves the function under the global context (InterpreterCreateQuery.cpp:2412->ITableFunction::execute:67), which has no user and is full access, soisPermittedalways took theviewbranch. From a user holding onlyGRANT CREATE TABLE ON <db>.*, the structure-mismatch exception reported the source table's complete column list and types to a caller deniedDESCRIBEon it; with a matchingELSEstructure the fallback became unreachable and the read raisedACCESS_DENIED.The defect is not a missing check but a missing identity: no check can decide a per-user branch with no user. So
viewIfPermittedoverridescanBeUsedToCreateTable(), checked atInterpreterCreateQuery.cpp:2406before anything is resolved.*Cluster(#73804) andeval(#110132) already use this mechanism, andCREATE TABLE ... AS view(...)is already denied at create time, soviewIfPermittedwas the outlier.CREATE VIEWis the supported replacement. Using the function in a query is unchanged, and nothing intests/ordocs/uses the refused form.Not addressed:
DatabaseOnDisk::createTableFromASTdoes not consult this virtual) and still disclose on read;ATTACH TABLE,UNDROP TABLE,RESTOREandDatabaseReplicatedlost-replica recovery of one now fail, as they already do for*Clusterandeval, though a restart still re-attaches it;the check reads only the outermost table functionaddressed after review: a persistedremote(..., viewIfPermitted(...))(orremote(..., loop(viewIfPermitted(...)))) disclosed the same way via the engine credentials on a local shard, soInterpreterCreateQuerynow also refuses, at any nesting depth, a table function whose storage is chosen by the current user's grants (a new narrowITableFunction::dependsOnCurrentUserGrantsvirtual, so user-independent nested functions such asclusterAllReplicasorevalare not newly refused). The same veto is now applied to the arguments of a table engine, because theRemote/RemoteSecureengines store a table function target of their own inremote_table_function_ptr: the SQL parser only producesviewIfPermitted(SELECT ... ELSE ...)in table-expression position, but theclickhouse_jsondialect executes a deserialized AST and could carry that shape into engine arguments. Definitions loaded back from already-validated metadata are not re-checked, so a table created before this change still attaches instead of disappearing on startup. The veto runs before the structure is inferred for a definition without a column list, soremote('unreachable', viewIfPermitted(...))or anELSE remote(...)arm is refused withBAD_ARGUMENTSwithout contacting the shard or analyzing the arm. The query form of the same disclosure,SELECT ... FROM remote(..., viewIfPermitted(...))withprefer_localhost_replica = 0, needs no table at all, so no create-time check reaches it: identical on master, tracked separately.Validation
Debug build,
26.9.1.1. Fix build id520db3a0176fe01b20010e6294308f9500507e94, basec523792320c65ef62e806fba02851d46b076b63c(master438a6180ae9641a3).Without the fix, from a user granted only
CREATE TABLE ON <db>.*, theCREATEsucceeds silently (engineProxy) and the read discloses:The same user gets
Code: 497 (ACCESS_DENIED)forDESCRIBE TABLE d5060.src.05060_view_if_permitted_not_persistable, fix05060_view_if_permitted_not_persistable, baseDecimal FixedString salary secret_a secret_b ssnviewIfPermitted, plus04028_describe_table_function_rbac_bypassand03307_forbid_loop_table_function_as_enginecount()= 3urlCluster/evalCREATE TABLE ... ASEvery arm is pinned by a mutant, and the three mutants redden different arm sets, so none is redundant.
04514_table_functions_access_rights_rewritecannot run in my sandbox (itsquery_as_userhelper uses$CLICKHOUSE_CLIENT_BINARYwithout$CLICKHOUSE_CLIENT_OPT, so it connects to port 9000) and fails identically on the base binary; its fourviewIfPermittedassertions were replayed by hand against the patched build and all pass.Workflow [PR]
Sync PR [sync-upstream/pr/116885]
Version info
26.9.1.909(included in26.9and later)