Skip to content

URL database: do not probe the filesystem without the read source grant - #113029

Merged
alexey-milovidov merged 5 commits into
masterfrom
url-database-exists-source-access
Aug 9, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
url-database-exists-source-access

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

The URL database engine (added in #111512) probes the local filesystem to answer whether a file:// table exists. EXISTS TABLE requires only the SHOW TABLES privilege — InterpreterExistsQuery answers it from DatabaseCatalog::isTableExist, which lands in DatabaseURL::checkFileURLExists — so a user without the read source grant could tell whether a file exists under user_files. The same probe runs on the resolution path, where it reports FILE_DOESNT_EXIST before the source access of the delegate is checked, which is another way to observe the same thing (DESCRIBE, SELECT).

Now the probe is performed only after the read source grant is confirmed, using the new non-throwing ContextAccess::isGrantedWithFilter and ITableFunction::isSourceAccessGranted. Without the grant the table is claimed to exist, exactly as it is for a remote URL (which is not probed either) and for a path outside of user_files, so an attempt to resolve the table fails with the access error instead of disclosing anything.

New test 04692_url_database_exists_no_source_probe.

Related: #111512

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

A table of the URL database engine no longer discloses whether a local file exists to a user without the read source grant: EXISTS TABLE, which requires only the SHOW TABLES privilege, and the resolution of a table no longer probe the filesystem before the grant is confirmed.

…rant

`EXISTS TABLE` requires only the `SHOW TABLES` privilege, and
`InterpreterExistsQuery` answers it from `DatabaseCatalog::isTableExist`,
which for a `URL` database lands in `DatabaseURL::checkFileURLExists` and
probes the local filesystem. A user without the read source grant could
therefore tell whether a file exists under `user_files`. The same probe also
runs on the resolution path, where it reports `FILE_DOESNT_EXIST` before the
source access of the delegate is checked.

Now the probe is performed only after the read source grant is confirmed,
using the new non-throwing `ContextAccess::isGrantedWithFilter` and
`ITableFunction::isSourceAccessGranted`. Without the grant the table is
claimed to exist, exactly as it is for a remote URL (which is not probed
either) and for a path outside of `user_files`, so an attempt to resolve it
fails with the access error instead of disclosing anything.

Follows up the review of #111512
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ca961fd]

Summary: ✅


AI Review

Summary

This PR fixes the URL database side channel around file:// tables by making EXISTS TABLE and read-side table resolution stop probing the local filesystem until the user has the matching READ ON FILE source grant. The current head also addresses the two earlier inline review findings by deriving the read-grant decision without constructing the delegate and by rejecting file:// resolution before delegate parsing. I did not find any remaining correctness or security issue in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 25/26 (96.15%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 2, 2026
Comment thread src/Databases/DatabaseURL.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 2ca961f - the build was skipped, reused from cache, or predates profile upload.

alexey-milovidov and others added 2 commits August 3, 2026 23:09
…elegate

The review of #113029 pointed
out that `isURLReadGranted` was not probe-free: constructing the `url`
table function parses the delegate's arguments immediately, and for a
`file://` URL `TableFunctionFile::parseFirstArguments` goes through
`StorageFile::FileSource::parse`, which stats the path and enumerates
directory contents before `READ ON FILE` is checked — a timing/resource
side channel that defeats the purpose of the check.

Derive the grant decision directly from the grants instead, without
constructing anything: `checkFileURLExists` only ever probes `file://`
URLs, and the `file` delegate reports an empty URI for source-access
filtering (see `TableFunctionURL::parseArgumentsImpl`), so the delegate's
own check is exactly `isGrantedWithFilter(READ, FILE, "")`, reproduced
here verbatim. The now-unused `ITableFunction::isSourceAccessGranted` is
removed; `ContextAccess::isGrantedWithFilter` stays as the primitive.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113029&sha=cebdc42b01538df822d2da154bb5b51f1d4538d6&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%204%2F4%29 (test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write) and provide a fix in a separate PR. If the fix is already in progress, link it here. The test fails daily across many unrelated PRs and on master, so it is not caused by this PR; no open tracking issue was found. The other red on this run, the Logical error: 'current_version != existing_version' in Stress test (arm_tsan), is tracked in #107501 and is also unrelated.

Comment thread src/Databases/DatabaseURL.cpp Resolved
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

A fix is already in progress and it is mine: #112828 (open). This run is its signature.

The failure here is ClickHouse lost some messages: 97903, that is 97903 of 100000 distinct keys after the broker comes back. kill_nats is docker stop, so the broker shuts down gracefully and answers the outstanding JetStream pull request with 409 Server Shutdown, and the client then closes the subscription. ClickHouse does not notice, because INATSConsumer::isSubscribed only tests that the subscription vector is non-empty, so the re-subscribe path in NATSSource is gated on a predicate that cannot see a dead subscription. The consumer stops for good, and the messages published after the restart are the missing ones. #112828 adds a per-subscription liveness check and consults it in the streaming task.

One correction: an open tracking issue does exist, #96651, a user report against 26.1.2 where DETACH plus ATTACH is the only recovery. #112828 closes it. The closed #39185 is an older, unrelated thing.

Measured breadth over the last 7 days, excluding #112828's own runs: 33 failures across 30 distinct pull requests against 13777 passes, so 0.24 percent of runs. Every failure is on arm_binary, distributed plan, with shard 2/4 carrying 17 of the 33, and no other flavour has failed once. On master there are 2 failures, on 07-30 and 07-31, and none since. Onset is #112464, which restored the suite: the 11 days before it have neither failures nor passes.

#112828 has been open since 07-31 with no review yet.

The current_version != existing_version attribution is right, #107501 is open and unrelated to this.

…ore constructing the delegate

The construction of the `file` delegate observes the filesystem while
parsing its arguments (`StorageFile::FileSource::parse` enumerates the
matching paths), and the parse errors (e.g. that the path is outside of
`user_files`) were reported before the source access check of the
delegate. Now `getTableImpl` fails with the access error before the
delegate of a `file://` table is constructed, so `DESCRIBE` and
`SELECT` without the `READ ON FILE` grant no longer touch the local
filesystem.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both reds on commit 2c60c1c are unrelated to this PR (which only touches DatabaseURL table resolution and access-grant filtering):

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. Investigated; STID 1611-483a is not #110338, and I will open a separate PR.

That STID bucket pools two unrelated defects under one generic test_name. Splitting the 180-day CI DB history by payload:

So per-STID identity is not evidence of a shared root cause here. #110338 and @george-larionov's #113244 both touch only MergeTreeIndexSet.cpp (set skip index); neither touches FunctionTopKFilter or optimizeTopK. Different carrier.

Root cause of the __topKFilter arm: FunctionTopKFilter::getReturnTypeImpl unconditionally declares UInt8, but the vectorized path builds lessOrEquals/greaterOrEquals against the sort column and returns whatever that yields. For a sort column that is not itself Nullable but contains a Nullable element, tuple comparison yields Nullable(UInt8), so the declared and actual types diverge and ExpressionActions asserts:

Tuple(UInt64, Nullable(UInt64))      -> Nullable(UInt8)
Tuple(Tuple(Nullable(UInt64)))       -> Nullable(UInt8)
Tuple(UInt64, UInt64)                -> UInt8

The existing guard at FunctionTopKFilter.cpp:85 tests data_type->isNullable(), which is a top-level test only, so a Nullable nested inside a Tuple takes the vectorized path. optimizeTopK.cpp:177-178 excludes Dynamic and Variant from the prewhere for the same reason but has no nullability exclusion. This is the same defect class I fixed for Dynamic/Variant in #100742; that fix handled the two types it was reported against rather than the general property, and the tuple carrier was missed. My own oversight.

Reproduced locally on master 51810f428ac1 (debug), default settings, no use_top_k_dynamic_filtering override needed:

CREATE TABLE tab_t (id UInt64, tup Tuple(UInt64, Nullable(UInt64)))
ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 1, index_granularity = 64;
-- 20 batches of 5000 rows, so the threshold tracker is set before later parts are read
INSERT INTO tab_t SELECT number, tuple(number, number) FROM numbers(0, 5000);
... (x20)
SELECT tup FROM tab_t ORDER BY tup ASC NULLS LAST LIMIT 10;

gives byte-for-byte the CI message (Expected UInt8. Got Nullable(UInt8), input block structure:tup Tuple(UInt64, Nullable(UInt64))). It needs several parts so the threshold is established before a later part is read; a single part does not reproduce. use_top_k_dynamic_filtering = 0 is clean, which localises it to that optimization.

The other three recorded carriers agree with the same rule: Tuple(Date, Nullable(Float64)), Tuple(b String, c Tuple(d Nullable(UInt64), ...)), and this one.

You are right that there is no tracking issue for this STID. I will fix the general property rather than the reported type, and link the PR here.

Session id: cron:clickhouse-premium-slot-25:20260804-202200

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Fix opened: #113406.

It keys on the general property as promised, but not at the seam I sketched above. I had suggested excluding sort columns that structurally contain a Nullable in optimizeTopK.cpp; measuring first showed that would be a regression, because Array(Nullable(T)) and Map(K, Nullable(V)) comparisons resolve to plain UInt8 and work correctly today, so a structural predicate would silently disable use_top_k_dynamic_filtering for them. Instead the fix tests the resolved comparison type inside FunctionTopKFilter::executeVectorized, on the line that already computes it, and falls back to the existing general path when it is not UInt8. That path builds a ColumnUInt8 directly, so it cannot diverge, and no future type wrapper can reopen this the way the Tuple carrier reopened #100742. optimizeTopK.cpp is untouched.

One carrier beyond the three in my earlier comment turned up while enumerating: Tuple(LowCardinality(Nullable(String))), which needs no allow_suspicious_low_cardinality_types to create. Both new carriers are covered by the extended #100742 regression test.

Session id: cron:clickhouse-review-slot-11:20260805-022300

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master to pull in #111997, which fixes the ColumnBLOB should be converted to a regular column before usage logical error (#113165) behind three of the four stress-test reds on 1b32b7a. The fourth, the hung check in Stress test (arm_asan_ubsan, s3), is also unrelated: the stuck query is the internal async-insert flush of 03365_json_rollback_bug (tagged no-asan — too slow for sanitizers) parsing 2M JSON rows under ASan + ThreadFuzzer, with no URL-database or access-check frames in the stacks; the fix is in progress in #112646. All 6 local url_database stateless tests pass on the merged branch.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. This is not very important, but good to have.

@alexey-milovidov alexey-milovidov self-assigned this Aug 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 9, 2026
Merged via the queue into master with commit 319e5d5 Aug 9, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the url-database-exists-source-access branch August 9, 2026 22:30
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 9, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 10, 2026
… database

`DatabaseFilesystem::isTableExist` answered from the table cache and then probed the
directory, neither of which checked a grant, while `EXISTS TABLE` itself requires only
`SHOW TABLES`. A user with that privilege and without `READ ON FILE` could therefore tell
an existing file under `user_files` from a missing one: measured on the previous head of
this branch, `EXISTS TABLE` returned 1 for a cached name and 0 for a name that is not
there. The resolution path was already gated, so what was left of the disclosure was an
existence oracle over the same directory.

Without the grant the answer is now that the table exists, which is what
`DatabaseURL::checkFileURLExists` reports in the same situation: resolving such a table
fails with the access error, so the state of the directory stays unobservable. The check
is the entry of the method, above the cache lookup, for the reason the resolution gate is:
the cache is keyed on the table name alone, so an entry filled by a grant holder must not
answer for a user who does not hold it.

`URL`, the sibling engine with this defect class, gated its resolution path and its
existence probe in one change, ClickHouse#113029, under one test. Hence three assertions here rather
than a second test file: two for the ungranted user, a cached name and a missing one, which
must answer alike, and one after the grant, which keeps that pair from being a constant.
wickdChromosome pushed a commit to wickdChromosome/ClickHouse that referenced this pull request Sep 26, 2026
A clone of a part that passes no invalidated_columns_to_write (the
untouched-part clone in a mutation, clone-instead-of-fetch of a
replicated mutation, moves between disks) used to delete the
invalidated_system_columns.txt it had just hardlinked or copied from
the source part: writeInvalidatedSystemColumnsFileImpl unconditionally
removed the existing file and wrote nothing back for an empty set.
Losing the file resurrects the stale physically stored _block_number
and _block_offset values that were disclaimed when the part was adopted
from another table (ClickHouse#111801), so several co-active clones of one source
part expose duplicate row identities.

A lightweight UPDATE then captures the duplicates into a single patch
part with a constant _part_data_version, and applying that patch in
Join mode fails the 'current_version != existing_version' assertion in
PatchJoinCache::Entry::addBlock, which aborts debug and sanitizer
builds; release builds silently drop one of the duplicate rows.

Fix in two places:
- writeInvalidatedSystemColumnsFileImpl keeps an existing file when the
  caller has nothing new to invalidate; this covers the clones that
  copy or hardlink the whole part directory.
- cloneAndLoadDataPart merges the source part's invalidated set into
  the clone parameters; this also covers the Packed storage, whose
  freeze/freezeRemote copy only the data archive, so the destination
  never inherits the file.

Failure history:
https://play.clickhouse.com/play?user=play&tab=Query%20V#U0VMRUNUIGNoZWNrX3N0YXJ0X3RpbWUsIHB1bGxfcmVxdWVzdF9udW1iZXIsIGNoZWNrX25hbWUsIHRlc3RfbmFtZSBGUk9NIGNoZWNrcwpXSEVSRSB0ZXN0X25hbWUgTElLRSAnJWN1cnJlbnRfdmVyc2lvbiAhPSBleGlzdGluZ192ZXJzaW9uJScgQU5EIGNoZWNrX3N0YXJ0X3RpbWUgPj0gbm93KCkgLSBJTlRFUlZBTCAzIE1PTlRICk9SREVSIEJZIGNoZWNrX3N0YXJ0X3RpbWU=

The reproduced CI failure (the only one on a branch that already had
the invalidation mechanism from ClickHouse#111801):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113029&sha=cebdc42b01538df822d2da154bb5b51f1d4538d6&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#113029

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

Labels

pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants