Set host on new request correctly (#536)

### Motivation
If we follow a redirect which changes the origin e.g. from `127.0.0.1` to `localhost` we didn't change the `Host` header to the appropriate new origin and port combination.
### Changes
Use the original request which does not include the host instead of the prepared request to form a new request to the redirect URL.

### Alternatives
If the user defines a `Host` header themselves on the original `HTTPClientRequest` we currently never touch it, even in the redirect case. Maybe we should change our strategy and do one of the following:
1. We could always override the user defined `Host` header
2. We could only remove the user defined `Host` header on redirect and set it to the new origin and port combination
This commit is contained in:
David Nadoba
2021-12-24 12:31:24 +01:00
committed by GitHub
parent e531961906
commit 19e83a35df
4 changed files with 44 additions and 6 deletions
@@ -75,7 +75,11 @@ extension HTTPClient {
try redirectState.redirect(to: redirectURL.absoluteString)
currentRedirectState = redirectState
let newRequest = preparedRequest.followingRedirect(to: redirectURL, status: response.status)
let newRequest = currentRequest.followingRedirect(
from: preparedRequest.url,
to: redirectURL,
status: response.status
)
guard newRequest.body.canBeConsumedMultipleTimes else {
// we already send the request body and it cannot be send again
@@ -75,12 +75,16 @@ extension RequestBodyLength {
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension HTTPClientRequest.Prepared {
func followingRedirect(to redirectURL: URL, status: HTTPResponseStatus) -> HTTPClientRequest {
extension HTTPClientRequest {
func followingRedirect(
from originalURL: URL,
to redirectURL: URL,
status: HTTPResponseStatus
) -> HTTPClientRequest {
let (method, headers, body) = transformRequestForRedirect(
from: self.url,
method: self.head.method,
headers: self.head.headers,
from: originalURL,
method: self.method,
headers: self.headers,
body: self.body,
to: redirectURL,
status: status