Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -101,12 +101,12 @@ private static Set<String> replacedNames(HttpResponse response, List<Cookie> 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<Cookie> nextCookies = cookieStore.get(next);
Set<String> setByResponse = replacedNames(response, nextCookies, request.getUri(), next, cookieDecoder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<PrototypeRequestBuilder> {

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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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()) {
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> 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;
}
}
}
65 changes: 65 additions & 0 deletions client/src/test/java/org/asynchttpclient/proxy/HttpsProxyTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<String> 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
Expand Down
Loading