reuse the digest auth state to avoid unnecessary requests (#2463)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* reuse the digest auth challenge to avoid sending twice as many requests * fix for digest testcase * ran testing/linting scripts * codereview changes, removed tomchristie username from all authentication tests
authored by rettier · committed by GitHub · parent 69e13cb · Browse files · 3 files·+139 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Philipp Reitter <p.reitter@accessio.at>
- Co-authored-by: Tom Christie <tom@tomchristie.com>
Diff stats
3 files+139 added−31 removed
- tests:+123 added−26 removed
- other:+16 added−5 removed
Provenance
- Commit
8327e13- Tree
f4bebb5- Author
rettier <rettier@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
69e13cb
3 files changed+139 added−31 removed
modified:httpx/_auth.py+16 added-5 removed
156 unmodified lines157 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]158 ) -> None:159 self._username = to_bytes(username)160 self._password = to_bytes(password)161+ self._last_challenge: typing.Optional[_DigestAuthChallenge] = None162+ self._nonce_count = 1163 164 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:165+ if self._last_challenge:166+ request.headers["Authorization"] = self._build_auth_header(167+ request, self._last_challenge168+ )169+170 response = yield request171 172 if response.status_code != 401 or "www-authenticate" not in response.headers:173 # If the response is not a 401 then we don't7 unmodified lines181 # If the response does not include a 'WWW-Authenticate: Digest ...'182 # header, then we don't need to build an authenticated request.183 return184 178- challenge = self._parse_challenge(request, response, auth_header)179- request.headers["Authorization"] = self._build_auth_header(request, challenge)185+ self._last_challenge = self._parse_challenge(request, response, auth_header)186+ self._nonce_count = 1187+188+ request.headers["Authorization"] = self._build_auth_header(189+ request, self._last_challenge190+ )191 yield request192 193 def _parse_challenge(194 self, request: Request, response: Response, auth_header: str40 unmodified lines235 A2 = b":".join((request.method.encode(), path))236 # TODO: implement auth-int237 HA2 = digest(A2)238 228- nonce_count = 1 # TODO: implement nonce counting229- nc_value = b"%08x" % nonce_count230- cnonce = self._get_client_nonce(nonce_count, challenge.nonce)239+ nc_value = b"%08x" % self._nonce_count240+ cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)241+ self._nonce_count += 1242 243 HA1 = digest(A1)244 if challenge.algorithm.lower().endswith("-sess"):245 HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))73 unmodified linesmodified:tests/client/test_auth.py+83 added-26 removed
6 unmodified lines7 import hashlib8 import os9 import threading10 import typing11+from urllib.request import parse_keqv_list12 13 import pytest14 15 import httpx135 unmodified lines151 152 @pytest.mark.asyncio153 async def test_basic_auth() -> None:154 url = "https://example.org/"154- auth = ("tomchristie", "password123")155+ auth = ("user", "password123")156 app = App()157 158 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:159 response = await client.get(url, auth=auth)160 161 assert response.status_code == 200161- assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}162+ assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}163 164 165 @pytest.mark.asyncio166 async def test_basic_auth_with_stream() -> None:167 """168 See: https://github.com/encode/httpx/pull/1312169 """170 url = "https://example.org/"170- auth = ("tomchristie", "password123")171+ auth = ("user", "password123")172 app = App()173 174 async with httpx.AsyncClient(175 transport=httpx.MockTransport(app), auth=auth1 unmodified line177 async with client.stream("GET", url) as response:178 await response.aread()179 180 assert response.status_code == 200180- assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}181+ assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}182 183 184 @pytest.mark.asyncio185 async def test_basic_auth_in_url() -> None:185- url = "https://tomchristie:password123@example.org/"186+ url = "https://user:password123@example.org/"187 app = App()188 189 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:190 response = await client.get(url)191 192 assert response.status_code == 200192- assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}193+ assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}194 195 196 @pytest.mark.asyncio197 async def test_basic_auth_on_session() -> None:198 url = "https://example.org/"198- auth = ("tomchristie", "password123")199+ auth = ("user", "password123")200 app = App()201 202 async with httpx.AsyncClient(203 transport=httpx.MockTransport(app), auth=auth204 ) as client:205 response = await client.get(url)206 207 assert response.status_code == 200207- assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}208+ assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}209 210 211 @pytest.mark.asyncio212 async def test_custom_auth() -> None:66 unmodified lines279 280 @pytest.mark.asyncio281 async def test_auth_disable_per_request() -> None:282 url = "https://example.org/"282- auth = ("tomchristie", "password123")283+ auth = ("user", "password123")284 app = App()285 286 async with httpx.AsyncClient(287 transport=httpx.MockTransport(app), auth=auth29 unmodified lines317 318 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:319 assert client.auth is None320 320- client.auth = ("tomchristie", "password123") # type: ignore321+ client.auth = ("user", "password123") # type: ignore322 assert isinstance(client.auth, BasicAuth)323 324 url = "https://example.org/"325 response = await client.get(url)326 assert response.status_code == 200326- assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}327+ assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}328 329 330 @pytest.mark.asyncio331 async def test_auth_invalid_type() -> None:15 unmodified lines347 348 @pytest.mark.asyncio349 async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:350 url = "https://example.org/"350- auth = DigestAuth(username="tomchristie", password="password123")351+ auth = DigestAuth(username="user", password="password123")352 app = App()353 354 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:355 response = await client.get(url, auth=auth)4 unmodified lines360 361 362 def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:363 url = "https://example.org/"363- auth = DigestAuth(username="tomchristie", password="password123")364+ auth = DigestAuth(username="user", password="password123")365 auth_header = "Token ..."366 app = App(auth_header=auth_header, status_code=401)367 368 client = httpx.Client(transport=httpx.MockTransport(app))6 unmodified lines375 376 @pytest.mark.asyncio377 async def test_digest_auth_200_response_including_digest_auth_header() -> None:378 url = "https://example.org/"378- auth = DigestAuth(username="tomchristie", password="password123")379+ auth = DigestAuth(username="user", password="password123")380 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'381 app = App(auth_header=auth_header, status_code=200)382 383 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:6 unmodified lines390 391 @pytest.mark.asyncio392 async def test_digest_auth_401_response_without_digest_auth_header() -> None:393 url = "https://example.org/"393- auth = DigestAuth(username="tomchristie", password="password123")394+ auth = DigestAuth(username="user", password="password123")395 app = App(auth_header="", status_code=401)396 397 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:398 response = await client.get(url, auth=auth)20 unmodified lines419 async def test_digest_auth(420 algorithm: str, expected_hash_length: int, expected_response_length: int421 ) -> None:422 url = "https://example.org/"422- auth = DigestAuth(username="tomchristie", password="password123")423+ auth = DigestAuth(username="user", password="password123")424 app = DigestApp(algorithm=algorithm)425 426 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:427 response = await client.get(url, auth=auth)7 unmodified lines435 436 response_fields = [field.strip() for field in fields.split(",")]437 digest_data = dict(field.split("=") for field in response_fields)438 438- assert digest_data["username"] == '"tomchristie"'439+ assert digest_data["username"] == '"user"'440 assert digest_data["realm"] == '"httpx@example.org"'441 assert "nonce" in digest_data442 assert digest_data["uri"] == '"/"'443 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes6 unmodified lines450 451 @pytest.mark.asyncio452 async def test_digest_auth_no_specified_qop() -> None:453 url = "https://example.org/"453- auth = DigestAuth(username="tomchristie", password="password123")454+ auth = DigestAuth(username="user", password="password123")455 app = DigestApp(qop="")456 457 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:458 response = await client.get(url, auth=auth)10 unmodified lines469 470 assert "qop" not in digest_data471 assert "nc" not in digest_data472 assert "cnonce" not in digest_data472- assert digest_data["username"] == '"tomchristie"'473+ assert digest_data["username"] == '"user"'474 assert digest_data["realm"] == '"httpx@example.org"'475 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes476 assert digest_data["uri"] == '"/"'477 assert len(digest_data["response"]) == 64 + 24 unmodified lines482 @pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))483 @pytest.mark.asyncio484 async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:485 url = "https://example.org/"485- auth = DigestAuth(username="tomchristie", password="password123")486+ auth = DigestAuth(username="user", password="password123")487 app = DigestApp(qop=qop)488 489 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:490 response = await client.get(url, auth=auth)4 unmodified lines495 496 @pytest.mark.asyncio497 async def test_digest_auth_qop_auth_int_not_implemented() -> None:498 url = "https://example.org/"498- auth = DigestAuth(username="tomchristie", password="password123")499+ auth = DigestAuth(username="user", password="password123")500 app = DigestApp(qop="auth-int")501 502 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:503 with pytest.raises(NotImplementedError):2 unmodified lines506 507 @pytest.mark.asyncio508 async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:509 url = "https://example.org/"509- auth = DigestAuth(username="tomchristie", password="password123")510+ auth = DigestAuth(username="user", password="password123")511 app = DigestApp(qop="not-auth")512 513 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:514 with pytest.raises(ProtocolError):2 unmodified lines517 518 @pytest.mark.asyncio519 async def test_digest_auth_incorrect_credentials() -> None:520 url = "https://example.org/"520- auth = DigestAuth(username="tomchristie", password="password123")521+ auth = DigestAuth(username="user", password="password123")522 app = DigestApp(send_response_after_attempt=2)523 524 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:525 response = await client.get(url, auth=auth)1 unmodified line527 assert response.status_code == 401528 assert len(response.history) == 1529 530 531+@pytest.mark.asyncio532+async def test_digest_auth_reuses_challenge() -> None:533+ url = "https://example.org/"534+ auth = DigestAuth(username="user", password="password123")535+ app = DigestApp()536+537+ async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:538+ response_1 = await client.get(url, auth=auth)539+ response_2 = await client.get(url, auth=auth)540+541+ assert response_1.status_code == 200542+ assert response_2.status_code == 200543+544+ assert len(response_1.history) == 1545+ assert len(response_2.history) == 0546+547+548+@pytest.mark.asyncio549+async def test_digest_auth_resets_nonce_count_after_401() -> None:550+ url = "https://example.org/"551+ auth = DigestAuth(username="user", password="password123")552+ app = DigestApp()553+554+ async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:555+ response_1 = await client.get(url, auth=auth)556+ assert response_1.status_code == 200557+ assert len(response_1.history) == 1558+559+ first_nonce = parse_keqv_list(560+ response_1.request.headers["Authorization"].split(", ")561+ )["nonce"]562+ first_nc = parse_keqv_list(563+ response_1.request.headers["Authorization"].split(", ")564+ )["nc"]565+566+ # with this we now force a 401 on a subsequent (but initial) request567+ app.send_response_after_attempt = 2568+569+ # we expect the client again to try to authenticate, i.e. the history length must be 1570+ response_2 = await client.get(url, auth=auth)571+ assert response_2.status_code == 200572+ assert len(response_2.history) == 1573+574+ second_nonce = parse_keqv_list(575+ response_2.request.headers["Authorization"].split(", ")576+ )["nonce"]577+ second_nc = parse_keqv_list(578+ response_2.request.headers["Authorization"].split(", ")579+ )["nc"]580+581+ assert first_nonce != second_nonce # ensures that the auth challenge was reset582+ assert (583+ first_nc == second_nc584+ ) # ensures the nonce count is reset when the authentication failed585+586+587 @pytest.mark.parametrize(588 "auth_header",589 [590 'Digest realm="httpx@example.org", qop="auth"', # missing fields4 unmodified lines595 async def test_async_digest_auth_raises_protocol_error_on_malformed_header(596 auth_header: str,597 ) -> None:598 url = "https://example.org/"542- auth = DigestAuth(username="tomchristie", password="password123")599+ auth = DigestAuth(username="user", password="password123")600 app = App(auth_header=auth_header, status_code=401)601 602 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:603 with pytest.raises(ProtocolError):10 unmodified lines614 def test_sync_digest_auth_raises_protocol_error_on_malformed_header(615 auth_header: str,616 ) -> None:617 url = "https://example.org/"561- auth = DigestAuth(username="tomchristie", password="password123")618+ auth = DigestAuth(username="user", password="password123")619 app = App(auth_header=auth_header, status_code=401)620 621 with httpx.Client(transport=httpx.MockTransport(app)) as client:622 with pytest.raises(ProtocolError):62 unmodified lines685 686 @pytest.mark.asyncio687 async def test_digest_auth_unavailable_streaming_body():688 url = "https://example.org/"632- auth = DigestAuth(username="tomchristie", password="password123")689+ auth = DigestAuth(username="user", password="password123")690 app = DigestApp()691 692 async def streaming_body():693 yield b"Example request body" # pragma: no cover70 unmodified linesmodified:tests/test_auth.py+40 added
1 unmodified line2 Unit tests for auth classes.3 4 Integration tests also exist in tests/client/test_auth.py5 """6+from urllib.request import parse_keqv_list7+8 import pytest9 10 import httpx11 50 unmodified lines62 # No other requests are made.63 response = httpx.Response(content=b"Hello, world!", status_code=200)64 with pytest.raises(StopIteration):65 flow.send(response)66+67+68+def test_digest_auth_with_401_nonce_counting():69+ auth = httpx.DigestAuth(username="user", password="pass")70+ request = httpx.Request("GET", "https://www.example.com")71+72+ # The initial request should not include an auth header.73+ flow = auth.sync_auth_flow(request)74+ request = next(flow)75+ assert "Authorization" not in request.headers76+77+ # If a 401 response is returned, then a digest auth request is made.78+ headers = {79+ "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'80+ }81+ response = httpx.Response(82+ content=b"Auth required", status_code=401, headers=headers83+ )84+ first_request = flow.send(response)85+ assert first_request.headers["Authorization"].startswith("Digest")86+87+ # Each subsequent request contains the digest header by default...88+ request = httpx.Request("GET", "https://www.example.com")89+ flow = auth.sync_auth_flow(request)90+ second_request = next(flow)91+ assert second_request.headers["Authorization"].startswith("Digest")92+93+ # ... and the client nonce count (nc) is increased94+ first_nc = parse_keqv_list(first_request.headers["Authorization"].split(", "))["nc"]95+ second_nc = parse_keqv_list(second_request.headers["Authorization"].split(", "))[96+ "nc"97+ ]98+ assert int(first_nc, 16) + 1 == int(second_nc, 16)99+100+ # No other requests are made.101+ response = httpx.Response(content=b"Hello, world!", status_code=200)102+ with pytest.raises(StopIteration):103+ flow.send(response)