Skip to content
Myr

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

3 files+139 added−31 removed

modified:httpx/_auth.py+16 added-5 removed
156 unmodified lines
157 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 = 1163164 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 )169170 response = yield request171172 if response.status_code != 401 or "www-authenticate" not in response.headers:173 # If the response is not a 401 then we don't
7 unmodified lines
181 # If the response does not include a 'WWW-Authenticate: Digest ...'182 # header, then we don't need to build an authenticated request.183 return184178 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 = 1187188 request.headers["Authorization"] = self._build_auth_header(189 request, self._last_challenge190 )191 yield request192193 def _parse_challenge(194 self, request: Request, response: Response, auth_header: str
40 unmodified lines
235 A2 = b":".join((request.method.encode(), path))236 # TODO: implement auth-int237 HA2 = digest(A2)238228 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 += 1242243 HA1 = digest(A1)244 if challenge.algorithm.lower().endswith("-sess"):245 HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))
73 unmodified lines
modified:tests/client/test_auth.py+83 added-26 removed
6 unmodified lines
7import hashlib8import os9import threading10import typing11from urllib.request import parse_keqv_list1213import pytest1415import httpx
135 unmodified lines
151152@pytest.mark.asyncio153async def test_basic_auth() -> None:154 url = "https://example.org/"154 auth = ("tomchristie", "password123")155 auth = ("user", "password123")156 app = App()157158 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:159 response = await client.get(url, auth=auth)160161 assert response.status_code == 200161 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}162 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}163164165@pytest.mark.asyncio166async 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()173174 async with httpx.AsyncClient(175 transport=httpx.MockTransport(app), auth=auth
1 unmodified line
177 async with client.stream("GET", url) as response:178 await response.aread()179180 assert response.status_code == 200180 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}181 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}182183184@pytest.mark.asyncio185async def test_basic_auth_in_url() -> None:185 url = "https://tomchristie:password123@example.org/"186 url = "https://user:password123@example.org/"187 app = App()188189 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:190 response = await client.get(url)191192 assert response.status_code == 200192 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}193 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}194195196@pytest.mark.asyncio197async def test_basic_auth_on_session() -> None:198 url = "https://example.org/"198 auth = ("tomchristie", "password123")199 auth = ("user", "password123")200 app = App()201202 async with httpx.AsyncClient(203 transport=httpx.MockTransport(app), auth=auth204 ) as client:205 response = await client.get(url)206207 assert response.status_code == 200207 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}208 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}209210211@pytest.mark.asyncio212async def test_custom_auth() -> None:
66 unmodified lines
279280@pytest.mark.asyncio281async def test_auth_disable_per_request() -> None:282 url = "https://example.org/"282 auth = ("tomchristie", "password123")283 auth = ("user", "password123")284 app = App()285286 async with httpx.AsyncClient(287 transport=httpx.MockTransport(app), auth=auth
29 unmodified lines
317318 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:319 assert client.auth is None320320 client.auth = ("tomchristie", "password123") # type: ignore321 client.auth = ("user", "password123") # type: ignore322 assert isinstance(client.auth, BasicAuth)323324 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=="}328329330@pytest.mark.asyncio331async def test_auth_invalid_type() -> None:
15 unmodified lines
347348@pytest.mark.asyncio349async 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()353354 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:355 response = await client.get(url, auth=auth)
4 unmodified lines
360361362def 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)367368 client = httpx.Client(transport=httpx.MockTransport(app))
6 unmodified lines
375376@pytest.mark.asyncio377async 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)382383 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:
6 unmodified lines
390391@pytest.mark.asyncio392async 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)396397 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:398 response = await client.get(url, auth=auth)
20 unmodified lines
419async 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)425426 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:427 response = await client.get(url, auth=auth)
7 unmodified lines
435436 response_fields = [field.strip() for field in fields.split(",")]437 digest_data = dict(field.split("=") for field in response_fields)438438 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 quotes
6 unmodified lines
450451@pytest.mark.asyncio452async 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="")456457 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:458 response = await client.get(url, auth=auth)
10 unmodified lines
469470 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 + 2
4 unmodified lines
482@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))483@pytest.mark.asyncio484async 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)488489 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:490 response = await client.get(url, auth=auth)
4 unmodified lines
495496@pytest.mark.asyncio497async 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")501502 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:503 with pytest.raises(NotImplementedError):
2 unmodified lines
506507@pytest.mark.asyncio508async 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")512513 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:514 with pytest.raises(ProtocolError):
2 unmodified lines
517518@pytest.mark.asyncio519async 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)523524 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:525 response = await client.get(url, auth=auth)
1 unmodified line
527 assert response.status_code == 401528 assert len(response.history) == 1529530531@pytest.mark.asyncio532async def test_digest_auth_reuses_challenge() -> None:533 url = "https://example.org/"534 auth = DigestAuth(username="user", password="password123")535 app = DigestApp()536537 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)540541 assert response_1.status_code == 200542 assert response_2.status_code == 200543544 assert len(response_1.history) == 1545 assert len(response_2.history) == 0546547548@pytest.mark.asyncio549async 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()553554 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) == 1558559 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"]565566 # with this we now force a 401 on a subsequent (but initial) request567 app.send_response_after_attempt = 2568569 # 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) == 1573574 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"]580581 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 failed585586587@pytest.mark.parametrize(588 "auth_header",589 [590 'Digest realm="httpx@example.org", qop="auth"', # missing fields
4 unmodified lines
595async 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)601602 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:603 with pytest.raises(ProtocolError):
10 unmodified lines
614def 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)620621 with httpx.Client(transport=httpx.MockTransport(app)) as client:622 with pytest.raises(ProtocolError):
62 unmodified lines
685686@pytest.mark.asyncio687async 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()691692 async def streaming_body():693 yield b"Example request body" # pragma: no cover
70 unmodified lines
modified:tests/test_auth.py+40 added
1 unmodified line
2Unit tests for auth classes.34Integration tests also exist in tests/client/test_auth.py5"""6from urllib.request import parse_keqv_list78import pytest910import httpx11
50 unmodified lines
62 # 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)666768def test_digest_auth_with_401_nonce_counting():69 auth = httpx.DigestAuth(username="user", password="pass")70 request = httpx.Request("GET", "https://www.example.com")7172 # 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.headers7677 # 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")8687 # 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")9293 # ... 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)99100 # 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)