Skip to content
Myr

Record history of requests made during authentication (#718)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Record history of requests made during authentication * Add asserts on digest auth history

authored by Florimond Manca · committed by GitHub · parent 910aa90 · Browse files · 2 files+71 added−4 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: Gaurav Dhameeja <gdhameeja@gmail.com>

Diff stats

2 files+71 added−4 removed

  • tests:+62 added−1 removed
  • other:+9 added−3 removed

2 files+71 added−4 removed

modified:httpx/client.py+9 added-3 removed
449 unmodified lines
450 if request.url in (response.url for response in history):451 raise RedirectLoop()452453 response = await self.send_handling_auth(454 request, auth=auth, timeout=timeout,454 request, history, auth=auth, timeout=timeout,455 )456 response.history = list(history)457458 if not response.is_redirect:
111 unmodified lines
570571 return request.stream572573 async def send_handling_auth(574 self, request: Request, auth: Auth, timeout: Timeout,574 self,575 request: Request,576 history: typing.List[Response],577 auth: Auth,578 timeout: Timeout,579 ) -> Response:580 auth_flow = auth(request)581 request = next(auth_flow)582 while True:
5 unmodified lines
588 except BaseException as exc:589 await response.aclose()590 raise exc from None591 else:592 response.history = list(history)593 await response.aread()594 request = next_request589 await response.aclose()595 history.append(response)596597 async def send_single_request(598 self, request: Request, timeout: Timeout,599 ) -> Response:
373 unmodified lines
modified:tests/client/test_auth.py+62 added-1 removed
4 unmodified lines
56import pytest78from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response9from httpx.auth import Auth, AuthFlow10from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11from httpx.dispatch.base import Dispatcher1213
204 unmodified lines
218 response = await client.get(url, auth=auth)219220 assert response.status_code == 200221 assert response.json() == {"auth": None}222 assert len(response.history) == 0223224225@pytest.mark.asyncio226async def test_digest_auth_200_response_including_digest_auth_header() -> None:
7 unmodified lines
234 response = await client.get(url, auth=auth)235236 assert response.status_code == 200237 assert response.json() == {"auth": None}238 assert len(response.history) == 0239240241@pytest.mark.asyncio242async def test_digest_auth_401_response_without_digest_auth_header() -> None:
4 unmodified lines
247 response = await client.get(url, auth=auth)248249 assert response.status_code == 401250 assert response.json() == {"auth": None}251 assert len(response.history) == 0252253254@pytest.mark.parametrize(255 "algorithm,expected_hash_length,expected_response_length",
18 unmodified lines
274 client = AsyncClient(dispatch=MockDigestAuthDispatch(algorithm=algorithm))275 response = await client.get(url, auth=auth)276277 assert response.status_code == 200278 assert len(response.history) == 1279280 authorization = typing.cast(dict, response.json())["auth"]281 scheme, _, fields = authorization.partition(" ")282 assert scheme == "Digest"283
20 unmodified lines
304 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=""))305 response = await client.get(url, auth=auth)306307 assert response.status_code == 200308 assert len(response.history) == 1309310 authorization = typing.cast(dict, response.json())["auth"]311 scheme, _, fields = authorization.partition(" ")312 assert scheme == "Digest"313
18 unmodified lines
332 url = "https://example.org/"333 auth = DigestAuth(username="tomchristie", password="password123")334335 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop))328 await client.get(url, auth=auth)336 response = await client.get(url, auth=auth)337338 assert response.status_code == 200339 assert len(response.history) == 1340341342@pytest.mark.asyncio343async def test_digest_auth_qop_auth_int_not_implemented() -> None:344 url = "https://example.org/"345 auth = DigestAuth(username="tomchristie", password="password123")
21 unmodified lines
367 client = AsyncClient(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))368 response = await client.get(url, auth=auth)369370 assert response.status_code == 401371 assert len(response.history) == 1372373374@pytest.mark.parametrize(375 "auth_header",
16 unmodified lines
392 )393394 with pytest.raises(ProtocolError):395 await client.get(url, auth=auth)396397398@pytest.mark.asyncio399async def test_auth_history() -> None:400 """401 Test that intermediate requests sent as part of an authentication flow402 are recorded in the response history.403 """404405 class RepeatAuth(Auth):406 """407 A mock authentication scheme that requires clients to send408 the request a fixed number of times, and then send a last request containing409 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers410 of intermediate responses.411 """412413 def __init__(self, repeat: int):414 self.repeat = repeat415416 def __call__(self, request: Request) -> AuthFlow:417 nonces = []418419 for index in range(self.repeat):420 request.headers["Authorization"] = f"Repeat {index}"421 response = yield request422 nonces.append(response.headers["www-authenticate"])423424 key = ".".join(nonces)425 request.headers["Authorization"] = f"Repeat {key}"426 yield request427428 url = "https://example.org/"429 auth = RepeatAuth(repeat=2)430 client = AsyncClient(dispatch=MockDispatch(auth_header="abc"))431432 response = await client.get(url, auth=auth)433 assert response.status_code == 200434 assert response.json() == {"auth": "Repeat abc.abc"}435436 assert len(response.history) == 2437 resp1, resp2 = response.history438 assert resp1.json() == {"auth": "Repeat 0"}439 assert resp2.json() == {"auth": "Repeat 1"}440441 assert len(resp2.history) == 1442 assert resp2.history == [resp1]443444 assert len(resp1.history) == 0