Skip to content

HTTPCLIENT-2436: Try the next address after a TLS failure in the async client, stop on certificate errors - #3332

Open
Sharawey74 wants to merge 15 commits into
apache:masterfrom
Sharawey74:HTTPCLIENT-2436-tls-fallback
Open

Sharawey74 wants to merge 15 commits into
apache:masterfrom
Sharawey74:HTTPCLIENT-2436-tls-fallback

Conversation

@Sharawey74

Copy link
Copy Markdown

Fixes #3313 (HTTPCLIENT-2436).

The async client gave up as soon as the TLS handshake failed on the first resolved address, while the classic client moved on to the next one. With localhost resolving to 127.0.0.1 and ::1 and a server that never answers the handshake, classic gave up after 2 x handshake timeout and async after 1 x, so the same TlsConfig behaved differently depending on the transport.

This makes both transports follow one rule, as agreed in the issue:

  • the handshake fails with a CertificateException or an SSLPeerUnverifiedException anywhere in its cause chain: fail right away, since every address presents the same certificate
  • any other IOException (handshake timeout, connection reset, peer closing mid-handshake, TLS alert): try the next address

Three commits:

  1. Fall back to remaining addresses when TLS fails after a connect is @arturobernalg's commit from arturobernalg@729b6876f, applied unchanged with him as author. It adds a SessionValidator hook to MultihomeIOSessionRequester that runs the TLS handshake on every connected session before it is accepted, for both the sequential path and the Happy Eyeballs race, so MultihomeConnectionInitiator does not change. The commit message has the details, including the cancellation hardening.
  2. Stop trying other addresses when the peer's certificate is rejected adds ConnectExceptionSupport.isPeerCertificateFailure, which walks the whole cause chain (cycle-safe), and uses it in four places: the async sequential path and race fallback, and the classic sequential path and race fallback. Classic used to retry on certificate failures too, so it now stops there the same way.
  3. Test that certificate failures do not try other addresses against a real server adds TestTlsCertificateFailureNoFallback in httpclient5-testing (see below).

A peer closing the connection mid-handshake and a TLS alert both surface as a bare SSLHandshakeException, so the check goes by cause type rather than by SSLException. A host name mismatch is covered under both the built-in and the client-side verification: CertificateException in the first case, SSLPeerUnverifiedException in the second.

H2-only clients are not covered and can be a follow-up.

Tests:

  • ConnectExceptionSupportTest: direct and nested causes, non-certificate handshake failures, null, and a cyclic cause chain

  • DefaultHttpClientConnectionOperatorTest: a certificate failure and a peer-unverified failure on the first of two real loopback addresses stop after one handshake, a non-certificate SSLHandshakeException still falls back; each with and without Happy Eyeballs

  • DefaultAsyncClientConnectionOperatorTest: the same two failure kinds stop the async operator without a second connect attempt, with and without Happy Eyeballs

  • TestTlsCertificateFailureNoFallback: classic and async, with and without Happy Eyeballs, against a real TLS server whose certificate is untrusted or issued to another host name, with the host name checked under both BUILTIN and CLIENT. The request must fail with a certificate failure and the second address must never be connected to.

All 12 cases of the real-server test and the 8 new operator tests fail without the second commit. mvn -pl httpclient5 install passes (1270 tests, japicmp included), as do TestTlsCertificateFailureNoFallback, TestHappyEyeballsTlsFallback, TestHappyEyeballsTlsFallbackAsync and TestHttpAsyncMinimalTlsHandshake, on both JDK 21 and JDK 25. TestHappyEyeballsTlsFallbackAsync.cancelDuringFallbackAfterRealTlsFailure_abortsPendingAttempt failed once in five runs here, which matches the flakiness noted in the first commit's message (the httpcore5 cancellation window).

arturobernalg and others added 15 commits November 25, 2026 18:46
No notifications block meant issue events defaulted to [email protected]
via the Apache Git Service. Harmless at normal volume, but the Jira
Issues migration (INFRA-28579) is about to import 2347 issues here,
which would flood the list. Point issues at [email protected]
instead, same pattern apache/maven and apache/opennlp use after their
own Jira migrations.
The ASF Git Service's .asf.yaml validator rejected [email protected]:
notifications targets must be the project's real @httpcomponents.apache.org
list, not the hc.apache.org vanity domain used on the website/mail links.
Neither [email protected] nor [email protected]
validated. Infra is creating [email protected] instead
(INFRA-28579, simpler than a new list under httpcomponents.apache.org).
Don't merge until confirmed created.
The mapping was fixed in apache/infrastructure-asfyaml#152 (httpcomponents
-> hc), but issue notifications still went to dev@ after the merge. No
content change, just a fresh push to .asf.yaml to force the Git Service
to re-evaluate the notifications block.
Per Infra (Bob), force a real value-diff push to .asf.yaml so the Git
Service fully reprocesses notifications::issues end to end, rather
than a no-op comment-only re-save. Restored to [email protected]
in a follow-up commit.
Second half of the revert/restore cycle Infra (Bob) asked for, to force
the Git Service to fully reprocess notifications::issues end to end.
Define INTERLEAVE as no-bias and align tests and debug output.
Add manual gated IT to dump DEFAULT vs INTERLEAVE results.
Expand unit coverage for scope mapping and core RFC comparison rules.
…ults.

Tighten resolver semantics and filtering for HTTP/TCP connect targets.
Races connection attempts across a host's resolved addresses instead
of trying them strictly sequentially: first address immediately, each
next one after a configurable delay (250ms default) unless an earlier
one fails first, in which case the next address starts at the RFC
8305 Section 5 minimum spacing (10ms). First success wins; the rest
are cancelled or closed. An attempt cancelled from outside the race is
treated like a failure so the future is never left pending forever.

A winning session can be selected by the race at the same moment the
caller cancels the outer Future directly. ComplexFuture#completed then
returns false; close the session instead of silently dropping it.

Opt-in, off by default; disabled behavior is unchanged.
…ient

Replaces the one-thread-per-address, sleep-based stagger with a single
dispatcher that starts the first address immediately and waits up to
the connection attempt delay for an outstanding attempt to finish
before starting the next; on a failure it advances immediately, at the
RFC 8305 minimum spacing (10ms), instead of waiting out the full delay.
No worker thread ever sleeps a delay itself, bounding concurrency to
the number of resolved addresses actually in flight.

Socket registration goes through a small atomic registry instead of a
bare reference: deciding a winner and a worker registering its socket
can happen at the same instant, and whichever runs second closes the
socket, so nothing registered around that moment survives open
regardless of timing. shutdownNow() alone cannot abort a blocking
Socket#connect; closing the socket is what actually does that, on
every exit path (winner found, every address failed, or interrupted)
via one cleanup call in a finally block.

An interruption during the minimum-spacing wait is now propagated
instead of swallowed, aborting the race immediately like interruption
anywhere else in it. Racing is skipped in favor of the existing
sequential path when a specific, non-ephemeral local port is
requested, since binding several attempts to it concurrently would
trade a real connect failure for a spurious bind conflict.

Public, blocking connect() behavior, TLS, SOCKS and local binding are
otherwise unchanged.
Since the challenge parsing was reworked, a single malformed
WWW-Authenticate or Proxy-Authenticate header causes all challenges in
the response to be discarded, so a valid Basic or Digest challenge in
another header is no longer used and the 401 is returned as is. Before
that change only the malformed header was skipped.

The empty map returned in that case is also immutable, so a response
that carries Authentication-Info together with a malformed challenge
header fails with UnsupportedOperationException.

Parse each header separately again and skip only the ones that fail.
…8305)

MultihomeIOSessionRequester only retried a TCP-level connect failure across
the resolved addresses; a TLS failure on an address that had already
connected at the TCP level, racing or not, ended the whole attempt instead
of trying the others, the same regression apache#936 fixed for the classic
client. Adds a SessionValidator hook run on every connected session before
it is accepted, shared by the plain sequential path and the race's
post-win fallback, mirroring DefaultHttpClientConnectionOperator's
connectSequentially.

Hardens cancellation around that fallback: a cancel arriving while a
TLS-triggered fallback attempt is in flight reaches the live attempt, in
both the plain sequential path and the racing path's post-win fallback.
executeNext() checks future.isDone() before starting a new attempt, at
the top of executeNext() itself and in onFailure(), the two places that
start a new attempt, and holds a single ReentrantLock per
connectSequentially() run, shared across all its attempts, across the
index check and the future's dependency retarget, so a same-thread
reentrant rejection and a cross-thread one can never race on which
attempt is tracked. Race's own six synchronized blocks are converted the
same way, matching the project's lock discipline for virtual threads. A
TlsStrategy that reports an outcome and then throws, in violation of its
contract, is a no-op on the second signal instead of double-advancing
the fallback. The handshake result is reported before the
onAfterTlsHandshake hook runs, so a throwing hook cannot hang the
connect() future.

The cancellation this hardening targets can still be lost underneath it,
in httpcore5: SingleCoreIOReactor#processConnectionRequest connects and
completes an IOSessionRequest before assigning it a closeable, so a
cancel() landing in that window returns true without anything to close.
A separate, narrower check-then-set race in ComplexFuture#setDependency
itself is also unclosed. Both are out of scope here and belong in
httpcore5.

TestHttpAsyncMinimalTlsHandshake.testTlsHandshakeFailure is pinned to a
literal address: "localhost" resolves to more than one address in this
environment, and a TLS failure is no longer necessarily final for the
last-tried address, so a second, unlistened-on address could mask the
TLS failure the test asserts.

TestHappyEyeballsTlsFallbackAsync's probe accepts the TCP connection,
reads the ClientHello and replies in plaintext, producing a real
SSLException. Its cancel-during-fallback scenario's own server observes
the client disconnecting directly, so the test cannot pass merely
because cancelling a future completes it locally regardless of whether
cancellation propagated anywhere. This test is flaky under heavy CPU
load (the cancel can still land in the httpcore5 window above); a
validated fix exists but is not applied here.

Unit tests cover: the isDone() guard at both its entry points (the
racing one directly, via Race.onWinnerRejected()'s call into
executeNext(); the sequential one indirectly, via onFailure(), which
does not on its own exercise the top-of-executeNext() guard); the
session never being closed when a throwing onAfterTlsHandshake hook is
swallowed; and the double-invocation guard on both the callback and the
throw-without-callback paths.
A TLS failure on one resolved address made both transports try the
next one, whatever the cause. When the peer's certificate is untrusted
or does not match the host name, every address of the host presents
the same certificate, so the remaining attempts can only fail the same
way and just add a handshake timeout or round trip each.

Treat such a failure as final in both the classic and the async
transport, with or without Happy Eyeballs racing: the handshake fails
with a CertificateException or an SSLPeerUnverifiedException anywhere
in its cause chain. Any other IOException, including a handshake
timeout, a connection reset, the peer closing mid-handshake or a TLS
alert, still moves on to the next address, since those cannot be told
apart from a transient failure by type and may well succeed elsewhere.

The check lives in ConnectExceptionSupport so both transports apply
the same rule. H2-only clients are not covered yet.
…eal server

Runs both the classic and the async client, with and without Happy
Eyeballs, against a real TLS server whose certificate is either
untrusted or issued to another host name, with the host name checked
by JSSE during the handshake (BUILTIN) or by the client afterwards
(CLIENT). In every case the request must fail with a certificate
failure and the second resolved address must never be connected to.
Copilot AI balanced review requested due to automatic review settings December 1, 2026 21:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@ok2c

ok2c commented Dec 2, 2026

Copy link
Copy Markdown
Member

@Sharawey74 The change-set turned out to be much bigger than I anticipated. Can we handle each commit as a separate pull request?

@arturobernalg Could you please submit your original change-set as a separate request?

@Sharawey74

Copy link
Copy Markdown
Author

@Sharawey74 The change-set turned out to be much bigger than I anticipated. Can we handle each commit as a separate pull request?

@arturobernalg Could you please submit your original change-set as a separate request?

Sure, I'll split it. @arturobernalg, once your PR is up I'll open mine on top of it.

@Sharawey74

Copy link
Copy Markdown
Author

Arturo's change is now in #3336. I'll open my two commits as separate PRs on top of it, one for the certificate fail-fast change and one for the real-server test, and close this one once they're up.

@ok2c ok2c added the 5.8.x 5.8 release series label Dec 5, 2026
@ok2c

ok2c commented Dec 5, 2026

Copy link
Copy Markdown
Member

@Sharawey74 I am very sorry but @arturobernalg changes in #3336 are too big for 5.7 release. This will also block your changes. I am sorry about that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

5.8.x 5.8 release series

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[HTTPCLIENT-2436] Async connect does not retry next resolved address after TLS handshake failure, unlike classic

5 participants