Repository navigation
Require the WRITE ON FILE grant when rename_files_after_processing is set - #117895
antonio2368 merged 13 commits into
Conversation
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]>
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 Nit noted rather than fixed: that same sentence says structure resolution happens "without reading" DISAGREE, with evidence. The changelog category was challenged as |
|
Workflow [PR], commit [b58a884] Summary: ✅
AI ReviewSummaryThis PR closes the main unauthorized rename paths by requiring Findings❌ Blockers
Tests
Final VerdictStatus: Minimum required actions:
LLVM Coverage Report |
|
cc @antonio2368 @nikitamikhaylov, could you review this? A |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+49.02 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units11 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. |
`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]>
…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.
…rocessing-write-grant
|
🕵️ Verified the mechanism and I agree with the placement. Three things before merge. Please do switch to The Also, the note that a 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 |
| = query_context->getSettingsRef()[Setting::rename_files_after_processing].value | ||
| == context_->getSettingsRef()[Setting::rename_files_after_processing].value; | ||
|
|
||
| return query_context->executeTableFunction( |
There was a problem hiding this comment.
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.
Cherry pick #117895 to 26.6: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
Cherry pick #117895 to 26.3: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
Cherry pick #117895 to 26.7: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
…ame_files_after_processing` is set
…ame_files_after_processing` is set
…ame_files_after_processing` is set
…ame_files_after_processing` is set
Backport #117895 to 26.8: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
Backport #117895 to 26.7: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
Backport #117895 to 26.6: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
Backport #117895 to 26.3: Require the `WRITE ON FILE` grant when `rename_files_after_processing` is set
`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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reading a
Filesource withrename_files_after_processingset now requires theWRITE ON FILEgrant on top ofREAD ON FILE, on the initiator forfileCluster: the setting renames the files aSELECThas 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 needsGRANT WRITE ON FILE. A per-query renaming rule is also no longer cached by aFilesystemdatabase, 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 *.*andREAD ON FILEis refusedINSERT INTO FUNCTION file(...), yet this renamed it:Root cause.
ITableFunction::checkSourceAccesspicks the privilege fromis_insert_queryalone, so aSELECTis authorized withREAD, while thefs::renamehappens later, inStorageFileSource::beforeDestroy. The mutation is per reader, in a storage that can outlive the query, so the checks go where it happens:StorageFile::readrequiresWRITEwhen the renamer is armed. It is the unique gate forStorageFileSource, so it coversfile,url('file://...'), both database engines and thefileClusterworkers.DatabaseFilesystem::getTableImplneither reads nor writes the table cache while the setting is set. On master aDESCRIBEwith 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.fileClusterinitiator is authorized fromupdateBeforeReadand fromgetTaskIteratorExtension, which a distributedINSERT ... SELECTreaches without the former.Behaviour change. A
SELECT, or a plan-buildingEXPLAIN(PLAN,PIPELINE), on aFilesource with the setting now needsWRITE ON FILE,fileClusteron 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
*Clustersource grant does. The cache's hit path runs no source check, soREAD ON FILEis unenforced for a cached table.Related: #111402
Related: #118042
Validation
enable_read_write_grantsis 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.shoverlay: 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 PIPELINEand a distributedINSERT ... SELECTall rename; an armed cache entry makes both an unprivileged user's and the owner's plainSELECTrename; an unarmed entry silently drops the rename for both.EXPLAIN PLANrenames nothing but is refused too, so no plan-buildingEXPLAINneeds 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
fileClusterread, so only a ninth removing both reddens it; removing one reddens exactly the arm the other cannot reach.--test-runs 50passes 50/50, and again at--jobs 8, so nono-paralleltag; both distributed-insert arms are also green at each value ofparallel_distributed_insert_select. Taggedno-replicated-database: that mode installs a replicated access storage whose serialization round trip widensGRANT READ ON FILEtoREADandWRITE(issue 111402), so no denial would fire.Eighteen existing tests re-run green: both that set this setting, both that exercise the
Filesystemcache, all sixURL-database tests, the four policing setting descriptions, and four on the cluster and task-iterator paths, one coveringdistributedWriteFromClusterStoragewith afileClustersource. 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
26.8.3.55,26.7.7.40,26.6.5.66,26.3.33.8