Skip to content

Fix/interserver mode before secret hash bug - #99675

Merged
tiandiwonder merged 23 commits into
ClickHouse:masterfrom
MillaFleurs:fix/interserver-mode-before-secret-hash-bug
Jul 27, 2026
Merged

tiandiwonder merged 23 commits into
ClickHouse:masterfrom
MillaFleurs:fix/interserver-mode-before-secret-hash-bug

Conversation

@MillaFleurs

@MillaFleurs MillaFleurs commented Mar 16, 2026 •

Copy link
Copy Markdown

Changelog category (leave one):

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

Changelog entry

Reject native protocol handshakes that use the USER_INTERSERVER_MARKER for an unknown cluster, or for a cluster configured without a <secret>. Previously such a handshake would let an unauthenticated client enter interserver mode and exercise pre-auth protocol packets (e.g. TablesStatusRequest) backed by a fake_interserver_context, learning information about local tables without proving knowledge of the cluster secret.

Scope

This addresses the unknown-cluster and no-secret-cluster cases of the issue:

Deployment type Behavior after this change
Single-node (no clusters) USER_INTERSERVER_MARKER is rejected because the cluster does not exist (CLUSTER_DOESNT_EXIST)
Cluster without <secret> USER_INTERSERVER_MARKER is rejected with AUTHENTICATION_FAILED
Cluster with <secret> Marker is accepted, and the secret hash is still verified in processQuery

For clusters that do have a non-empty <secret>, a client that knows the cluster name can still send pre-query packets such as TablesStatusRequest before the hash is verified. Closing that remaining surface requires either authenticating during the Hello phase (challenge/response over the salt + cluster secret) or reworking ConnectionEstablisher so the secret hash is sent before TablesStatusRequest. Both are protocol-level changes that warrant their own discussion and a protocol-revision bump, so they are tracked separately rather than folded into this fix.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

This fixes a bug so the expected behavior of ClickHouse is as documented.

I compiled this successfully and ran the POC from issue #99512 against it, confirming the fix works with no errors thrown. An integration test (test_interserver_marker_requires_cluster_secret) sends a crafted native-protocol Hello packet and asserts the server rejects both an unknown cluster and a cluster configured without a secret, including verifying the expected log message.

Related: #99512

Version info

  • Merged into: 26.8.1.184 (included in 26.8 and later)

KD2YCU added 3 commits March 15, 2026 17:48
…er Mode prior to actually being authenticated which allows the return of real table metadata system.one, system.numbers, system.tables, system.databases, system.columns — all without credentials! I'm committing the fix, this bug is logged as ClickHouse#99512
@CLAassistant

CLAassistant commented Mar 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ tiandiwonder
✅ alexey-milovidov
❌ KD2YCU
You have signed the CLA already but the status is still pending? Let us recheck it.

Comment thread src/Server/TCPHandler.cpp Resolved
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d68b6f2]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
01660_join_or_any ERROR cidb
Server died FAIL cidb
03707_statistics_cache NOT_FAILED cidb
02345_implicit_transaction NOT_FAILED cidb
01010_partial_merge_join NOT_FAILED cidb
02499_monotonicity_toUnixTimestamp64 NOT_FAILED cidb
01147_partial_merge_full_join NOT_FAILED cidb
Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) FAIL cidb, issue
Upgrade check (amd_release) FAIL
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR closes the remaining Hello-phase gap for USER_INTERSERVER_MARKER: peers that claim an unknown cluster or a cluster without a configured <secret> are now rejected before interserver mode is entered, the reject is recorded through Session::onAuthenticationFailure, and the socket is closed without sending an exception payload back to the unauthenticated peer. I did not find any unresolved correctness or compatibility issues in the current head: the native client only sends USER_INTERSERVER_MARKER when a cluster secret is configured, the updated old-protocol regression test still reaches the TablesStatusRequest rejection path, and the new integration coverage exercises the silent-close and system.session_log behavior.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 17, 2026
Comment thread src/Server/TCPHandler.cpp Resolved
@MillaFleurs

Copy link
Copy Markdown
Author

Thank you I'll take a look tomorrow and update it...

alexey-milovidov and others added 5 commits March 18, 2026 06:11
Replace `try { ... } catch (...) {}` with a direct check that lets
`getCluster` propagate `CLUSTER_DOESNT_EXIST`. The silent `catch (...)`
was both flagged as dangerous by review and rejected by the style check
(`catch (...) that silently swallows exceptions`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The reviewer (`clickhouse-gh`) and CI proved that gating
`receivePacketsExpectQuery` on `is_interserver_authenticated` rejects
packets that legitimate distributed/interserver protocol flows send
before the first authenticated `Query`:

  - `IgnoredPartUUIDs` from `RemoteQueryExecutor::sendQueryUnlocked`
    (`connections->sendIgnoredPartUUIDs` before `connections->sendQuery`).
  - `TablesStatusRequest` from `ConnectionEstablisher::run` via
    `Connection::getTablesStatus`.

Multiple integration and stateless tests confirmed the breakage:
`02590_interserver_mode_client_info_initial_query_start_time` and
`test_distributed_inter_server_secret` were failing with
`ATTEMPT_TO_READ_AFTER_EOF` because the server was closing connections
mid-flow with `AUTHENTICATION_FAILED`.

The remaining `receiveHello` check (rejecting `USER_INTERSERVER_MARKER`
when the cluster has no secret) already fixes the original bug for
single-node servers and clusters without secrets, which is the primary
attack surface reported in ClickHouse#99512.

CI report: ClickHouse#99675

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Confirms that `USER_INTERSERVER_MARKER` is rejected at the `receiveHello`
phase when the named cluster either does not exist or has no `<secret>`
configured. Without this rejection a client could enter interserver
mode without proving knowledge of the cluster secret and exercise
pre-auth protocol packets that rely on `fake_interserver_context`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Server/TCPHandler.cpp Resolved
alexey-milovidov and others added 3 commits May 18, 2026 00:21
The `processClusterNameAndSalt` method reads the salt as a
length-prefixed string via `readStringBinary`, not as 32 raw bytes.
Sending 32 raw `'A'` bytes made the server interpret the first byte
(`0x41 = 65`) as the VarUInt length and then wait for 65 bytes that
never came. The handshake-timeout closed the connection, so the test
saw a `closed` socket and the first assertion (rejection happened)
passed — but our new exception path was never reached, which is why
the `contains_in_log` assertion failed in every CI shard.

Encoding the salt as a length-prefixed string lets the server finish
reading the `Hello` packet and reach the `receiveHello` check that
rejects the interserver marker for clusters without a secret.

CI report: ClickHouse#99675

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 20, 2026
Workflow files in this branch were stale or had been deleted as a
workaround for GitHub's workflow-scope check. Restoring them to match
`master` so the PR diff no longer contains those unrelated changes.
@alexey-milovidov

Copy link
Copy Markdown
Member

Picked this up to keep it moving:

  • Merged latest master (the branch was ~540 commits behind). No conflicts; the diff is unchanged (only src/Server/TCPHandler.cpp plus the new integration test).
  • Rebuilt and re-ran the integration test test_interserver_marker_requires_cluster_secret locally — both cases (unknown cluster, secret-less cluster) pass and the AUTHENTICATION_FAILED log assertion holds.
  • Corrected the PR description / changelog entry to match the actual scope. The previous entry ("Interserver mode is no longer entered prior to checking the secret hash" + "Cluster with secrets → fully protected") overclaimed: as @alexey-milovidov noted, for clusters with a <secret> the pre-auth TablesStatusRequest surface is intentionally left as a protocol-level follow-up. The new entry describes precisely what this change does — reject the USER_INTERSERVER_MARKER for unknown clusters and clusters without a <secret> — and documents the remaining surface as tracked separately.

The only CI failure was test_s3_aws_sdk_has_slightly_unreliable_behaviour::test_dataloss, a 600s client timeout in an unrelated S3 test (CIDB confirms it as a recurring Timeout flaky on master), not connected to the interserver handshake change.

@alexey-milovidov

Copy link
Copy Markdown
Member

Kept this moving:

  • Merged latest master (the branch was ~710 commits behind). No conflicts; the diff is unchanged — only src/Server/TCPHandler.cpp (the 11-line receiveHello secret check) plus the new integration test.
  • Rebuilt clickhouse cleanly and re-ran test_interserver_marker_requires_cluster_secret locally against the fresh master — both cases (unknown cluster, secret-less cluster) pass (2 passed), including the AUTHENTICATION_FAILED log assertion.
  • The only red check was CH Inc sync (tests failed). The failing sync job log shows Connection refused (localhost:9000) / Server replica 0 not ready during test setup, before any test ran — the server never started. This is an infrastructure flake, not a regression: the handshake change can only reject interserver-marker connections, it can't stop the server from listening, and only one stateless shard failed (a real regression would fail every shard). Pushing this master-merge regenerates the sync PR and re-runs it on fresh master.

The remaining unresolved thread (pre-auth TablesStatusRequest for clusters that do have a <secret>) is the protocol-level follow-up @alexey-milovidov already scoped out of this fix; left untouched.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master into the branch (it was 595 commits behind and red). The merge was clean — no conflicts — and the only code change (receiveHello in TCPHandler.cpp) is intact. Rebuilt clickhouse after the merge: compiles cleanly.

The CI reds were all unrelated flakes now addressed by the master merge or known issues:

The one remaining unresolved review thread is the design question about pre-auth TablesStatusRequest for clusters that do have a <secret>; that is intentionally out of scope per the discussion (it needs a protocol-revision bump and is tracked separately).

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, the only red here is CH Inc sync → "Check public build", and it's a false positive in the sync tooling — not a defect in this PR. Public CI is fully green and the PR's actual change (an 11-line cluster-secret check in TCPHandler::receiveHello) compiles cleanly in the public build.

Failing job: https://github.com/ClickHouse/clickhouse-private/actions/runs/27341320229/job/80779004585

Root cause. ci/jobs/check_public_build.py clones the public repo and copies the PR's modified shared files into it, then builds. This PR modifies src/Server/TCPHandler.cpp, so the whole private TCPHandler.cpp is copied over the public one. The private file contains private-only JWT code (JWTCredentials, guarded by #if USE_JWT_CPP && USE_SSL) whose declaration lives in src/Access/Credentials.h. The check's paired-header logic only syncs the same-basename header (TCPHandler.h), not Access/Credentials.h, so the public clone ends up with the private JWT usage but its own public Credentials.h without the JWTCredentials declaration:

src/Server/TCPHandler.cpp:1986:31: error: use of undeclared identifier 'JWTCredentials'
src/Server/TCPHandler.cpp:2445:35: error: use of undeclared identifier 'JWTCredentials'

@evillique's recent 19d6e31fa6e ("Do not sync private-only files into the public clone") does not cover this case: TCPHandler.cpp exists in both repos, so it is still copied wholesale; the gap is a shared .cpp whose private version references private-only declarations from a non-paired shared header.

Suggested direction (your call): apply only the PR's own diff (master..head for the file) onto the public clone's copy instead of copying the private file wholesale, or also sync the private versions of shared headers the copied .cpp depends on. Could you take this in a separate PR against clickhouse-private and link it here?

The remaining sync test-job reds are unrelated known flakes (none touch this PR's own tests, all reran-and-passed or were auto-classified flaky): test_kafka_engine_put_errors_to_stream (#60222), test_shared_merge_tree_virtual_parts_broad_cast (kazoo NoNode, passed on retry), 01666_merge_tree_max_query_limit (#59317), 03100_lwu_07_merge_patches (not reproducible, 7/7 passed on rerun), stress "Hung check" (#107171).

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov thanks for the precise root cause. I checked from the public side and your diagnosis holds: this PR's own change is the 11-line cluster-secret check in receiveHello, which references only public symbols (getCluster, getSecret, ErrorCodes::AUTHENTICATION_FAILED). The JWTCredentials errors at lines 1986/2445 are private-only divergence the PR never touched, dragged in by the wholesale copy of the private TCPHandler.cpp.

One blocker on the ask: I don't have access to clickhouse-private (404 for me as a non-collaborator), so I can't fork it, read check_public_build.py, or open the PR there. If someone grants groeneai access I'll open it; otherwise here is the concrete fix for whoever owns the tooling (evillique's 19d6e31fa6e).

Recommendation: Direction 1 (apply only the PR's own delta), and prefer it over Direction 2. The check's purpose is "does this PR's change break the public build", so the public clone should be public repo + this PR's delta, never the whole private file. Direction 2 (also sync private headers the .cpp depends on) papers over the symptom: it pulls more private-only code into the public clone, needs transitive-include analysis, and breaks again on the next shared .cpp that references a different non-paired private declaration.

The robust way to apply the delta is a 3-way merge rather than a naive git apply master..head (which fails on context when the public and private copies of a shared file have diverged near the hunks). For each modified shared file F:

# in the private checkout: BASE = PR merge-base, HEAD = PR head
git show "$BASE:$F" > /tmp/base
git show "$HEAD:$F" > /tmp/head
# 3-way merge the PR's delta (base..head) onto the public clone's own copy
git merge-file -p "$PUBLIC_CLONE/$F" /tmp/base /tmp/head > "$PUBLIC_CLONE/$F.merged" \
  && mv "$PUBLIC_CLONE/$F.merged" "$PUBLIC_CLONE/$F"

git merge-file incorporates the base..head changes (the PR's delta) into the public copy. A non-zero exit means a genuine conflict between the PR's change and public/private divergence, which the check should surface as "needs manual attention" instead of a misleading compile error. The same-basename paired-header logic can then be dropped for these files, since you're no longer importing the private file wholesale.

I'll link the clickhouse-private PR here if I open it; happy to if access is granted.

@alexey-milovidov

Copy link
Copy Markdown
Member

@evillique (tooling owner), @groeneai — one refinement to the CH Inc sync → Check public build root cause that makes the fix simpler, especially for the sync-PR case that blocks this PR.

For sync PRs, ci/jobs/check_public_build.py already clones the upstream PR's HEAD, not public master:

if is_sync_pr:
    # cloning upstream PR HEAD instead of master
    clone_command = [git clone --no-checkout ...; fetch origin pull/{parent_pr_number}/head; checkout FETCH_HEAD]

So for a sync PR the public clone's src/Server/TCPHandler.cpp is already public master + this PR's 11-line delta — exactly what the public build should compile. The subsequent shutil.copy2(src, dst) then overwrites it with the private TCPHandler.cpp, which carries private-only JWTCredentials usage (#if USE_JWT_CPP && USE_SSL) whose declaration lives in src/Access/Credentials.h — a non-paired header that is never synced. That is the use of undeclared identifier 'JWTCredentials' at public_repo/.../TCPHandler.cpp.

In other words: for sync PRs the wholesale copy is not just missing a header — it is purely harmful, replacing public + delta with private + delta.

Concrete fix (two distinct cases):

  • Sync PR (is_sync_pr): the public clone is the PR head and already reflects the public PR's changes, so skip the copy of files that already exist in the public clone — there is nothing to apply. (Only genuinely-new files absent from the PR head, if any, would need copying.)
  • Non-sync private PR: the public clone is at master, so the private PR's delta does need applying — there, use the 3-way merge @groeneai described (git merge-file -p public_copy BASE HEAD, BASE = PR merge-base, HEAD = the checked-out private file) so only the PR's delta lands and a non-zero exit is surfaced as "needs manual attention" rather than a misleading compile error. The same-basename paired-header heuristic can then be dropped, since the private file is no longer imported wholesale.

This is in clickhouse-private's ci/jobs/check_public_build.py; I have access and am happy to open the PR if you'd prefer, but it's your tooling so flagging the precise fix for your call. The public side of this PR is fully green and unaffected.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov agreed, the sync-PR refinement is correct and simpler. For a sync PR the public clone is checked out at the upstream PR head, so every shared file the PR touches is already public master + the public delta; the later shutil.copy2 of the private file is purely harmful, swapping in private + delta and dragging in the non-paired JWTCredentials usage. Skipping the copy of any file that already exists in the clone (os.path.exists(dst) as the discriminator) is the right fix, copying only genuinely-new files absent from the PR head.

The 3-way merge stands for the non-sync private PR case (clone at master, apply only the delta via git merge-file -p public_copy BASE HEAD, surfacing a non-zero exit as "needs manual attention" rather than a misleading compile error). One generalization: once both paths stop importing a private file wholesale over an existing public one, the same-basename paired-header heuristic can be dropped entirely, not just on the non-sync branch.

On opening the PR: I still have no clickhouse-private access (404 on the repo, the file, and the failing job run as of now), so I cannot open it there. Since you have access it is your or evillique's call; happy to open and own it if groeneai is granted access. Public side here remains green and unaffected.

@alexey-milovidov

Copy link
Copy Markdown
Member

Kept this moving:

  • Merged latest master (the branch was ~2750 commits behind and red). The merge is clean — no conflicts — and the diff is unchanged: only the 11-line receiveHello cluster-secret check in src/Server/TCPHandler.cpp plus the integration test. Master's one intervening change to TCPHandler.cpp is in parallel-block marshalling (low_cardinality_allow_in_native_format), unrelated to the Hello phase, so it does not interact with this fix.
  • The only red was CH Inc sync, reported as tests failed but rooted in the Check public build tooling false positive I described on 2026-06-12: the check copies the private TCPHandler.cpp (which carries JWTCredentials usage guarded by #if USE_JWT_CPP && USE_SSL) over the public one without syncing the matching src/Access/Credentials.h, so the public clone fails to compile. That has since been fixed in clickhouse-private — commit 19d6e31fa ("Do not sync private-only files into the public clone in check_public_build", 2026-06-11 20:46) and ClickHouse/clickhouse-private#60796 ("Even better check_public_build", merged 2026-06-12 20:07), both landing after this PR's last sync run (2026-06-11 13:51). This master re-merge regenerates the sync PR on top of current private master, which includes those fixes, so the Check public build failure should no longer occur.

The remaining unresolved review thread (pre-auth TablesStatusRequest for clusters that do have a <secret>) is the protocol-level follow-up intentionally scoped out of this fix — it needs Hello-phase challenge/response or a ConnectionEstablisher rework plus a protocol-revision bump, and re-introducing a pre-auth packet filter would break the legitimate interserver flows the earlier review already rejected. Left untouched.

@alexey-milovidov

Copy link
Copy Markdown
Member

Kept this moving:

  • Merged latest master (the branch was ~910 commits behind and red). The merge is clean — no conflicts — and the diff is unchanged: only the 11-line receiveHello cluster-secret check in src/Server/TCPHandler.cpp plus the integration test. Master moved the surrounding code (the check now sits at TCPHandler.cpp:1993), but the Hello-phase logic is untouched.

  • The only red was CH Inc sync (build failed), and this time it was not the Check public build / JWTCredentials tooling issue from before — it was a transient private-master build break unrelated to this PR. The sync PR (clickhouse-private#52651) was built at 2026-06-15 23:00 against a private master snapshot in which programs/distributed-cache-bench/BenchClient.cpp included a header that did not exist:

    programs/distributed-cache-bench/BenchClient.cpp:8:10: fatal error: 'IO/SilkFiberStreamSocketImpl.h' file not found
    

    That bad include came from private commit 963e7040293 ("Reimplement distributed-cache-bench mTLS on native silk fiber sockets", 2026-06-15 13:24) and broke every private build config — which is exactly the tell that it is not this PR's 11-line interserver-Hello change (that compiles cleanly in both public and private). It was already reverted on private master by 67b95156db8 ("Revert 'Add native mTLS support to distributed-cache-bench'", 2026-06-16 08:59). This master re-merge regenerates the sync PR on top of current private master, which now contains that revert, so the build failed should clear.

Public CI is fully green (162 checks, 0 failed), the AI review verdict is Approve, and there are no unresolved review threads. The remaining out-of-scope item (pre-auth TablesStatusRequest for clusters that do have a <secret>) is the protocol-level follow-up already scoped out — it needs a Hello-phase challenge/response or a ConnectionEstablisher rework plus a protocol-revision bump, so it is tracked separately.

@alexey-milovidov

Copy link
Copy Markdown
Member

Kept this moving:

  • Public CI is fully green (162 checks, 0 failed), the AI review verdict is Approve, and there are no unresolved review threads. The change is unchanged: the 11-line receiveHello cluster-secret check in src/Server/TCPHandler.cpp plus the integration test. The branch is only ~2 days behind master (merge-base 2dbda7a43b4, 2026-06-18), no conflicts, so no re-merge was needed.

  • The only red is CH Inc sync, and it is a deterministic tooling false positive — not this change. The sync PR's Check public build job fails with:

    public_repo/src/Server/TCPHandler.cpp:2023:31: error: use of undeclared identifier 'JWTCredentials'
    public_repo/src/Server/TCPHandler.cpp:2482:35: error: use of undeclared identifier 'JWTCredentials'
    

    Root cause: for sync PRs, check_public_build.py already clones the upstream PR HEAD (so the public clone has the correct public version of every file this PR touches), but it then still copies the private TCPHandler.cpp over it. The private file uses JWTCredentials, declared in the private-only src/Access/Credentials.h; the paired-header logic only syncs same-basename headers (TCPHandler.h), so the clone gets the usage without the declaration and fails to build. Any sync PR touching TCPHandler.cpp hits this. This is the same Check public build issue discussed earlier in this thread; Include multiline logs in fuzzer fatal.log report #60796 added the upstream-HEAD clone but left the now-redundant copy in place.

    Fix submitted as a private tooling PR: ClickHouse/clickhouse-private#61663 — for sync PRs, skip copying private files into the public clone and build the upstream PR HEAD as-is (the non-sync path is unchanged). Once that merges and the sync PR re-merges master, Check public build should pass.

  • The other sync-side reds (01666_merge_tree_max_query_limit (new analyzer multiple join using, unconsistent left most table column names #59317), test_distributed_cache/test.py::test_graceful_shutdown, test_database_delta/test.py::test_complex_table_schema, stress Cannot start clickhouse-server) are pre-existing flakes/infra unrelated to the interserver-Hello change; they will be re-run once the tooling unblocks the sync.

The remaining out-of-scope item (pre-auth TablesStatusRequest for clusters that do have a <secret>) is the protocol-level follow-up already scoped out — it needs a Hello-phase challenge/response or a ConnectionEstablisher rework plus a protocol-revision bump, tracked separately.

@alexey-milovidov

Copy link
Copy Markdown
Member

Status update on CH Inc sync:

  • The deterministic Check public build false positive (the JWTCredentials undeclared-identifier error from copying the private TCPHandler.cpp over the public clone) is now fixed on the tooling side: clickhouse-private#61663 ("do not copy private files over the public clone for sync PRs") merged on 2026-06-22, and the latest sync run shows Check public build green again.
  • The remaining CH Inc sync red is down to two flaky stress jobs — Stress test (amd_tsan, SharedCatalog, meta in keeper) and Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper) — whose non-SharedCatalog twins on the same compilers all pass. These are unrelated to the 11-line receiveHello change (stress workloads do not exercise the interserver USER_INTERSERVER_MARKER handshake). Re-running them.

Public CI is fully green (149 / 0), the AI review verdict is Approve, and there are no unresolved review threads.

@rschu1ze

rschu1ze commented Jul 2, 2026

Copy link
Copy Markdown
Member

@tiandiwonder Can you please check if this PR is a duplicate of #99854 ?

@rschu1ze

rschu1ze commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

@tiandiwonder Since you were working on related issue #99854, would you like to check this one as well (I assigned you)? Thanks!

Comment thread src/Server/TCPHandler.cpp Outdated
Comment on lines +1997 to +2002
/// Verify the cluster is configured with a secret before entering
/// interserver mode. Otherwise, the `USER_INTERSERVER_MARKER` would
/// let any client enter interserver mode and exercise pre-auth
/// protocol packets that rely on a `fake_interserver_context`.
/// `getCluster` throws `CLUSTER_DOESNT_EXIST` if the cluster is
/// unknown; we deliberately let it propagate.

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.

optional: this comment is a bit long — 2-3 lines would do. the fake_interserver_context detail reads better in the PR/issue description; inline it's enough to say why we reject and that getCluster throws CLUSTER_DOESNT_EXIST for an unknown cluster, which we let propagate.

Suggested change
/// Verify the cluster is configured with a secret before entering
/// interserver mode. Otherwise, the `USER_INTERSERVER_MARKER` would
/// let any client enter interserver mode and exercise pre-auth
/// protocol packets that rely on a `fake_interserver_context`.
/// `getCluster` throws `CLUSTER_DOESNT_EXIST` if the cluster is
/// unknown; we deliberately let it propagate.
/// Reject interserver mode unless the cluster has a `<secret>`; otherwise any client
/// could enter interserver mode and exercise pre-auth protocol packets. `getCluster`
/// throws `CLUSTER_DOESNT_EXIST` for an unknown cluster, which we deliberately let propagate.

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.

Applied directly in 1260b249.

@alexey-milovidov

Copy link
Copy Markdown
Member

Kept this moving:

  • Merged latest master (the branch was ~2 weeks behind). The merge is clean — no conflicts — and the diff is unchanged: the receiveHello cluster-secret check in src/Server/TCPHandler.cpp plus the integration test.
  • Re: the duplicate question with Fix unauthenticated TablesStatusRequest in interserver mode #99854 — that PR merged into master today (b361f3f8928, included via this merge) and closes the pre-auth TablesStatusRequest leak for clusters that do have a <secret>, by requiring an authentication hash (or the interserver_tables_status_require_auth setting for old clients) inside processTablesStatusRequest itself. This PR is complementary rather than a duplicate: it rejects the USER_INTERSERVER_MARKER at the receiveHello stage for an unknown cluster or a cluster without a <secret>, closing off interserver mode entirely for those cases (not just the TablesStatusRequest packet). Verified the two changes don't conflict — TCPHandler.cpp merged clean and both mechanisms coexist logically.
  • Rebuilt clickhouse after the merge (compiles cleanly) and re-ran test_interserver_marker_requires_cluster_secret against the fresh master — both cases (unknown cluster, secret-less cluster) still pass.
  • The one open review thread (comment-length nit from @tiandiwonder) was already addressed in 1260b249; leaving it for @tiandiwonder to resolve.

Comment thread src/Server/TCPHandler.cpp Resolved
Comment thread src/Server/TCPHandler.cpp Resolved
alexey-milovidov and others added 2 commits July 25, 2026 01:02
…ession_log

- Do not serialize the exception back to an unauthenticated interserver peer
  when the `Hello`-phase cluster-secret check fails: the handshake catch block
  now closes the connection without a response for `AUTHENTICATION_FAILED` in
  interserver mode, so nothing (not even whether the named cluster exists)
  is disclosed. Previously the exception with a stack trace was sent back.
- Wrap the `CLUSTER_DOESNT_EXIST` from `getCluster` into `AUTHENTICATION_FAILED`
  (mirroring `processQuery`) so both rejection paths are uniform.
- Route the rejection through `Session::onAuthenticationFailure` so the blocked
  `USER_INTERSERVER_MARKER` handshakes appear in `system.session_log` as
  `LoginFailure` rows with the `TCP_Interserver` interface.
- Tighten `test_interserver_marker_requires_cluster_secret` to require a silent
  close (no data) and assert the `session_log` row.
- Fix `test_interserver_tables_status_auth::test_old_protocol_unauthenticated_request_is_rejected`
  (failed on 5 CI lanes: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99675&sha=959beb1aabdd19bb6315e8ee519c441cf94da5e9&name_0=PR):
  the `Hello` must name the existing secreted cluster `mismatch`, otherwise the
  handshake itself is now rejected and the `TablesStatusRequest` stage that the
  test covers is never reached.

ClickHouse#99675

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

Copy link
Copy Markdown
Member

Kept this moving:

  • Merged latest master (the branch was ~4800 commits behind; clean, no conflicts).
  • Addressed both open review items (commit d68b6f2f553):
    • The Hello-phase reject is now routed through Session::onAuthenticationFailure, so blocked USER_INTERSERVER_MARKER handshakes appear in system.session_log as LoginFailure rows with the TCP_Interserver interface — this was the single Major in the AI review verdict.
    • Nothing is serialized back to the unauthenticated peer anymore: the handshake catch block closes the connection without a response for interserver AUTHENTICATION_FAILED, so the exception/stack trace no longer leaks, and the peer cannot even tell whether the named cluster exists (CLUSTER_DOESNT_EXIST is wrapped into AUTHENTICATION_FAILED, mirroring processQuery).
  • Fixed the 5 CI reds (all the same test, deterministic): test_interserver_tables_status_auth::test_old_protocol_unauthenticated_request_is_rejected from Fix unauthenticated TablesStatusRequest in interserver mode #99854 sent an empty cluster name in the Hello, which this PR now rejects at the handshake — before the TablesStatusRequest stage that test covers. The test now names the existing secreted cluster mismatch, so the handshake is accepted and the Fix unauthenticated TablesStatusRequest in interserver mode #99854 rejection path is still exercised. The PR's own test is tightened to require a silent close (no data) plus the new session_log row.
  • Verified locally against a server built from this branch: unknown cluster and secret-less cluster → connection closed with 0 bytes and a LoginFailure row in system.session_log; old-protocol TablesStatusRequest against mismatch → Hello accepted, then 0 bytes.

Remaining: the CLA check still shows the KD2YCU committer identity unsigned (2 of 3) — that needs @MillaFleurs to sign or re-attribute; and the final merge decision stays with a human.

CI report analyzed: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99675&sha=959beb1aabdd19bb6315e8ee519c441cf94da5e9&name_0=PR

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 91.90% -0.10%
Branches 78.40% 78.20% -0.20%

Changed lines: Changed C/C++ lines covered: 22/23 (95.65%) · Uncovered code

Full report · Diff report

@tiandiwonder
tiandiwonder added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit 1d4408f Jul 27, 2026
177 of 179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
tiandiwonder added a commit that referenced this pull request Oct 22, 2026
26.7 lacks #99675, so the handshake still sends the
`AUTHENTICATION_FAILED` exception back to an interserver peer, and `ClientInfo::getLastForwardedFor`
throws on a non-IP forwarded address before `onAuthenticationFailure` is reached. The connection
is rejected in both cases; only the assertions about a silent close and the `system.session_log`
row for the malformed address are adjusted.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=127346&sha=latest&name_0=BackportPR&name_1=Integration%20tests%20(amd_tsan%2C%205%2F6)
PR: #127346

Co-Authored-By: Claude Opus 5.5 (1M context) <[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 manual approve Manual approve required to run CI 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.

8 participants