Skip to content

Commit a0a1b72

Browse files
authored
Merge pull request #817 from hardikkaurani/fix/http-redirect-port-same-origin
fix(http): consider port in redirect handler same origin check
2 parents 9ff5c10 + 69925c0 commit a0a1b72

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

‎packages/http/httpx/kiota_http/middleware/redirect_handler.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,4 +247,4 @@ def _same_origin(self, url: httpx.URL, other: httpx.URL) -> bool:
247247
"""
248248
Return 'True' if the given URLs share the same origin.
249249
"""
250-
return (url.scheme == other.scheme and url.host == other.host)
250+
return (url.scheme == other.scheme and url.host == other.host and url.port == other.port)

‎packages/http/httpx/tests/middleware_tests/test_redirect_handler.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,41 @@ def test_not_same_origin(mock_redirect_handler):
156156
assert not mock_redirect_handler._same_origin(origin1, origin2)
157157

158158

159+
def test_not_same_origin_different_port(mock_redirect_handler):
160+
origin1 = httpx.URL(BASE_URL)
161+
origin2 = httpx.URL(f"{BASE_URL}:8443")
162+
assert not mock_redirect_handler._same_origin(origin1, origin2)
163+
164+
165+
@pytest.mark.asyncio
166+
async def test_redirect_to_different_port_updates_host_header():
167+
"""Test that if a request is redirected to a different port on the same host,
168+
the Host header is updated with the new port."""
169+
170+
redirect_target = "https://example.com:8443/foo"
171+
172+
def request_handler(request: httpx.Request):
173+
if str(request.url) == redirect_target:
174+
return httpx.Response(200)
175+
return httpx.Response(
176+
FOUND,
177+
headers={LOCATION_HEADER: redirect_target},
178+
)
179+
180+
handler = RedirectHandler()
181+
request = httpx.Request(
182+
"GET",
183+
BASE_URL,
184+
headers={"Host": "example.com"},
185+
)
186+
mock_transport = httpx.MockTransport(request_handler)
187+
resp = await handler.send(request, mock_transport)
188+
assert resp.status_code == 200
189+
assert resp.request != request
190+
assert resp.request.url == redirect_target
191+
assert resp.request.headers["Host"] == "example.com:8443"
192+
193+
159194

160195

161196
@pytest.mark.asyncio

0 commit comments

Comments
 (0)