Skip to content

Add stored cookies without rebuilding the request - #2384

Merged
hyperxpro merged 4 commits into
AsyncHttpClient:mainfrom
maygemdev:claude/cookie-request-rebuild-a5ef24
Nov 14, 2026
Merged

hyperxpro merged 4 commits into
AsyncHttpClient:mainfrom
maygemdev:claude/cookie-request-rebuild-a5ef24

Conversation

@pavel-ptashyts

@pavel-ptashyts pavel-ptashyts commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When the client's cookie store has a cookie for the request URI, DefaultAsyncHttpClient.executeRequest adds it with request.toBuilder(), addCookieIfUnset and build(). That rebuild copies every header into a new header set, copies the cookie, form param and body part lists twice and encodes the URI again, on every request that carries a session cookie.

The URI step is also a bug. toBuilder() always uses the fixing URI encoder, so a request built with URL encoding disabled is re-encoded, but only when the store has a cookie for it:

Request request = new RequestBuilder("GET", true).setUrl("http://localhost/a|b?q={x}").build();
// no stored cookie:   http://localhost/a|b?q={x}
// with stored cookie: http://localhost/a%7Cb?q=%7Bx%7D   (on main)

Changes:

  1. DefaultRequest.withCookies (package-private) returns a request that differs only by its cookie list. The URI is kept as built and the other fields are shared, not copied.
  2. executeRequest merges the stored cookies into a new list with the same rule as addCookieIfUnset: the request's own cookies first and never replaced, then each stored cookie whose name is not there yet, so the first stored cookie of a name wins. If every stored name is already set, the request is passed on unchanged. A null cookie list (possible through the public DefaultRequest constructor) is treated as empty, as the builder did.
  3. Other Request implementations, including subclasses of DefaultRequest, still go through toBuilder(), as they may override what it copies.
  4. StoredCookieRequestBenchmark measures executeRequest up to the request filters with and without a matching stored cookie.

Behaviour notes

  • Same cookies, in the same order, as before, with names compared case-sensitively as addCookieIfUnset does. The only intended difference is that the URI is no longer re-encoded on this path.
  • The new request shares the original's HttpHeaders object and lists. Without a matching stored cookie (or with the cookie store disabled) executeRequest already passes the caller's request, with the same objects, to the filters and the sender, so the copy was incidental to the cookie path. No production code mutates request.getHeaders(): the redirect and auth interceptors copy first. Before this change the rebuild hid a missing copy for every request with a stored cookie, so a test now executes one request twice across a cross-origin 302 with a stored cookie and checks that its headers are unchanged.
  • No public API change: withCookies is package-private, the new helpers in DefaultAsyncHttpClient are private. Revapi passes.

Not changed here: these paths also go through toBuilder() and so still re-encode a URI built with URL encoding disabled. They are not on the per-request path and change more than the cookies, so they are left for a separate change:

  • preProcessRequest, for a request with a range offset, and ResumableAsyncHandler.adjustRequestRange;
  • the retry built by Unauthorized401Interceptor and ProxyUnauthorized407Interceptor;
  • the target request rebuilt by ConnectSuccessInterceptor after a proxy CONNECT.

So a request built with URL encoding disabled keeps its URI when a stored cookie is added, but not yet on an auth retry or through a tunnelling proxy.

Benchmark

StoredCookieRequestBenchmark, JMH 1.37, JDK 17.0.2, Windows, -prof gc, 5 x 1 s warmup, 5 x 1 s measurement, main against this branch. A request filter ends each call by throwing a preallocated exception, so nothing reaches the network; both arms then build the same failed future. noStoredCookie sends to a host with no stored cookie and is the baseline.

Bytes/op with escape analysis off (-XX:-DoEscapeAnalysis, 1 fork), which gives exact allocation counts:

Arm Headers main This PR
storedCookie 4 1928 1320
storedCookie 16 2408 1320
noStoredCookie 4 1008 1008
noStoredCookie 16 1008 1008

Adding the stored cookie costs 920 to 1400 bytes on main, growing with the header count, and 312 bytes here, independent of it (the store lookup's list, the merged cookie list and the new request).

With default JVM flags (2 forks) escape analysis removes part of it, so the figures vary by a few dozen bytes between forks: storedCookie 1800 -> 1056 B/op with 4 headers and 2184 -> 1272 B/op with 16. The host was running other builds, so the timings had error bars of 50 to 100 percent and are not reported.

Tests

New tests in DefaultAsyncHttpClientTest capture the request that reaches the filters, with no server:

  • a request built with URL encoding disabled keeps its URL (fails on main with the re-encoded URL above);
  • request cookies are not replaced by stored ones, and the original request is not modified;
  • a request that already has a cookie of every stored name is passed on as is;
  • the first stored cookie of a name wins;
  • cookie names are compared case-sensitively (SID on the request and sid in the store both go out);
  • every other field of DefaultRequest is carried over as the same object, checked reflectively on requests that set every field to a non-null value no other field holds, except the Boolean flags; across three such requests each flag takes both values and each pair of flags differs, so a swapped flag or a constant in its place fails;
  • a subclass of DefaultRequest goes through its toBuilder();
  • a DefaultRequest with a null cookie list gets the stored cookies.

RedirectCredentialSecurityTest.crossDomainRedirectLeavesCallerRequestHeadersUnchanged executes one built request with Authorization and Cookie headers and a stored cookie twice across a cross-origin 302, and checks after each run that the request's headers are unchanged, that the stored cookie was sent (so the run went through withCookies) and that both runs sent the credentials to the first origin only.

./mvnw clean verify -Dgpg.skip=true passes on JDK 17 (2001 tests; no JDK 11 and no gpg on the host); CI covers JDK 11.

Second-agent review

Both reviewers ran from fresh CLI sessions, read-only, with the intent and constraints in the prompt.

Reviewer Agent and model Effort Commit reviewed Result
Guided (against AGENTS.md, on git diff upstream/main...HEAD) Codex gpt-6-astra medium 5b54dd8 No findings
Independent (no checklist, reads the files) Claude Code claude-opus-5-5 medium 5b54dd8 No findings

Six rounds in all: three before the PR was opened (15ece6b, 3c843f5, f7ff016), and three on the commit that answers the maintainer review (rounds 4 to 6; it was amended before the push after rounds 4 and 5). Fixed from earlier rounds:

  • the field test set all four Boolean flags to true, so a swap of two of them in withCookies would pass; now two requests make every pair differ (checked by swapping two flags, which fails the test), and the body fields are compared too;
  • added tests for the subclass path and for the first stored cookie of a name;
  • a DefaultRequest with a null cookie list failed only on the stored-cookie path; it is now treated as empty;
  • round 4 (independent reviewer, nit): the redirect test did not check that the stored cookie was added, so it could silently stop going through withCookies; it now asserts that the cookie reached the first origin;
  • round 5 (independent reviewer, nit): both requests in the field test had the same followRedirect and refuseCrossOriginBodyOnRedirect, so passing Boolean constants for those two would pass; a third request now gives each flag both values.

Not changed:

  • Shared HttpHeaders and lists (round 1, guided reviewer as a bug, independent reviewer as a nit). A filter or a reused RequestBuilder that mutates them now reaches the original request also when a stored cookie matched. The path without a matching stored cookie already behaves that way, as described under behaviour notes, and deep-copying the headers is the cost this change removes.
  • Normalisation that build() did for a hand-built DefaultRequest (round 1, independent reviewer, nit), such as a null charset. Such a request fails the same way without a stored cookie.

Claude Code on behalf of Pavel Ptashyts

🤖 Generated with Claude Code

pavel-ptashyts and others added 3 commits November 7, 2026 20:13
When the cookie store had a cookie for the request URI,
executeRequest ran request.toBuilder() and build() to add it. That
copied every header into a new header set, copied the cookie, form
param and body part lists twice and encoded the URI again, on every
request that carries a session cookie.

The URI step was also a bug. toBuilder() always uses the fixing URI
encoder, so a request built with URL encoding disabled was sent
encoded, but only when the store had a cookie for it: "/a|b?q={x}"
went out as "/a%7Cb?q=%7Bx%7D".

A DefaultRequest is now copied with only its cookie list replaced
and its URI kept as built, and is returned unchanged when it already
carries a cookie of every stored name. Other Request implementations
still go through toBuilder(), as they may override what it copies.

Claude Code on behalf of Pavel Ptashyts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The field test set all four Boolean flags to true, so swapping two
adjacent Boolean parameters in DefaultRequest.withCookies would still
pass. It now uses two requests in which every pair of flags differs,
and compares the body fields too. New tests check that the first
stored cookie of a name wins and that a DefaultRequest subclass still
goes through toBuilder().

Claude Code on behalf of Pavel Ptashyts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A DefaultRequest made through its public constructor may carry a
null cookie list. The toBuilder() path treated it as empty, so the
new path failed with a NullPointerException only when the cookie
store had a cookie for the request, while the same request without
a stored cookie was sent.

Claude Code on behalf of Pavel Ptashyts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of AsyncHttpClient#2384 found gaps the tests let through. The field test
used requests with no file, stream or byte body, so withCookies could
drop those fields unnoticed: it now builds requests with every field
set to a distinct non-null value and compares the fields reflectively.
A request cookie SID and a stored cookie sid both go out, which pins
the case-sensitive name match. Sharing the caller's headers relies on
the redirect interceptor copying them before stripping credentials;
a test now executes one request twice across a cross-origin 302 with
a stored cookie and checks its headers are unchanged.

The withCookies javadoc no longer says a raw URI is sent as written:
auth retries and CONNECT still rebuild the request through toBuilder.

Claude Code on behalf of Pavel Ptashyts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@hyperxpro hyperxpro left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, thanks!

@hyperxpro
hyperxpro merged commit 7846624 into AsyncHttpClient:main Nov 14, 2026
13 checks passed
@pavel-ptashyts
pavel-ptashyts deleted the claude/cookie-request-rebuild-a5ef24 branch November 14, 2026 18:04
hyperxpro pushed a commit that referenced this pull request Nov 20, 2026
## Summary

`Request.toBuilder()` always uses the fixing URI encoder. So a request
built with URL encoding disabled is sent re-encoded as soon as a `Range`
header is added to it, on either of the two paths that add one:

```java
Request request = new RequestBuilder("GET", true).setUrl("http://localhost/a|b?q={x}").setRangeOffset(5).build();
// request line on main:   GET /a%7Cb?q=%7Bx%7D HTTP/1.1
// request line with this: GET /a|b?q={x} HTTP/1.1
```

1. `DefaultAsyncHttpClient.preProcessRequest`, for a request with a
range offset, ran `toBuilder()`, `setHeader("Range", ...)` and
`build()`.
2. `ResumableAsyncHandler.adjustRequestRange` did the same, and rebuilt
the request on every call, also when it set no header.

This is the same `toBuilder()` problem that #2384 fixed for stored
cookies; these two paths were listed there under "Not changed here".

Changes:

1. **`preProcessRequest`** sets the range through a new package-private
`withRangeHeader`. A `DefaultRequest` is copied through a new
package-private `RequestBuilder(Request, boolean disableUrlEncoding,
boolean validateHeaders)` constructor with `(request, true, false)`.
That is what `toBuilder()` does (`RequestBuilderBase(prototype, false,
false)`) with only the encoder changed: the prototype's URI is already
encoded, and the raw encoder returns it unchanged. Everything else
`build()` does (scheme check, charset, empty lists for a hand-built
request) still happens.
2. **`adjustRequestRange`** returns the request itself when it needs no
`Range` header (it has one, or no bytes were transferred yet). Otherwise
a `DefaultRequest` is copied the same way, by a private nested
`RequestBuilderBase` subclass, since the new `RequestBuilder`
constructor is not visible from `handler.resumable`.
3. Subclasses of `DefaultRequest` and other `Request` implementations
still go through `toBuilder()` on both paths, as they may override what
it copies.

Unlike #2384 this does not share fields with the original request: the
range-offset path is not a per-request path (it runs only for requests
with a range offset), so keeping `build()` in it is simpler than
reproducing what `build()` checks and fills in.

## Behaviour notes

- Same `Range` semantics as before: the resumable handler sets it only
when the request has none, and the range offset then replaces any
earlier value (all values, as `setHeader` did).
- `adjustRequestRange` now returns the same instance when it adds
nothing, so such a request goes on exactly as it does without a
resumable handler. Its callers (`preProcessRequest`,
`ResumableIOExceptionFilter`) do not depend on identity. One exception
keeps the old normalisation: a `DefaultRequest` built through its public
constructor with a null charset or a null cookie, form param or body
part list is still rebuilt, so `build()` fills those in as before. Other
`build()`-only effects, such as the scheme check, do not run on this
no-op path, just as they do not without the handler.
- No public API change: the new `RequestBuilder` constructor and
`withRangeHeader` are package-private, the nested builder is private.
Revapi passes.

## Also found, not changed here

`executeRequest` calls `preProcessRequest` only when the client has at
least one request filter (the `noRequestFilters` fast path, since
d61fb56 for #706). Without a request filter, `setRangeOffset` is
ignored and `ResumableAsyncHandler` adds no `Range` header to the first
request: on `main` a request with `setRangeOffset(5)` on a client
without filters reaches the server with no `Range` header. That is a
separate bug for a separate change. The wire tests here add a
pass-through request filter to reach the path.

## Tests

`DefaultAsyncHttpClientTest`, over a loopback `ServerSocket` that
records the request head:

- a request built with URL encoding disabled and a range offset goes out
with its URI as built, `Range: bytes=5-` and its other headers, and the
caller's request has no `Range` header afterwards (fails on `main` with
`GET /a%7Cb?q=%7Bx%7D`);
- the same through a `ResumableAsyncHandler` with a stored offset,
without and with a range offset (the offset replaces the handler's
`Range`);
- the range offset replaces two earlier `Range` values;
- a subclass of `DefaultRequest` goes through its `toBuilder()`.

The raw socket is used because these tests assert the request-target
bytes as sent. The Jetty server in `org.asynchttpclient.testserver`
exposes the decoded path (`getPathInfo`), which reads the same for
`/a|b` and `/a%7Cb`. `CrossHostReplayTest` and other tests use the same
pattern.

Calling `withRangeHeader` directly:

- every field of the result equals what `toBuilder()` produces, checked
reflectively;
- the request's headers are not validated, as with `toBuilder()` (a
`DefaultRequest` with non-validating `ReadOnlyHttpHeaders` holding an
illegal value and an illegal name keeps both);
- a hand-built `DefaultRequest` with null lists and charset gets them
filled in, with its raw URI kept;
- a hand-built `DefaultRequest` with an `ftp` URI is still rejected.

`ResumableAsyncHandlerTest`:

- a request built with URL encoding disabled keeps its URL (fails on
`main` with `http://localhost/a%7Cb?q=%7Bx%7D`);
- without an offset, or with a `Range` header already set, the request
is returned as is (both fail on `main`);
- every field of the rebuilt request equals what `toBuilder()` produces;
- the request's headers are not validated;
- a hand-built `DefaultRequest` with any one of the four fields null is
rebuilt and gets it filled in, and with all four null its raw URL is
kept, with and without a `Range` header added;
- a subclass of `DefaultRequest` goes through its `toBuilder()`, also
when it is rebuilt only for a null charset;
- an existing `Range` header is kept when a hand-built request is
rebuilt;
- a hand-built `DefaultRequest` with an `ftp` URI is still rejected when
it is rebuilt.

`./mvnw clean verify -Dgpg.skip=true` passes on JDK 17 (2083 tests; no
JDK 11 and no gpg on the host); CI covers JDK 11.

## Second-agent review

Both reviewers ran from fresh CLI sessions, read-only, with the intent
and constraints in the prompt.

| Reviewer | Agent and model | Effort | Commit reviewed | Result |
| --- | --- | --- | --- | --- |
| Guided (against `AGENTS.md`, on `git diff upstream/main...HEAD`) |
Codex `gpt-6-astra` | medium | 59b27b7 | No findings |
| Independent (no checklist, reads the files) | Claude Code
`claude-opus-5-5` | medium | 59b27b7 | No findings |

Nine rounds in all, the commit amended before the push after each round
with findings. Fixed from earlier rounds:

- the wire tests bound the server to `InetAddress.getLoopbackAddress()`
but sent to `127.0.0.1`, which fails where IPv6 is preferred; the server
now binds to `127.0.0.1` (round 1, guided);
- the accepted socket had no read timeout (round 2, guided);
- an earlier version shared fields with the original request through a
package-private `DefaultRequest.withHeaders`, as `withCookies` does.
Rounds 1 to 5 found what that skipped from `build()`: the header copy
validated headers that `toBuilder()` copied without validation (the base
`HttpHeaders.copy()` builds a validating `DefaultHttpHeaders`), null
lists and a null charset of a hand-built request were no longer filled
in, and the scheme check no longer ran. The range-offset path now keeps
`build()`, with only the encoder changed;
- tests added: every field of the rebuilt request on both paths, no
header validation on both paths, each null field on its own, the scheme
check, and the resumable handler and range offset together over the wire
(rounds 1 to 5, independent);
- a raw `0x01` byte in a test string literal is now written as `\u0001`
(round 3, independent);
- javadoc no longer says the URI "is already encoded", which a
hand-built request need not be, and a test comment no longer claims an
order of steps the test cannot see (round 7, independent);
- tests added for an existing `Range` header kept when a hand-built
request is rebuilt (round 7), and for a `DefaultRequest` subclass with a
null charset rebuilt through its `toBuilder()` and the scheme check on
the resumable rebuild path (round 8, independent).

Not changed:

- **The no-op path of `adjustRequestRange`** skips `build()`-only
effects such as the scheme check or deriving the charset from
`Content-Type` for a hand-built request with non-null fields (rounds 4
and 5, independent, risk and nit). Not rebuilding there is the point of
the change, and the request then goes on exactly as without a resumable
handler.

Claude Code on behalf of Pavel Ptashyts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
hyperxpro pushed a commit that referenced this pull request Nov 27, 2026
Two fixes and one stronger test, following #2408. Both fixes concern
behaviour released in 3.0.15.

## Stop a stale 407 flag from forcing a CONNECT

**Motivation:** When AHC answers a proxy's 407 on a kept-alive
connection, it flags the exchange so that the retry sends a CONNECT on
the connection it holds. Only a tunnel that opens clears the flag. So
after a 407 on a plain `http` request, the flag stays set for the rest
of the exchange, and a redirect or filter replay to an `https` URL sends
its request as a CONNECT too.

Since #2408, that attempt keeps the proxy's login after a cross-origin
hop, or takes the login of the proxy it moves to. The pool lookup is
scoped by that login, so the attempt finds a tunnel that an earlier
exchange pooled to the new target.
- **Before #2410,** the CONNECT was written into that tunnel, which
means to the origin, with a preemptive `Proxy-Authorization` and the
proxy's custom headers.
- **Since #2410, and so in 3.0.15,** a CONNECT never takes a pooled
channel. So the attempt opens another connection and tunnel to the proxy
instead, and the pooled tunnel goes unused.
- **Under a connection limit,** that extra connection can be one too
many. With `maxConnections` 2, a pooled tunnel and the plain `http`
request hold both permits, and the redirect fails with
`TooManyConnectionsException`, although the tunnel it could take is idle
in the pool.

**Modification:** The flag is cleared whenever an attempt sends the
exchange's target request, so only the 407's own retry sees it.

**Result:** The redirected or replayed request takes the tunnel from the
pool and is sent inside it, as it is when no 407 came earlier. It needs
no further connection, so a connection limit no longer fails it.

**Tests** cover:
- two proxies, with a preemptive login on the second;
- one proxy with the default login;
- one proxy with a custom header;
- one proxy with `maxConnections` 2, where the redirect has to reuse the
pooled tunnel;
- a guard where no tunnel is pooled.

They check that nothing but the request reaches the origin, that the
response is the redirected one, and that the pooled tunnel is reused.

## Keep the raw URI when a request changes proxy

**Motivation:** When a retry, redirect or filter replay goes through a
different proxy than the attempt before, AHC drops the
`Proxy-Authorization` header the request carries, because it was meant
for the previous proxy (#2408). It did so by copying the request with
`Request.toBuilder()`, which always encodes the URI again. A request
built with URL encoding disabled therefore reached the new proxy with a
different request target: `GET http://host/a|b?q={x}` became `GET
http://host/a%7Cb?q=%7Bx%7D`. #2384 and #2393 fixed the same
`toBuilder()` effect for stored cookies and the `Range` header.

**Modification:** A `DefaultRequest` is copied with the raw URI encoder,
through a private `RequestBuilderBase` subclass, as
`ResumableAsyncHandler` does since #2393. Subclasses and other `Request`
implementations still go through `toBuilder()`, as they may override
what it copies.

**Result:** The request reaches the new proxy with the URI it was built
with, minus the previous proxy's `Proxy-Authorization`. No public API
change.

## Check that a tunnel is pooled under its proxy

This commit only changes a test.

**Motivation:** The test for a selector that alternates between two
proxies only counted CONNECTs. Suppose the request entering a freshly
opened tunnel followed the selector to the other proxy. It would still
be written on the channel it holds, so no second tunnel would open and
the test would pass, while the channel is pooled under the other proxy's
key.

**Modification:** A second request, selected through the proxy that
opened the tunnel, has to reuse that tunnel from the pool.

**Result:** The test now fails if entering a tunnel moves the exchange
to another proxy.

## AI disclosure

Claude Code on behalf of Matthias Kurz. Every commit includes
`Co-Authored-By` per `AGENTS.md`.

## Test plan

All on JDK 11. Docker was not running, so the skipped tests include the
Testcontainers proxy tests.

- [x] `./mvnw -B -ntp -Dgpg.skip=true clean verify`: 2,497 tests, 0
failures, 22 skipped; Revapi passed against 3.0.15.
- [x] Focused proxy, tunnel, NTLM, SOCKS, `ProxyConnectRetryTest` and
`CallerContentLengthTest` suites: 172 tests, 0 failures. That run was on
`main` before the release commits and before the connection-limit test
was added.
- [x] `ProxyReselectionTest` 5 times: 35 of 35 each time.
- [x] **Each fix reverted:**
- Without the stale-flag fix, three of its five new tests fail. Two fail
because the redirect opens another connection instead of taking the
pooled tunnel. The third fails with `TooManyConnectionsException: Too
many connections: 2`. The other two tests already pass without it, since
#2410: one checks that the proxy's custom header does not reach the
origin, and one is the guard where no tunnel is pooled.
- Without the raw-URI copy, its test fails: the new proxy receives
`/a%7Cb?q=%7Bx%7D`.
- The strengthened tunnel test fails when every attempt follows the
selector; the old version passed.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
hyperxpro pushed a commit that referenced this pull request Nov 27, 2026
**Motivation:** Three interceptors send a copy of the request they
handle, made with `Request.toBuilder()`:
- `ConnectSuccessInterceptor`, for the first request in a new tunnel,
once the proxy accepts the CONNECT;
- `Unauthorized401Interceptor` and `ProxyUnauthorized407Interceptor`,
for the retry with credentials.

`toBuilder()` encodes the URI again, so a request built with URL
encoding disabled was sent with a different request target: `/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. #2384 and #2393 fixed the same
`toBuilder()` effect for stored cookies and the `Range` header, and
#2412 does for a request that changes proxy.

**Modification:** A `DefaultRequest` is copied with the raw URI encoder,
through one package-private `RequestBuilderBase` subclass that the three
interceptors share, as `ResumableAsyncHandler` does since #2393.
Subclasses and other `Request` implementations still go through
`toBuilder()`, as they may override what it copies.
`CallerCookies.refresh`, which gets the retry's builder, now takes any
`RequestBuilderBase`.

**Result:** For a `DefaultRequest`, the origin, or the proxy for an
`http` request, receives the request target as the request was built: on
the first request in a new tunnel, and on each retry with credentials.
Another `Request` implementation keeps the copy its own `toBuilder()`
makes. A request built with URL encoding enabled is sent as before.

**Tests:**
- **`HttpsProxyTest`:**
- an `https` request through an HTTP proxy, built with URL encoding
disabled and enabled, to an origin that records the request target as it
arrived;
- a `DefaultRequest` subclass, whose own `toBuilder()` still makes the
tunnel's request.
- **`AuthRetryRawUriTest`:** Basic and Digest retries after a 401 and
after a 407, plus a guard with URL encoding enabled. The server accepts
any credentials, so these check the request target only.

Reverting any one of the five copies fails exactly its own test, and so
does matching the class with `instanceof`.

**Not changed:** this doesn't cover every internal copy.
- `replayOfConnectRetry` (#2410) also copies with `toBuilder()`, when a
filter replays a CONNECT retry. It is left for the open question on
#2410.
- A 307 or 308 redirect also copies with `toBuilder()`, but sends the
URI from `Location`, not the one it copied.

## AI disclosure

Claude Code on behalf of Matthias Kurz. The commit includes
`Co-Authored-By` per `AGENTS.md`.

## Test plan

All on JDK 11. Docker was not running, so the skipped tests include the
Testcontainers proxy tests.

- [x] `./mvnw -B -ntp -Dgpg.skip=true clean verify`: 2,499 tests, 0
failures, 22 skipped; Revapi passed against 3.0.15.
- [x] `AuthRetryRawUriTest` and `HttpsProxyTest` 5 times: 20 of 20 each
time.
- [x] **Each change reverted on its own:** the 401 Digest and general
retries, the 407 Digest and general retries, and the tunnel each fail
exactly their own test. `instanceof` instead of the exact class fails
the subclass test.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@mkurz mkurz mentioned this pull request Nov 27, 2026
4 tasks done
hyperxpro pushed a commit that referenced this pull request Nov 30, 2026
**Motivation:** While AHC answers a proxy's 407 with a CONNECT retry, a
filter that replays is shown that CONNECT. `replayOfConnectRetry`, from
#2410, turns the replay back into the target request. If the filter
replays with a request of its own, that method copies it with
`toBuilder()`, and the default implementation encodes the URI again. A
`DefaultRequest` built with URL encoding disabled therefore went into
the tunnel with a different request target: `GET /a|b?q={x}` became `GET
/a%7Cb?q=%7Bx%7D`. #2384, #2393 and #2412 fixed the same `toBuilder()`
effect elsewhere. This is in 3.0.15.

It takes a replay with a new request. A filter that replays the request
it was shown, unchanged, gets the target back as it is, URI included.

Both kinds of filter get there:
- **A `ResponseFilter`,** for example on the proxy's 503 to the
authenticated CONNECT.
- **An `IOExceptionFilter`,** for example when the proxy drops the
connection during an NTLM handshake.

**Modification:** An exact `DefaultRequest` is copied with
`PrototypeRequestBuilder`, which #2412 added to `NettyRequestSender` for
the same reason. Subclasses and other `Request` implementations still go
through their own `toBuilder()`, as they may override what it copies.
Both copies in `NettyRequestSender` now share that rule through
`PrototypeRequestBuilder.copyOf`.

**Result:** AHC no longer encodes a replayed `DefaultRequest`'s URI
again, so it reaches the origin with the URI it was built with.

**Unchanged:** the cookies `replayOfConnectRetry` puts back. That
question is still open in [my comment on
#2410](#2410 (comment)).

**Tests,** in `ProxyConnectRetryTest`:
- **`replayingTheProxyAnswerKeepsTheRequestTarget`:** a response filter
replays the proxy's 503 to the authenticated CONNECT.
- **`replayingAConnectThatLostItsConnectionKeepsTheRequestTarget`:** an
IOException filter replays when the proxy drops the connection during
the NTLM handshake.
- **In both:**
- **The filter's request:** the filter replays with its own copy of the
request. It copies with a `RequestBuilderBase` subclass that keeps the
URI, and adds a header, so only AHC's copy could encode the URI again.
- **Expected:** the origin receives `GET /a|b?q={x}` with the filter's
header.
  - **Control:** with URL encoding enabled, `GET /a%7Cb?q=%7Bx%7D`.
- **Without the fix,** both cases with encoding disabled receive the
encoded target. The controls pass.
-
**`replayingTheProxyAnswerCopiesARequestSubclassThroughItsToBuilder`:**
a filter replays with a `DefaultRequest` subclass, and its `toBuilder()`
is called once. Copying every request with `PrototypeRequestBuilder`
fails it.

## AI disclosure

Claude Code on behalf of Matthias Kurz. The commit includes
`Co-Authored-By` per `AGENTS.md`.

## Test plan

All on JDK 11.

- [x] `./mvnw -B -ntp -Dgpg.skip=true clean verify`: 2,518 tests, 0
failures, 22 skipped; Revapi passed against 3.0.15. Docker was not
running, so the skipped tests include the Testcontainers proxy tests.
- [x] `ProxyConnectRetryTest` 5 times: 24 of 24 each time.
- [x] **Without the fix:** the two cases with URL encoding disabled
fail, and the origin receives `GET /a%7Cb?q=%7Bx%7D`. The other 22 tests
pass.
- [x] **Copying every request with `PrototypeRequestBuilder`:** the
subclass test fails, with `toBuilder()` called 0 times instead of 1. The
other 23 tests pass.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants