From 90d71b6d701a98850fe5a9378732a7c825455081 Mon Sep 17 00:00:00 2001 From: Matthias Kurz Date: Thu, 26 Nov 2026 09:56:44 +0100 Subject: [PATCH] Keep the raw URI in tunnels and auth retries Three interceptors send a copy of the request they handle, made with toBuilder(): ConnectSuccessInterceptor for the first request in a new tunnel, and the 401 and 407 interceptors for the retry with credentials. toBuilder() encodes the URI again, so a request built with URL encoding disabled was sent encoded: /a|b?q={x} went out as /a%7Cb?q=%7Bx%7D. That hit the https, wss or ws request that opens a tunnel through an HTTP or HTTPS proxy, every retry after a 401, and every retry after a 407 to an http request. A request that takes a pooled tunnel is not copied. Copy a DefaultRequest with URL encoding disabled instead, as #2393 does for a Range header, through one package-private builder that the three interceptors share. Another Request implementation still goes through its own toBuilder(), which copies it as before. The copies are still copies, so nothing else about them changes. Claude Code on behalf of Matthias Kurz Co-Authored-By: Claude Opus 5.5 --- .../handler/intercept/CallerCookies.java | 6 +- .../intercept/ConnectSuccessInterceptor.java | 2 +- .../intercept/PrototypeRequestBuilder.java | 40 +++++ .../ProxyUnauthorized407Interceptor.java | 10 +- .../intercept/Unauthorized401Interceptor.java | 10 +- .../intercept/AuthRetryRawUriTest.java | 158 ++++++++++++++++++ .../asynchttpclient/proxy/HttpsProxyTest.java | 65 +++++++ 7 files changed, 279 insertions(+), 12 deletions(-) create mode 100644 client/src/main/java/org/asynchttpclient/netty/handler/intercept/PrototypeRequestBuilder.java create mode 100644 client/src/test/java/org/asynchttpclient/netty/handler/intercept/AuthRetryRawUriTest.java diff --git a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/CallerCookies.java b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/CallerCookies.java index bee7a2a46..83b4ffd8b 100644 --- a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/CallerCookies.java +++ b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/CallerCookies.java @@ -19,7 +19,7 @@ import io.netty.handler.codec.http.cookie.ClientCookieDecoder; import io.netty.handler.codec.http.cookie.Cookie; import org.asynchttpclient.Request; -import org.asynchttpclient.RequestBuilder; +import org.asynchttpclient.RequestBuilderBase; import org.asynchttpclient.StoreCookies; import org.asynchttpclient.cookie.CookieStore; import org.asynchttpclient.uri.Uri; @@ -101,12 +101,12 @@ private static Set replacedNames(HttpResponse response, List nex /** * For a retry of the same request: the caller's cookies, then the store's current ones. */ - static void refresh(RequestBuilder retry, Request request, HttpResponse response, CookieStore cookieStore, + static void refresh(RequestBuilderBase retry, Request request, HttpResponse response, CookieStore cookieStore, ClientCookieDecoder cookieDecoder) { refresh(retry, request, response, cookieStore, request.getUri(), cookieDecoder); } - static void refresh(RequestBuilder retry, Request request, HttpResponse response, CookieStore cookieStore, + static void refresh(RequestBuilderBase retry, Request request, HttpResponse response, CookieStore cookieStore, Uri next, ClientCookieDecoder cookieDecoder) { List nextCookies = cookieStore.get(next); Set setByResponse = replacedNames(response, nextCookies, request.getUri(), next, cookieDecoder); diff --git a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ConnectSuccessInterceptor.java b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ConnectSuccessInterceptor.java index 9d0948554..2c0ffb6da 100644 --- a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ConnectSuccessInterceptor.java +++ b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ConnectSuccessInterceptor.java @@ -82,7 +82,7 @@ public boolean exitAfterHandlingConnect(Channel channel, NettyResponseFuture // the origin's credentials. Nothing else may set this — see NettyRequestSender#isConnectAlreadyDone. future.setTunnelEstablished(true); - Request targetRequest = future.getTargetRequest().toBuilder().build(); + Request targetRequest = PrototypeRequestBuilder.copyOf(future.getTargetRequest()).build(); if (whenHandshaked == null) { requestSender.drainChannelAndExecuteNextRequest(channel, future, targetRequest); } else { diff --git a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/PrototypeRequestBuilder.java b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/PrototypeRequestBuilder.java new file mode 100644 index 000000000..4337cb51b --- /dev/null +++ b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/PrototypeRequestBuilder.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2026 AsyncHttpClient Project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asynchttpclient.netty.handler.intercept; + +import org.asynchttpclient.DefaultRequest; +import org.asynchttpclient.Request; +import org.asynchttpclient.RequestBuilderBase; + +/** + * Copies a request as {@link Request#toBuilder()} does, but keeps its URI as it is: {@code toBuilder()} encodes the + * URI again, which changes one built with URL encoding disabled. + */ +final class PrototypeRequestBuilder extends RequestBuilderBase { + + private PrototypeRequestBuilder(Request prototype) { + super(prototype, true, false); + } + + /** + * A builder for a copy of {@code request} with its URI as it is. Exact class only: a subclass or another + * {@link Request} implementation goes through its own {@link Request#toBuilder()}, as it may override what the + * builder copies. + */ + static RequestBuilderBase copyOf(Request request) { + return request.getClass() == DefaultRequest.class ? new PrototypeRequestBuilder(request) : request.toBuilder(); + } +} diff --git a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ProxyUnauthorized407Interceptor.java b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ProxyUnauthorized407Interceptor.java index 77bf1e385..b3e2fe9a0 100644 --- a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ProxyUnauthorized407Interceptor.java +++ b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ProxyUnauthorized407Interceptor.java @@ -24,7 +24,7 @@ import org.asynchttpclient.Realm; import org.asynchttpclient.Realm.AuthScheme; import org.asynchttpclient.Request; -import org.asynchttpclient.RequestBuilder; +import org.asynchttpclient.RequestBuilderBase; import org.asynchttpclient.netty.NettyResponseFuture; import org.asynchttpclient.netty.channel.ChannelManager; import org.asynchttpclient.netty.channel.ChannelState; @@ -172,7 +172,8 @@ public boolean exitAfterHandling407(Channel channel, NettyResponseFuture futu future.setChannelState(ChannelState.NEW); HttpHeaders requestHeaders = new DefaultHttpHeaders().add(request.getHeaders()); - RequestBuilder nextRequestBuilder = future.getCurrentRequest().toBuilder().setHeaders(requestHeaders); + RequestBuilderBase nextRequestBuilder = PrototypeRequestBuilder.copyOf(future.getCurrentRequest()) + .setHeaders(requestHeaders); refreshCookies(nextRequestBuilder, request, response); if (future.getCurrentRequest().getUri().isSecured()) { nextRequestBuilder.setMethod(CONNECT); @@ -325,7 +326,8 @@ public boolean exitAfterHandling407(Channel channel, NettyResponseFuture futu throw new IllegalStateException("Invalid Authentication scheme " + proxyRealm.getScheme()); } - RequestBuilder nextRequestBuilder = future.getCurrentRequest().toBuilder().setHeaders(requestHeaders); + RequestBuilderBase nextRequestBuilder = PrototypeRequestBuilder.copyOf(future.getCurrentRequest()) + .setHeaders(requestHeaders); refreshCookies(nextRequestBuilder, request, response); if (future.getCurrentRequest().getUri().isSecured()) { nextRequestBuilder.setMethod(CONNECT); @@ -382,7 +384,7 @@ private static void ntlmProxyChallenge(String authenticateHeader, HttpHeaders re } } // The challenge may have set cookies, and the retry has to carry those, not the values it went out with. - private void refreshCookies(RequestBuilder retry, Request request, HttpResponse response) { + private void refreshCookies(RequestBuilderBase retry, Request request, HttpResponse response) { CookieStore cookieStore = config.getCookieStore(); if (cookieStore != null) { CallerCookies.refresh(retry, request, response, cookieStore, cookieDecoder); diff --git a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Unauthorized401Interceptor.java b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Unauthorized401Interceptor.java index 72ba3782d..884667f48 100644 --- a/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Unauthorized401Interceptor.java +++ b/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Unauthorized401Interceptor.java @@ -49,7 +49,7 @@ import org.asynchttpclient.AsyncHttpClientConfig; import io.netty.handler.codec.http.cookie.ClientCookieDecoder; import org.asynchttpclient.cookie.CookieStore; -import org.asynchttpclient.RequestBuilder; +import org.asynchttpclient.RequestBuilderBase; import static io.netty.handler.codec.http.HttpHeaderNames.AUTHORIZATION; import static io.netty.handler.codec.http.HttpHeaderNames.WWW_AUTHENTICATE; @@ -143,7 +143,8 @@ public boolean exitAfterHandling401(Channel channel, NettyResponseFuture futu future.setChannelState(ChannelState.NEW); HttpHeaders requestHeaders = new DefaultHttpHeaders().add(request.getHeaders()); - RequestBuilder retry = future.getCurrentRequest().toBuilder().setHeaders(requestHeaders); + RequestBuilderBase retry = PrototypeRequestBuilder.copyOf(future.getCurrentRequest()) + .setHeaders(requestHeaders); refreshCookies(retry, request, response); final Request nextRequest = retry.build(); if (LOGGER.isDebugEnabled()) { @@ -291,7 +292,8 @@ public boolean exitAfterHandling401(Channel channel, NettyResponseFuture futu throw new IllegalStateException("Invalid Authentication scheme " + realm.getScheme()); } - RequestBuilder retry = future.getCurrentRequest().toBuilder().setHeaders(requestHeaders); + RequestBuilderBase retry = PrototypeRequestBuilder.copyOf(future.getCurrentRequest()) + .setHeaders(requestHeaders); refreshCookies(retry, request, response); final Request nextRequest = retry.build(); @@ -349,7 +351,7 @@ private static void kerberosChallenge(Realm realm, Request request, HttpHeaders headers.set(AUTHORIZATION, NEGOTIATE + ' ' + challengeHeader); } // The challenge may have set cookies, and the retry has to carry those, not the values it went out with. - private void refreshCookies(RequestBuilder retry, Request request, HttpResponse response) { + private void refreshCookies(RequestBuilderBase retry, Request request, HttpResponse response) { CookieStore cookieStore = config.getCookieStore(); if (cookieStore != null) { CallerCookies.refresh(retry, request, response, cookieStore, cookieDecoder); diff --git a/client/src/test/java/org/asynchttpclient/netty/handler/intercept/AuthRetryRawUriTest.java b/client/src/test/java/org/asynchttpclient/netty/handler/intercept/AuthRetryRawUriTest.java new file mode 100644 index 000000000..c1b192984 --- /dev/null +++ b/client/src/test/java/org/asynchttpclient/netty/handler/intercept/AuthRetryRawUriTest.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2026 AsyncHttpClient Project. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.asynchttpclient.netty.handler.intercept; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.asynchttpclient.AbstractBasicTest; +import org.asynchttpclient.AsyncHttpClient; +import org.asynchttpclient.BoundRequestBuilder; +import org.asynchttpclient.Realm; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; + +import static io.netty.handler.codec.http.HttpHeaderNames.AUTHORIZATION; +import static io.netty.handler.codec.http.HttpHeaderNames.PROXY_AUTHENTICATE; +import static io.netty.handler.codec.http.HttpHeaderNames.PROXY_AUTHORIZATION; +import static io.netty.handler.codec.http.HttpHeaderNames.WWW_AUTHENTICATE; +import static org.asynchttpclient.Dsl.asyncHttpClient; +import static org.asynchttpclient.Dsl.basicAuthRealm; +import static org.asynchttpclient.Dsl.config; +import static org.asynchttpclient.Dsl.digestAuthRealm; +import static org.asynchttpclient.Dsl.proxyServer; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The retry that answers a 401 or a 407 is a copy of the request that was challenged, and must keep its request + * target as it was built: for a request built with URL encoding disabled, that is not the encoded form. + */ +public class AuthRetryRawUriTest extends AbstractBasicTest { + + private static final String TARGET = "/a|b?q={x}"; + private static final String ENCODED_TARGET = "/a%7Cb?q=%7Bx%7D"; + private static final String BASIC = "Basic realm=\"r\""; + private static final String DIGEST = "Digest realm=\"r\", nonce=\"n\", qop=\"auth\""; + + private final List targets = new CopyOnWriteArrayList<>(); + private volatile Challenge challenge; + + // Answers a request without credentials with the challenge, and records each request target as it arrived. + @Override + public AbstractHandler configureHandler() { + return new AbstractHandler() { + @Override + public void handle(String s, Request r, HttpServletRequest request, HttpServletResponse response) { + targets.add(request.getRequestURI() + '?' + request.getQueryString()); + Challenge current = challenge; + if (request.getHeader(current.credentialsHeader) == null) { + response.setStatus(current.status); + response.setHeader(current.challengeHeader, current.challenge); + } + r.setHandled(true); + } + }; + } + + @BeforeEach + public void clearTargets() { + targets.clear(); + } + + @Test + public void aBasicRetryKeepsAUriBuiltWithoutEncoding() throws Exception { + challengeWith(401, WWW_AUTHENTICATE, BASIC, AUTHORIZATION); + + sendThroughTheChallenge(true, basicAuthRealm("user", "secret"), false); + + assertEquals(List.of(TARGET, TARGET), targets); + } + + @Test + public void aDigestRetryKeepsAUriBuiltWithoutEncoding() throws Exception { + challengeWith(401, WWW_AUTHENTICATE, DIGEST, AUTHORIZATION); + + sendThroughTheChallenge(true, digestAuthRealm("user", "secret"), false); + + assertEquals(List.of(TARGET, TARGET), targets); + } + + @Test + public void aBasicProxyRetryKeepsAUriBuiltWithoutEncoding() throws Exception { + challengeWith(407, PROXY_AUTHENTICATE, BASIC, PROXY_AUTHORIZATION); + + sendThroughTheChallenge(true, basicAuthRealm("user", "secret"), true); + + assertEquals(List.of(TARGET, TARGET), targets); + } + + @Test + public void aDigestProxyRetryKeepsAUriBuiltWithoutEncoding() throws Exception { + challengeWith(407, PROXY_AUTHENTICATE, DIGEST, PROXY_AUTHORIZATION); + + sendThroughTheChallenge(true, digestAuthRealm("user", "secret"), true); + + assertEquals(List.of(TARGET, TARGET), targets); + } + + @Test + public void aRetryKeepsAnEncodedUri() throws Exception { + challengeWith(401, WWW_AUTHENTICATE, BASIC, AUTHORIZATION); + + sendThroughTheChallenge(false, basicAuthRealm("user", "secret"), false); + + assertEquals(List.of(ENCODED_TARGET, ENCODED_TARGET), targets); + } + + private void challengeWith(int status, CharSequence challengeHeader, String challenge, + CharSequence credentialsHeader) { + this.challenge = new Challenge(status, challengeHeader.toString(), challenge, credentialsHeader.toString()); + } + + // As a proxy, the server receives the request for an origin it never connects to. + private void sendThroughTheChallenge(boolean disableUrlEncoding, Realm.Builder realm, boolean toTheProxy) + throws Exception { + Realm notPreemptive = realm.setUsePreemptiveAuth(false).build(); + try (AsyncHttpClient client = asyncHttpClient(config() + .setDisableUrlEncodingForBoundRequests(disableUrlEncoding))) { + BoundRequestBuilder request = toTheProxy + ? client.prepareGet("http://origin.example" + TARGET) + .setProxyServer(proxyServer("localhost", port1).setRealm(notPreemptive)) + : client.prepareGet("http://localhost:" + port1 + TARGET).setRealm(notPreemptive); + + assertEquals(200, request.execute().get(TIMEOUT, TimeUnit.SECONDS).getStatusCode()); + } + } + + private static final class Challenge { + final int status; + final String challengeHeader; + final String challenge; + final String credentialsHeader; + + Challenge(int status, String challengeHeader, String challenge, String credentialsHeader) { + this.status = status; + this.challengeHeader = challengeHeader; + this.challenge = challenge; + this.credentialsHeader = credentialsHeader; + } + } +} diff --git a/client/src/test/java/org/asynchttpclient/proxy/HttpsProxyTest.java b/client/src/test/java/org/asynchttpclient/proxy/HttpsProxyTest.java index 01b98774a..866f70ba9 100644 --- a/client/src/test/java/org/asynchttpclient/proxy/HttpsProxyTest.java +++ b/client/src/test/java/org/asynchttpclient/proxy/HttpsProxyTest.java @@ -19,6 +19,7 @@ import org.asynchttpclient.AbstractBasicTest; import org.asynchttpclient.AsyncHttpClient; import org.asynchttpclient.AsyncHttpClientConfig; +import org.asynchttpclient.DefaultRequest; import org.asynchttpclient.RequestBuilder; import org.asynchttpclient.Response; import org.asynchttpclient.proxy.ProxyServer.Builder; @@ -44,6 +45,8 @@ import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import static org.asynchttpclient.Dsl.asyncHttpClient; @@ -297,6 +300,68 @@ public void testClosedConnectionWithProxy(String testName, ProxyType proxyType) } } + @Test + public void testTunnelledRequestKeepsAUriBuiltWithoutEncoding() throws Exception { + assertTunnelledRequestTarget(true, "/a|b?q={x}"); + } + + @Test + public void testTunnelledRequestKeepsAnEncodedUri() throws Exception { + assertTunnelledRequestTarget(false, "/a%7Cb?q=%7Bx%7D"); + } + + // The origin records the request target as it arrived, before any decoding. + private void assertTunnelledRequestTarget(boolean disableUrlEncoding, String expected) throws Exception { + AtomicReference target = new AtomicReference<>(); + int originPort = startServer(new AbstractHandler() { + @Override + public void handle(String s, Request r, HttpServletRequest request, HttpServletResponse response) { + target.set(request.getRequestURI() + '?' + request.getQueryString()); + r.setHandled(true); + } + }, true); + + try (AsyncHttpClient client = asyncHttpClient(config() + .setUseInsecureTrustManager(true) + .setDisableUrlEncodingForBoundRequests(disableUrlEncoding))) { + Response response = client.prepareGet("https://localhost:" + originPort + "/a|b?q={x}") + .setProxyServer(proxyServer("localhost", proxyPort)) + .execute() + .get(30, TimeUnit.SECONDS); + + assertEquals(200, response.getStatusCode()); + assertEquals(expected, target.get()); + } + } + + @Test + public void testTunnelledRequestGoesThroughToBuilderForRequestSubclass() throws Exception { + org.asynchttpclient.Request built = get(getTargetUrl2()) + .setProxyServer(proxyServer("localhost", proxyPort)) + .build(); + AtomicInteger toBuilderCalls = new AtomicInteger(); + org.asynchttpclient.Request request = new DefaultRequest(built.getMethod(), built.getUri(), built.getAddress(), + built.getLocalAddress(), built.getHeaders(), built.getCookies(), built.getByteData(), + built.getCompositeByteData(), built.getStringData(), built.getByteBufferData(), built.getByteBufData(), + built.getStreamData(), built.getBodyGenerator(), built.getFormParams(), built.getBodyParts(), + built.getVirtualHost(), built.getProxyServer(), built.getRealm(), built.getFile(), + built.getFollowRedirect(), built.getRequestTimeout(), built.getReadTimeout(), built.getRangeOffset(), + built.getCharset(), built.getChannelPoolPartitioning(), built.getNameResolver()) { + @Override + public RequestBuilder toBuilder() { + toBuilderCalls.incrementAndGet(); + return super.toBuilder(); + } + }; + + try (AsyncHttpClient client = asyncHttpClient(config().setUseInsecureTrustManager(true))) { + Response response = client.executeRequest(request).get(30, TimeUnit.SECONDS); + + assertEquals(200, response.getStatusCode()); + assertEquals(1, toBuilderCalls.get()); + } + } + @Test public void testHttpsProxyType() throws Exception { // Test that HTTPS proxy type can be configured and behaves correctly