Skip to content

Require the WRITE ON FILE grant when rename_files_after_processing is set - #117895

Merged
antonio2368 merged 13 commits into
ClickHouse:masterfrom
groeneai:file-rename-after-processing-write-grant
Sep 7, 2026
Merged

antonio2368 merged 13 commits into
ClickHouse:masterfrom
groeneai:file-rename-after-processing-write-grant

Conversation

@groeneai

@groeneai groeneai commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reading a File source with rename_files_after_processing set now requires the WRITE ON FILE grant on top of READ ON FILE, on the initiator for fileCluster: the setting renames the files a SELECT has read, which is a write to the source, and it used to happen for anyone who could read them. A query relying on it now needs GRANT WRITE ON FILE. A per-query renaming rule is also no longer cached by a Filesystem database, where it could make an unrelated later query rename files, or be dropped silently.

Description

Reported privately; no public issue to link. antonio2368 asked for a separate public pull request with himself assigned.

A user granted only CREATE TEMPORARY TABLE ON *.* and READ ON FILE is refused INSERT INTO FUNCTION file(...), yet this renamed it:

SELECT * FROM file('victim.csv', 'CSV', 'x UInt8')
SETTINGS rename_files_after_processing = 'processed_%a';

Root cause. ITableFunction::checkSourceAccess picks the privilege from is_insert_query alone, so a SELECT is authorized with READ, while the fs::rename happens later, in StorageFileSource::beforeDestroy. The mutation is per reader, in a storage that can outlive the query, so the checks go where it happens:

  • StorageFile::read requires WRITE when the renamer is armed. It is the unique gate for StorageFileSource, so it covers file, url('file://...'), both database engines and the fileCluster workers.
  • DatabaseFilesystem::getTableImpl neither reads nor writes the table cache while the setting is set. On master a DESCRIBE with it armed a cached table, so a later unrelated query renamed the file; an entry cached without the rule dropped it silently. Both have their own arms.
  • The fileCluster initiator is authorized from updateBeforeRead and from getTaskIteratorExtension, which a distributed INSERT ... SELECT reaches without the former.

Behaviour change. A SELECT, or a plan-building EXPLAIN (PLAN, PIPELINE), on a File source with the setting now needs WRITE ON FILE, fileCluster on the initiator. Where the rule is the query's own, the shared table is also built from that query's settings, so a sub-query-local schema-inference setting on such a reference is not honoured. The category, and the issue below, are at @ PedroTadim's request in #117895 (comment).

Pre-existing, not fixed here. The worker-side check evaluates whatever credentials the secondary query carries, as every *Cluster source grant does. The cache's hit path runs no source check, so READ ON FILE is unenforced for a cached table.

Related: #111402
Related: #118042

Validation

enable_read_write_grants is not a precondition for the repro: it is consulted when formatting and serializing grants, never when enforcing them.

The new test was validated on a server carrying the tests/config/install.sh overlay: without it the access-control improvements are not enforced, so such a test can pass for the wrong reason.

It fails on pristine master and passes with the change. On master, file, url('file://'), fileCluster, EXPLAIN PIPELINE and a distributed INSERT ... SELECT all rename; an armed cache entry makes both an unprivileged user's and the owner's plain SELECT rename; an unarmed entry silently drops the rename for both. EXPLAIN PLAN renames nothing but is refused too, so no plan-building EXPLAIN needs fewer privileges than the query it explains.

Eight mutations, one per check and one per guard direction, give eight pairwise-distinct sets of failing arms over all 28 pairs, six arms reddening under exactly one. Either initiator gate alone refuses the plain fileCluster read, so only a ninth removing both reddens it; removing one reddens exactly the arm the other cannot reach.

--test-runs 50 passes 50/50, and again at --jobs 8, so no no-parallel tag; both distributed-insert arms are also green at each value of parallel_distributed_insert_select. Tagged no-replicated-database: that mode installs a replicated access storage whose serialization round trip widens GRANT READ ON FILE to READ and WRITE (issue 111402), so no denial would fire.

Eighteen existing tests re-run green: both that set this setting, both that exercise the Filesystem cache, all six URL-database tests, the four policing setting descriptions, and four on the cluster and task-iterator paths, one covering distributedWriteFromClusterStorage with a fileCluster source. Five more there need a Keeper, an S3 endpoint or a second listener, and fail identically without the change.


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

Version info

  • Backported to: 26.8.3.55, 26.7.7.40, 26.6.5.66, 26.3.33.8

groeneai and others added 3 commits September 2, 2026 16:33
A user holding only READ ON FILE could rename any file it could read under
user_files by adding SETTINGS rename_files_after_processing=... to a SELECT
from the file table function. The same user is correctly refused an explicit
INSERT INTO FUNCTION file(...) with "necessary to have the grant WRITE ON
FILE", so the grant model does withhold writes from it; the read path simply
performed the fs::rename with no privilege check.

ITableFunction::checkSourceAccess derives the required privilege from
is_insert_query alone, so a SELECT is authorized with READ. The renaming rule
is then armed on the storage and the rename runs from
StorageFileSource::beforeDestroy, whose only guards are path confinement and a
no-clobber existence check. Authorization is therefore per query at resolution
time while the mutation is per reader, inside a storage whose lifetime can
outlive the query that armed it, and on a node the user may not have
authenticated to. A single resolution-time check is not a check on the
mutation, so this adds three checks on the paths that can mutate:

- StorageFile::read requires WRITE on the source when the renamer is armed.
  This is complete by construction rather than by enumerating callers:
  beforeDestroy runs only from ~StorageFileSource, which is constructed at
  exactly one site inside ReadFromFile::initializePipeline, itself constructed
  at exactly one site inside StorageFile::read. It therefore covers file(),
  url('file://'), both database engines and the fileCluster workers, whether
  the storage came from a cache or not, and it uses the reading query's own
  context.
- DatabaseFilesystem::getTableImpl neither reads from nor writes to the table
  cache while the setting is set. Previously a DESCRIBE carrying the setting
  left an armed table in that cache, so a later unrelated query renamed the
  file under a second user's authority; conversely a table already cached
  without the rule made the setting a silent no-op. The guard is symmetric
  because either half alone leaves one of those two defects.
- StorageFileCluster::updateBeforeRead authorizes the fileCluster initiator.
  Without a cluster secret the secondary queries authenticate as the cluster's
  configured user, so a worker-side check alone does not constrain the user who
  issued the query.

Nothing under src/TableFunctions/ changes, and structure resolution (DESCRIBE,
CREATE TABLE ... AS file(...)) is unaffected because it builds no reader and
cannot rename.

The File table engine is not a carrier: registerStorageFile constructs its
CommonArguments with an empty rename_after_processing, and that is the sole
input to the only site that arms the renamer.

access_control_improvements.enable_read_write_grants is not a precondition for
the defect. It is read only when formatting and serializing grants, never on
the enforcement path, which is why the bypass reproduces on a stock server.

The new test is tagged no-replicated-database because a replicated access
storage widens GRANT READ ON FILE to both READ and WRITE across an entity
serialization round trip, which would make every denial hold for the wrong
reason. See ClickHouse#111402, whose fix
is not merged yet.
Three arms in `05057_file_rename_after_processing_write_grant`. No source
change: the three checks are unmodified.

A `URL('file://')` database is a carrier of the defect in its own right, and it
had no arm. It resolves through its own path: `makeURLTableDelegate` builds the
delegate on a `Context::createCopy` that overrides only
`parallel_replicas_for_cluster_engines`, so the renaming rule survives and arms
the storage, and the read then reaches the gate through
`StorageURLDatabaseTable::read`, which forwards to the nested storage with the
reading query's own context. Measured rather than argued: on the unfixed server
a user holding only `READ ON FILE` renames the file this way, and the arm is
refused with `WRITE ON FILE` once the check is in place. Reverting the
`StorageFile::read` check reddens this arm, which is what shows it measures the
gate and not merely the path. These tables are never cached, so the
`DatabaseFilesystem` cache change has no counterpart to make here.

A `fileCluster` read that does not set the option must keep working for a user
holding only `READ ON FILE`. Without this arm the initiator check could be made
unconditional and nothing in the tree would notice, because the nine
pre-existing tests calling `fileCluster` all run as the full-access default
user, and the only other `fileCluster` reference here is a `DESCRIBE`, which
builds no reader and never reaches `StorageFileCluster::updateBeforeRead`.

A `fileCluster` read by a user who does hold `WRITE ON FILE` must still rename.
The initiator check throws before any worker is contacted, and the worker
storage is built independently from the worker's own settings, so if the option
stopped being forwarded or the worker stopped arming the renamer, every other
`fileCluster` arm would still report `WRITE ON FILE` and an intact file and look
correct.

Each of the two `fileCluster` arms is reddened by exactly one mutation and by no
other, so both are load-bearing rather than decorative.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ationale

Text and test only. The three access checks are unmodified, and the only `src/`
change is one prose sentence in a `DECLARE` doc string.

The sentence added to `rename_files_after_processing` claimed that a query which
sets the option requires `WRITE ON FILE`. That over-claims: the check lives in
`StorageFile::read`, which structure resolution never reaches, and
`05057_file_rename_after_processing_write_grant` asserts as much by running both
`DESCRIBE` forms with the option set as a user holding only `READ ON FILE` and
expecting them to succeed. A `DECLARE` doc string is the source of truth for the
generated settings reference, so the claim would have shipped to users as
documentation of an access-control rule. It now scopes the requirement to reads
and states the `DESCRIBE` case explicitly.

The `no-replicated-database` rationale stated the inverted consequence. It said
the grant widening would make the denials below hold for the wrong reason, which
describes a false pass. The opposite is true: the reader would hold `WRITE ON
FILE`, so none of the denials would fire and the test would fail. The tag
prevents a false failure, not a false pass. This also corrects the same inverted
sentence in the message of commit 8f0bf05, which cannot be amended.

The two structure-resolution arms were the only ones not asserting the
no-side-effect half, so a rename by the second `DESCRIBE` would have gone
unobserved while this change claims structure resolution cannot rename. They now
assert the file is still in place afterwards.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

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

Three rounds by an independent model plus my own cold pass over the resulting code each round: 13
findings, 9 AGREEd and fixed, 3 DISAGREEd, 1 nit noted below. The fixes added the missing
fileCluster and URL-database test arms and the two no-setting arms that pin the guards, and
corrected three statements that over-claimed the new requirement: the description now names only the
plan-building EXPLAIN forms, and the setting's documentation and the no-replicated-database
rationale are no longer wrong about structure resolution, which still needs only READ ON FILE.

Nit noted rather than fixed: that same sentence says structure resolution happens "without reading"
the file, which is imprecise when the structure is inferred rather than given, since inference does
open and consume the file. It never builds the reader that renames, so the grant requirement it
documents is correct. Better wording, if you want it pushed: "DESCRIBE does not build the query's
data-reading pipeline and therefore requires only READ ON FILE".

DISAGREE, with evidence. The changelog category was challenged as Critical Bug Fix: the reporting
reviewers scored this P4, since the rename target stays under the path policy the feature already
applies, an existing file cannot be clobbered (FILE_ALREADY_EXISTS), and nothing becomes readable
that was not readable before. I do not self-assign that category, and the description invites the
relabel. The other two were my own nits: the first commit message does not backtick literal names
(correcting it needs an amend, which the repository forbids), and one regression test named in my
plan was swapped for a more relevant one after it failed identically on the unpatched base binary
for an unrelated reason.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b58a884]

Summary: ✅


AI Review

Summary

This PR closes the main unauthorized rename paths by requiring WRITE ON FILE when rename_files_after_processing is set, but DatabaseFilesystem still has two unresolved memoization bugs. One can still bypass the new write check under SETTINGS enable_analyzer = 0, and the other resolves Filesystem tables with the wrong local settings once the rename rule is inherited from the outer query. Verdict: request changes.

Findings

❌ Blockers

  • [src/Databases/DatabaseFilesystem.cpp:181] The per-query Filesystem memo still falls back to table_function_results[bare_key] through Context::executeTableFunction. Under SETTINGS enable_analyzer = 0, an earlier explicit file('<absolute path>') in the same query can seed that bare-key entry without rename_files_after_processing, and this call then reuses it for fsdb.\x.csv` SETTINGS rename_files_after_processing = .... The reused StorageFilehas an emptyfile_renamer, so the read is neither denied for missing WRITE ON FILEnor renamed. Suggested fix: give thisDatabaseFilesystempath a memo key that cannot reuse bare-key compatibility entries, or split the compatibility fallback out ofContext::executeTableFunctionand let this caller opt out; add a regression mixing explicitfile('')withfsdb.`x.csv`underSETTINGS enable_analyzer = 0`.
  • [src/Databases/DatabaseFilesystem.cpp:181-182] Reusing query_context as the execution context when the rename rule is inherited from the outer query makes the cache key and the table construction use the same settings object. Any local settings that change StorageFile resolution (schema_inference_make_columns_nullable, format/schema-inference settings, and similar) are dropped, so a subquery can resolve the wrong column types or format behavior as soon as the outer query sets rename_files_after_processing. Suggested fix: separate the memo key context from the execution context so reuse is keyed by the outer query while table_function->execute still runs with the resolving context_; add a regression around schema_inference_make_columns_nullable = 0.
Tests
  • ⚠️ tests/queries/0_stateless/05057_file_rename_after_processing_write_grant.sh does not cover the enable_analyzer = 0 mixed file()/Filesystem case, so the remaining WRITE ON FILE bypass is untested.
  • ⚠️ The same test also does not pin the inherited-rename/local-schema-setting case, so the wrong-type regression can pass unnoticed.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Remove the bare-key reuse path for armed Filesystem reads so the new WRITE ON FILE requirement cannot be bypassed under enable_analyzer = 0.
  • Split the per-query memo key from the execution context so rename_files_after_processing sharing does not erase per-reference schema/format settings.

LLVM Coverage Report

⚠️ No coverage measurement for commit b58a884: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

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

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @antonio2368 @nikitamikhaylov, could you review this? A SELECT from file() with rename_files_after_processing set renamed the files it read with no privilege check, so READ ON FILE alone was enough to move files under user_files; the requirement is now enforced in StorageFile::read, the only place a renaming reader is built, plus the fileCluster initiator and the Filesystem database cache. @antonio2368, you asked to be assigned: that field is not one I can set from a fork, so please assign yourself.

Comment thread src/Storages/StorageFileCluster.cpp Resolved
@PedroTadim PedroTadim self-assigned this Sep 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Object file sizes

10 object files changed (+49.02 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageFileCluster.cpp.o 346.41 KiB 371.27 KiB +24.86 KiB (+7.18%)
src/CMakeFiles/dbms.dir/Storages/StorageFile.cpp.o 1.08 MiB 1.10 MiB +21.25 KiB (+1.92%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +5.0 s (+9%) in total before that adjustment.

Job report

groeneai and others added 4 commits September 3, 2026 17:58
`StorageFileCluster::updateBeforeRead` runs only from `IStorageCluster::read`, so a distributed
`INSERT ... SELECT` never reached it: `StorageDistributed::distributedWriteFromClusterStorage` and
`InterpreterInsertQuery::distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage` obtain
the task iterator by calling `getTaskIteratorExtension` directly. With
`parallel_distributed_insert_select`, which is 2 by default, a user holding only `READ ON FILE` could
therefore still have the workers rename the files:

    INSERT INTO dist SELECT * FROM
        fileCluster('test_shard_localhost', 'victim.csv', 'CSV', 'x UInt8')
    SETTINGS rename_files_after_processing = 'processed_%a';

That returned no error, renamed the file and inserted the rows. Without a cluster secret the
worker-side check evaluates the cluster's configured user, so the initiator is the only node where
the issuing user's grants are known.

The check therefore moves into a function called from both `updateBeforeRead` and
`getTaskIteratorExtension`, which is the one entry point all three task-iterator paths share.
`updateBeforeRead` stays: it also refuses a plan-building `EXPLAIN`, which builds no pipeline and so
never creates the task iterator.

Found by the automated reviewer on the pull request.

Co-Authored-By: Claude Opus 5 <[email protected]>
With the check also running from `getTaskIteratorExtension`, every arm that reads through
`fileCluster` is refused by either gate, so removing `updateBeforeRead` alone reddened nothing and
that gate was untested. `EXPLAIN PLAN optimize = 0` is the case that separates them: the plan is
built, so `IStorageCluster::read` runs, but it is never optimized and no pipeline is initialized, so
the task iterator is never created. Measured: removing `updateBeforeRead` reddens exactly that arm,
removing the `getTaskIteratorExtension` check reddens exactly the distributed `INSERT ... SELECT`
arm, and removing both reddens the plain `fileCluster` read as well.

The destination table is also emptied before the authorized distributed insert, so its row count is
that arm's own: with the shared counter, a regression that let the refused insert through showed up
as a failure in the arm after it rather than in the arm where it happened.

Co-Authored-By: Claude Opus 5 <[email protected]>
…arms

The runner randomizes the setting to 0 in the automatic-parallel-replicas mode, which routes an
`INSERT ... SELECT` through `IStorageCluster::read` instead of straight to the task iterator. Both
arms produce the same output either way, measured at 0, 1 and 2, so this does not fix a failure: it
keeps the arms exercising the route they exist to cover, which would otherwise be dropped silently in
that leg.

Co-Authored-By: Claude Opus 5 <[email protected]>
The sentence said structure is resolved "without reading it", which is wrong when the structure is
inferred: `DESCRIBE` then opens and reads the file. What it does not do is build the data-reading
pipeline, and that is what performs the rename, so `READ ON FILE` alone remains the correct
requirement. This corrects the wording introduced in a8fe267 and refined again here; the
access-control claim itself is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Databases/DatabaseFilesystem.cpp Resolved
…m database

Keeping a table that carries `rename_files_after_processing` out of the
`Filesystem` database cache is right across queries, but it also stopped two
references to one such table inside a single query from sharing it. Each
reference then built its own `StorageFile` with its own `readers_counter`,
`was_renamed` and `paths`, so whichever reader finished first renamed the file
and the other one failed to open it:

    SELECT (SELECT count() FROM fsdb.`x.csv`), count() FROM fsdb.`x.csv`
    SETTINGS rename_files_after_processing = 'processed_%a'

returned `Code: 107, FILE_DOESNT_EXIST` where master returned rows. Before this
PR the cross-query cache happened to provide that intra-query sharing too.

Such a table is now resolved through the query context's table function memo,
which is where `file()` itself is resolved (`QueryAnalyzer::resolveTableFunction`),
so all the references of one query share a single table and the rename happens
once, after the last reader. The memo dies with the query, so nothing is shared
with a later one and the cross-query guard is unchanged. Access is unaffected:
`StorageFile::read` runs per read, so the `WRITE ON FILE` check still fires for
every reference.

`Context::getOrCacheStorage`, the other per-query storage cache, cannot serve
this: it pins a name to a UUID and only inserts when the storage has one, and a
`Filesystem` table has no UUID.

A `URL('file://')` database still splits the storage the same way. That is
pre-existing on master and not narrowed by this change: `DatabaseURL` never
cached, and it wraps its delegate in a fresh `StorageURLDatabaseTable` per
resolution, so the memo would not reach it.
The memo that now shares an armed `Filesystem` table between the references of
one query keys on the changed settings of the context that resolves it, so two
references agreeing on `rename_files_after_processing` but differing in an
unrelated local setting still received separate tables:

    SELECT (SELECT count() FROM fsdb.`x.csv` SETTINGS max_threads = 2),
           count() FROM fsdb.`x.csv`
    SETTINGS rename_files_after_processing = 'processed_%a'

returned `Code: 107, FILE_DOESNT_EXIST` where master returned rows, because the
scalar subquery renamed the file under the outer read.

When the rule is the query's own, the query context resolves the table, so its
changed settings are the key for every reference and a local change elsewhere
cannot split them. A reference carrying a different rule than the query keeps
resolving through its own context, and so keeps the rule it asked for.

Two references that disagree about whether the rule applies at all still read
separate tables, and the one that asked renames. That is deliberate: a
reference inheriting a rule it did not set is the cached-arming bypass the
first commit of this pull request closes. The `file` table function splits the
same way there, on master too.
Comment thread src/Databases/DatabaseFilesystem.cpp Resolved
@PedroTadim

PedroTadim commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

🕵️

Verified the mechanism and I agree with the placement. file_renamer is armed once at construction from args.rename_after_processing (StorageFile.cpp:1380) and the fs::rename happens in StorageFileSource::beforeDestroy (:1630-1646), gated only on !file_renamer.isEmpty(), the uncaught-exception check and the reader counter — nothing between resolution and that rename consults access rights. So READ ON FILE plus the setting really is an unauthorized write while INSERT INTO FUNCTION file(...) is refused, and checking in StorageFile::read is the right single gate: structure resolution builds no reader, and the reading query's context is what matters since the storage can outlive its creator. The fileCluster double-check is justified too, not belt-and-braces — a distributed INSERT ... SELECT reaches getTaskIteratorExtension without going through IStorageCluster::read.

Three things before merge.

Please do switch to Backward Incompatible Change. A SELECT, or a plan-building EXPLAIN, that works today starts failing after upgrade for anyone holding READ but not WRITE ON FILE. pr-bugfix means no backport by default, so the surprise lands on an upgrade rather than a patch — which is exactly the case the category exists for.

The DatabaseFilesystem hunk is doing two independent things. Bypassing the cache when the rule is armed is the security-relevant part and is clearly correct. Memoising through executeTableFunction so every reader in one query shares the readers_counter is a separate correctness fix for rename semantics. Both are described, but the rule_is_the_query_setting ternary is subtle enough that I'd like a comment on what goes wrong when the rule came from a sub-context rather than the query context. If it is easy to split, the security fix becomes trivially reviewable on its own.

Also, the note that a DESCRIBE with the setting armed would cache a table on master, so a later unrelated query renamed the file — if that is demonstrable it is a second bug and deserves its own test. The docs line is right that DESCRIBE needs only READ (it builds no pipeline), but it should not be poisoning the cache either.

One of the "pre-existing, not fixed here" items is worth its own issue rather than a note: the cache hit path runs no source check, so READ ON FILE is unenforced for a cached Filesystem table. That is a live gap, not a wart.

@PedroTadim PedroTadim assigned antonio2368 and unassigned PedroTadim Sep 4, 2026
= query_context->getSettingsRef()[Setting::rename_files_after_processing].value
== context_->getSettingsRef()[Setting::rename_files_after_processing].value;

return query_context->executeTableFunction(

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 query-local memo can still hand an armed Filesystem read the wrong StorageFile. Context::executeTableFunction(..., execution_context) falls back from the settings-hash key to the bare AST key (src/Interpreters/Context.cpp:3413-3418). Under enable_analyzer = 0, an earlier explicit file('<absolute path>') in the same query seeds that bare entry via the legacy overload, and this call then reuses it for fsdb.\x.csv` SETTINGS rename_files_after_processing = 'processed_%a'` when both resolve to the same absolute path.

In that case the reused storage was built without rename_files_after_processing, so StorageFile::read sees an empty file_renamer: the Filesystem arm is not denied for missing WRITE ON FILE, and the requested rename is silently dropped. That is the same unarmed-cache bypass this PR is fixing across queries, just via table_function_results inside one query. Please give DatabaseFilesystem a memo path that cannot fall back to table_function_results[bare_key] (or otherwise isolate it from the legacy bare-key cache), and add a regression that mixes file('<absolute path>') with fsdb.\...`underSETTINGS enable_analyzer = 0`.

@ PedroTadim asked for this on the pull request: the ternary that picks the
context handed to `Context::executeTableFunction` is subtle, and the code did
not say what the other branch is for.

`Context::executeTableFunction` builds the table with the context it is given
and keys its per-query memo on that context's changed settings. Handing it the
query's context is therefore what makes every reference of one query share a
table, and share the reader counter that decides when the rename happens.

A rule a sub-query set locally is not among the query's settings, so resolving
such a reference through the query's context would build the table from a
different value of `rename_files_after_processing`, usually the empty one: it
would rename by a rule nobody asked for, or not rename at all.
The arm asserting that an armed `DESCRIBE` leaves nothing behind in a
`Filesystem` database's table cache was headed "a Filesystem database does not
cache the rename rule for later queries", which does not say which query arms
the cache. On pristine master both of its cases print `renamed`: the `DESCRIBE`
itself renames nothing, and the plain `SELECT` that follows it, carrying no
setting of its own, renames the file.
@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 4, 2026
@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 7, 2026
Merged via the queue into ClickHouse:master with commit e8673a8 Sep 7, 2026
175 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 7, 2026
PedroTadim added a commit that referenced this pull request Sep 7, 2026
Cherry pick #117895 to 26.6: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
PedroTadim added a commit that referenced this pull request Sep 7, 2026
Cherry pick #117895 to 26.3: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
PedroTadim added a commit that referenced this pull request Sep 7, 2026
Cherry pick #117895 to 26.7: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
robot-clickhouse added a commit that referenced this pull request Sep 7, 2026
robot-clickhouse added a commit that referenced this pull request Sep 7, 2026
robot-clickhouse added a commit that referenced this pull request Sep 7, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 7, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #117895 to 26.8: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #117895 to 26.7: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
clickhouse-gh Bot added a commit that referenced this pull request Sep 7, 2026
Backport #117895 to 26.6: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
antonio2368 added a commit that referenced this pull request Sep 8, 2026
Backport #117895 to 26.3: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
qoega pushed a commit to qoega/ClickHouse that referenced this pull request Nov 19, 2026
`rename_files_after_processing` renames the files a `SELECT` from `file()`
has read. ClickHouse#117895 authorizes that write by requesting `WRITE` on the `FILE`
source in `StorageFile::read` and on the `fileCluster` initiator, but the
readonly gate in `ContextAccess::checkAccessImplHelper` is a deny-list of
access types that does not contain `WRITE`. So a read-only session
(`readonly = 2`, which every HTTP GET request implies) holding
`WRITE ON FILE` renamed the files it read in `user_files` (measured on
master and on 26.10.2.103).

`WRITE` cannot join the deny-list: it also authorizes `BACKUP` destinations,
which `readonly` is documented not to restrict, and reads from an `S3`
database. So the two identical checks become one helper,
`StorageFile::checkAccessForRenamingFiles`, which keeps the `WRITE` check
and then refuses a read-only session with the gate's own `READONLY` error,
including its HTTP GET hint. The grant check stays first, so a user without
the grant still gets `ACCESS_DENIED`; `full_access` is exempt as in the
gate. `DESCRIBE` builds no reader and stays allowed.

Related: ClickHouse#132330
Related: ClickHouse#117895

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. groeneai-origin-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-backward-incompatible Pull request with backwards incompatible changes 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.

5 participants