diff --git a/CHANGELOG.md b/CHANGELOG.md index a3fa798973..6f2dd00fae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). * Expose `FunctionAuth` from the public API. (#3699) +### Fixed + +* `DigestAuth` no longer replays a cached `WWW-Authenticate` challenge to a different origin. + ## 0.28.1 (6th December, 2024) * Fix SSL case where `verify=False` together with client side certificates. diff --git a/httpx/_auth.py b/httpx/_auth.py index 9d24faed99..cb392574a9 100644 --- a/httpx/_auth.py +++ b/httpx/_auth.py @@ -188,10 +188,13 @@ def __init__(self, username: str | bytes, password: str | bytes) -> None: self._username = to_bytes(username) self._password = to_bytes(password) self._last_challenge: _DigestAuthChallenge | None = None + self._last_challenge_origin: tuple[str, bytes] | None = None self._nonce_count = 1 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: - if self._last_challenge: + origin = (request.url.scheme, request.url.netloc) + + if self._last_challenge and self._last_challenge_origin == origin: request.headers["Authorization"] = self._build_auth_header( request, self._last_challenge ) @@ -212,6 +215,7 @@ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, Non return self._last_challenge = self._parse_challenge(request, response, auth_header) + self._last_challenge_origin = origin self._nonce_count = 1 request.headers["Authorization"] = self._build_auth_header( diff --git a/tests/client/test_auth.py b/tests/client/test_auth.py index 72674e6f4b..c2a1a24ad1 100644 --- a/tests/client/test_auth.py +++ b/tests/client/test_auth.py @@ -553,6 +553,25 @@ async def test_digest_auth_reuses_challenge() -> None: assert len(response_2.history) == 0 +@pytest.mark.anyio +async def test_digest_auth_does_not_reuse_challenge_for_other_origin() -> None: + auth = httpx.DigestAuth(username="user", password="password123") + app = DigestApp() + + async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: + response_1 = await client.get("https://example.org/", auth=auth) + response_2 = await client.get("https://example.com/", auth=auth) + + assert response_1.status_code == 200 + assert len(response_1.history) == 1 + + # The challenge from 'example.org' must not be replayed to 'example.com', + # which would disclose a digest response derived from the user's password + # to an unrelated origin. + assert response_2.status_code == 200 + assert response_2.json() == {"auth": None} + + @pytest.mark.anyio async def test_digest_auth_resets_nonce_count_after_401() -> None: url = "https://example.org/"