Repository navigation
Add user_files_policy server setting for custom disks in user_files directory - #100173
alexey-milovidov wants to merge 277 commits into
Conversation
|
Workflow [PR], commit [cd05184] Summary: ❌
AI ReviewSummaryThe PR adds The new path representation was traced through scalar Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Correct partial-read rollback and the isolation collector, settle or explicitly track the deferred source-access/shared-write issues, document the mixed-cluster requirement, and obtain the targeted integration result on the final merge. |
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
When multiple disks in the `user_files_policy` volume have overlapping roots (for example `/mnt/user_files/` and `/mnt/user_files/archive/`), absolute-path resolution previously bound to the first disk that matched the path prefix. With first-match semantics that depends on disk order in config, an absolute path under the nested root gets captured by the parent disk and reads/writes are routed to the wrong backend. Pick the disk with the longest matching prefix in both `splitUserFilesAbsolutePath` (used by `StorageFile` for read/write/exists) and the `file()` function so the more specific disk wins. Address review: #100173 (comment) #100173 (comment)
|
@groeneai, fix "Logical error: Primary key type mismatch, expected A, got B. (STID: 3436-4175)" and send a separate PR. |
Resolve the conflict in `StorageFile.cpp` with the single-file parallel read (`split_file`) from master: keep the disk-aware read branch for `user_files_policy` and apply master's split-file version checks to the plain local branch. Splitting a single file is disabled under `user_files_policy`, because it `stat`s and reads the file by its local path instead of through `IDisk`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ar `file` without a policy The legacy branch of `FunctionFile` (no `user_files_policy`) had switched the root used for the access check from `fs::canonical(user_files_path)` to its lexical spelling as a side effect of an earlier refactoring. Under a symlinked `user_files_path` this rejected physical absolute paths that were accepted before. Restore the code from master. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ptor `ReadSettings::disableCaches` does not disable `OpenedFileCache`, which the `pread`, `pread_threadpool` and `io_uring` local read methods use and which is keyed by the path alone. After a file is replaced under the same name, a new read could reuse the descriptor of the old inode kept open by a concurrent reader. `getUserFilesDiskReadSettings` now always selects `LocalFSReadMethod::read`, which opens a fresh descriptor, as the reader of a plain `user_files_path` does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 I merged current |
Resolve the conflict in `StorageFileSource::generate`: master keeps the read buffer of a split file between its buckets (`if (!read_buf || split_file)` and `else if (!read_buf)` around `createReadBuffer`); apply that to the plain `user_files_path` branch. A file is never split with a `user_files_policy` volume. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ser_files_policy` files `LocalObjectStorage::patchSettings` replaced every local read method with `pread`, which shares descriptors by path through `OpenedFileCache`, so a `local_blob_storage` disk with plain metadata undid `getUserFilesDiskReadSettings`, and a read after the file was replaced under the same name could reuse the descriptor of the old inode. `read` is synchronous like `pread`, so keep it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`loadFiles` normalized the path with `lexically_normal` after the containment check had validated the original spelling. Removing `..` before resolving a symlink can select a different file, so `a/../b/file.log` with `a` pointing inside and `b` pointing outside the `user_files_policy` disk passed the check and then probed the outside file. Normalize the path once in the constructor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 All review threads are resolved. I merged current |
|
🕵 Status: the last CI run skipped the full suite only because of the review-threads gate. Two threads are open again, and each needs a human decision rather than a code change in this PR:
Please decide whether these should be handled in follow-up PRs (then the threads can be resolved) or in this one. |
Resolve a conflict in `YAMLRegExpTreeDictionarySource.h`: keep master's `[[nodiscard]]` on `getLastModification` and this PR's `checkFilePath`.
|
🕵 I merged current |
Resolve conflicts in `StorageFile`: keep both the new `format_settings_` argument of `FilesIterator` from master and the `user_files_volume_` argument of this PR; pass `std::nullopt` format settings in `StorageFileCluster` as master does. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…include `cachesObjectMetadata` and the overrides in `SubdirectoryDiskWrapperDirectoryIterator` trip `modernize-use-nodiscard`; after merging master `Disks/IDisk.h` was included twice in `Storages/ObjectStorage/Local/Configuration.cpp`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `FileLog` files Discovery and watcher updates called `is_regular_file` on a found file before `isDataFileAllowed`, so a child symlink pointing outside the policy root could disclose whether its target exists, or fail `CREATE TABLE` with `Too many levels of symbolic links` for an outside loop. Check the boundary first. The child-symlink regression now also covers a missing and a looping outside target. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…edRocksDB` without a policy Without `user_files_policy`, an explicit `rocksdb_dir` was resolved against and checked against `fs::canonical(user_files_path)`. The lexical check against the configured spelling rejected a physical path beneath a symlinked `user_files_path`, so an existing table could fail to attach after an upgrade. Restore the canonical root in the constructor, `truncate` and `create` (the configured spelling is accepted too); the policy branch is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d]]` `modernize-use-nodiscard` failed the `arm_tidy` builds on the override in `MetadataStorageWithPathWrapper`. Mark the other overrides the same way. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100173&sha=8a97d6414f8f3b8993e4ca4612924723d4b32e73&name_0=PR&name_1=Build%20%28arm_tidy%2C%202%2F4%29 #100173 Co-Authored-By: Claude Fable 5.2 <[email protected]>
The description used a `:::note` admonition, which `05621_documentation_no_docusaurus_syntax` rejects, and links to the old `/sql-reference/table-functions/...` routes. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100173&sha=8a97d6414f8f3b8993e4ca4612924723d4b32e73&name_0=PR&name_1=Fast%20test #100173 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Fixed the two CI failures of the last run and merged current
The |
| if (!path_to_archive.empty()) | ||
| throw Exception(ErrorCodes::BAD_ARGUMENTS, "Archive syntax is not supported with user_files_policy"); | ||
|
|
||
| res.paths = getPathsListOnDisk(filename, user_files_volume, res.total_bytes_to_read); |
There was a problem hiding this comment.
[Blocker] Check source access before resolving policy file paths
This runs during TableFunctionFile::parseFirstArguments, before ITableFunction::execute or getActualTableStructureWithAccess checks READ ON FILE. As a user with CREATE TEMPORARY TABLE but no file grant, run SELECT * FROM file('probe/data.csv', 'CSV', 'x UInt64'): an absent probe reaches the normal ACCESS_DENIED, while probe -> /outside throws DATABASE_ACCESS_DENIED from validateDiskRelativePathBoundary during parsing. The same query therefore reveals protected filesystem state without the source privilege. Wildcard inputs also enumerate the policy backend before denial.
The same parsing path is reachable through array sources, fileCluster, and the url delegate for file://. Defer filesystem-dependent resolution and glob expansion until the appropriate source check has succeeded, and add denied-user SELECT/DESCRIBE coverage. An unconditional READ check in FileSource::parse would incorrectly reject write-only inserts and engine-authorized creation, so those callers need to retain their respective access contracts.
There was a problem hiding this comment.
🕵 I am not changing this in this PR, and I am leaving the thread open for a human decision.
The ordering is not introduced here: on master, StorageFile::FileSource::parse already calls getPathsList from TableFunctionFile::parseFirstArguments, before ITableFunction::execute or getActualTableStructureWithAccess checks the source grant. That function stats the path, expands globs on the filesystem, and throws DATABASE_ACCESS_DENIED from checkCreationIsAllowed for a symlink leading outside user_files_path, while an absent path reaches the later ACCESS_DENIED. The policy branch (getPathsListOnDisk with validateDiskRelativePathBoundary) reproduces the same behaviour for a disk; it does not add a new way to observe the filesystem.
A fix has to cover both branches, and it cannot be a check inside parse or parseFirstArguments: the same parsing serves INSERT (which needs WRITE, not READ), DatabaseFilesystem (a read is authorized by the grants on the database, and only a write checks the source grant), the url delegate for file:// (the outer function does the check), and ENGINE = File (authorized by TABLE ENGINE). Deferring the path resolution and the glob expansion until after the caller's own check means making FileSource lazy for every one of these callers, which changes the access behaviour of file without user_files_policy too. That belongs in a separate PR against master.
Conflicts: - `programs/docker-init/docker-init.cpp`: master reads the paths with `getEffectiveConfigValue` (server arguments win over the configuration file); kept that and kept skipping `user_files_path` when `user_files_policy` is configured, reading the policy name the same way. - `src/Storages/StorageFileCluster.cpp`: master added a `const std::atomic_bool &` argument to the task callback; kept the `user_files_policy`-aware iterator and adopted the new signature. Co-Authored-By: Claude Fable 5.2 <[email protected]>
`master` removed the unused `chmod` and `supportsChmod` from `IDisk`, so the forwarding overrides in `SubdirectoryDiskWrapper` no longer compile after the merge. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…sDB` directory For a `read_only` table over an explicit `rocksdb_dir`, the factory probed the directory with `fs::exists` before the `FILE` access check, and the required grants depended on the result: `READ` for an existing directory, `READ, WRITE` for a missing one. A user without any `FILE` grant could tell from the access-denied message whether a directory under `user_files` exists. Require the baseline `READ ON FILE` first, and `WRITE` in addition only when the statement could create the directory. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 I merged current
Review threads:
Three threads are open and wait for a human decision: the one above, the |
| if (vec_null_map_to) | ||
| (*vec_null_map_to)[row] = true; | ||
| else | ||
| res_chars.insert(default_result.data(), default_result.data() + default_result.size()); |
There was a problem hiding this comment.
[Blocker] Discard partial output before applying the default
A remote read can return one buffer and then throw while fetching the next. copyData has already appended those bytes to res_chars, and AutoFinalizedWriteBuffer finalizes during unwinding, preserving that prefix. This catch then appends default_result without undoing the partial copy: if the first buffer was abc, file(path, 'fallback') returns abcfallback, and an empty default silently returns the truncated file.
Save the row's initial character offset and restore it before handling the exception/default. The legacy loop has the same omission, so share or apply the rollback there too. Please cover a read that fails after a nonempty chunk; missing-file coverage does not reach this case.
| /// With `user_files_policy`, `user_files_path` is a directory inside the disk of the policy | ||
| /// (possibly on remote storage such as `s3_plain`), installed below via `setUserFilesPolicy`. | ||
| /// In that case it is not a local path, so do not canonicalize or create it here. | ||
| if (server_settings[ServerSetting::user_files_policy].value.empty()) |
There was a problem hiding this comment.
[Major] Apply the policy-path distinction to filesystem isolation
The current CI merge also runs Collector::addDataPaths in programs/server/FilesystemIsolationPaths.cpp, which unconditionally calls addCanonicalPathKey("user_files_path") before this part of startup. With the documented user_files_policy configuration and user_files_path = '/', that collector requests host /, although the value now means the policy disk root. On a Linux host with namespace support, both filesystem_isolation = 'enforce' and 'best_effort' reach planMounts, which rejects host / with BAD_ARGUMENTS, preventing startup.
Skip the host user_files_path entry in that collector when the policy is configured as well; addDisks already collects the disk's host paths. A focused collector regression using a policy and user_files_path = '/' would cover this integration with current master.
Add a new
user_files_policyserver configuration parameter, similar totmp_policy, that lets theuser_filesdirectory live on a custom storage volume, including S3-backed disks. The policy must have exactly one volume containing exactly one disk; when configured, that disk provides the storage for user files, anduser_files_pathis interpreted as a directory inside that disk (/is the disk root; the disk root is used ifuser_files_pathis not configured).file(), theFiletable engine,FunctionFileandDatabaseFilesystemroute globbing, reads, writes, schema inference and truncation through theIDiskinterface when a volume is configured, so a remote backend such ass3_plainworks end to end.Features that fundamentally need a local POSIX path fail closed instead of silently operating on a metadata or ciphertext path:
ATTACH ... FROM,SQLite, thefilesystem()table function, the static HTTPfile://handler,FileLog,EmbeddedRocksDBwith an explicitrocksdb_dir, several dictionary sources,catboostEvaluate,InputFormatErrorsLogger, the local data lakes,rename_files_after_processing, the lazyParquetmaterialization pass and theDistributedformat all reject a policy disk that is not plain local. Archive syntax and partitioned writes are rejected underuser_files_policyon any disk type.Key changes:
user_files_policyinServerSettings, with an XML example and the list of limitationsContextstores theVolumePtrand exposesgetUserFilesVolume,getUserFilesPaths,isUserFilesPathandsetUserFilesPolicySubdirectoryDiskWrapperconfines the policy disk to the directory named byuser_files_pathStorageFilegains disk-based glob matching (listFilesWithRegexpMatchingOnDisk), disk-based reads (disk->readFile) and writes (disk->writeFile), disk-aware existence probes, and symlink-escape checks on the disk-relative pathgetUserFilesPathcaller updated for the disk-backed rootpathStartsWith(path, vector)andfileOrSymlinkPathStartsWith(path, vector)test_user_files_policycovering a local multi-disk, ans3_plainand aDiskEncryptedpolicyThis allows customers to have a "scratch area" for files in ClickHouse Cloud, shared among all replicas.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add a
user_files_policyserver setting to storeuser_fileson a custom disk, including S3-backed disks.Note
Medium Risk
Introduces a new storage-policy-backed path for
user_filesand rewires many read/write and path-validation code paths (including remote disks), which could affect file access semantics and security boundaries if edge cases are missed.Overview
Adds a new server setting
user_files_policythat binds theuser_filesdirectory to a storage policy (enforced to exactly one volume with one disk) and stores the resolvedVolumePtrinContext, with server startup applying it viasetUserFilesPolicy.Updates user-files consumers to become disk-aware when a policy is configured:
file()/StorageFileswitch toIDisk-based globbing, reads, writes, schema inference and truncation (plus new helpers likesplitUserFilesAbsolutePath,userFilesPathExists, and symlink-escape checks), while features that require local POSIX paths (ATTACH ... FROM, SQLite,filesystemtable function, static HTTPfile://, FileLog, several dictionary sources, error logger, etc.) now explicitly reject remoteuser_files_policydisks.Adds integration coverage for local-disk and
s3_plainconfigurations, including globbing, absolute paths, traversal/symlink-escape hardening, write/append/truncate behavior, schema inference, and expected rejections (e.g. partitioned inserts underuser_files_policy).Reviewed by Cursor Bugbot for commit 04b03ad. Bugbot is set up for automated code reviews on this repo. Configure here.
Workflow [PR]
Sync PR [sync-upstream/pr/100173]