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
Provenance
- Commit
bc6163c- Tree
fb186eb- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
910aa90
2 files changed+71 added−4 removed
modified:httpx/client.py+9 added-3 removed
449 unmodified lines450 if request.url in (response.url for response in history):451 raise RedirectLoop()452 453 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)457 458 if not response.is_redirect:111 unmodified lines570 571 return request.stream572 573 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 lines588 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)596 597 async def send_single_request(598 self, request: Request, timeout: Timeout,599 ) -> Response:373 unmodified linesmodified:tests/client/test_auth.py+62 added-1 removed
4 unmodified lines5 6 import pytest7 8 from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response9+from httpx.auth import Auth, AuthFlow10 from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11 from httpx.dispatch.base import Dispatcher12 13 204 unmodified lines218 response = await client.get(url, auth=auth)219 220 assert response.status_code == 200221 assert response.json() == {"auth": None}222+ assert len(response.history) == 0223 224 225 @pytest.mark.asyncio226 async def test_digest_auth_200_response_including_digest_auth_header() -> None:7 unmodified lines234 response = await client.get(url, auth=auth)235 236 assert response.status_code == 200237 assert response.json() == {"auth": None}238+ assert len(response.history) == 0239 240 241 @pytest.mark.asyncio242 async def test_digest_auth_401_response_without_digest_auth_header() -> None:4 unmodified lines247 response = await client.get(url, auth=auth)248 249 assert response.status_code == 401250 assert response.json() == {"auth": None}251+ assert len(response.history) == 0252 253 254 @pytest.mark.parametrize(255 "algorithm,expected_hash_length,expected_response_length",18 unmodified lines274 client = AsyncClient(dispatch=MockDigestAuthDispatch(algorithm=algorithm))275 response = await client.get(url, auth=auth)276 277 assert response.status_code == 200278+ assert len(response.history) == 1279+280 authorization = typing.cast(dict, response.json())["auth"]281 scheme, _, fields = authorization.partition(" ")282 assert scheme == "Digest"283 20 unmodified lines304 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=""))305 response = await client.get(url, auth=auth)306 307 assert response.status_code == 200308+ assert len(response.history) == 1309+310 authorization = typing.cast(dict, response.json())["auth"]311 scheme, _, fields = authorization.partition(" ")312 assert scheme == "Digest"313 18 unmodified lines332 url = "https://example.org/"333 auth = DigestAuth(username="tomchristie", password="password123")334 335 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop))328- await client.get(url, auth=auth)336+ response = await client.get(url, auth=auth)337 338+ assert response.status_code == 200339+ assert len(response.history) == 1340 341+342 @pytest.mark.asyncio343 async def test_digest_auth_qop_auth_int_not_implemented() -> None:344 url = "https://example.org/"345 auth = DigestAuth(username="tomchristie", password="password123")21 unmodified lines367 client = AsyncClient(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))368 response = await client.get(url, auth=auth)369 370 assert response.status_code == 401371+ assert len(response.history) == 1372 373 374 @pytest.mark.parametrize(375 "auth_header",16 unmodified lines392 )393 394 with pytest.raises(ProtocolError):395 await client.get(url, auth=auth)396+397+398+@pytest.mark.asyncio399+async 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+ """404+405+ 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+ """412+413+ def __init__(self, repeat: int):414+ self.repeat = repeat415+416+ def __call__(self, request: Request) -> AuthFlow:417+ nonces = []418+419+ for index in range(self.repeat):420+ request.headers["Authorization"] = f"Repeat {index}"421+ response = yield request422+ nonces.append(response.headers["www-authenticate"])423+424+ key = ".".join(nonces)425+ request.headers["Authorization"] = f"Repeat {key}"426+ yield request427+428+ url = "https://example.org/"429+ auth = RepeatAuth(repeat=2)430+ client = AsyncClient(dispatch=MockDispatch(auth_header="abc"))431+432+ response = await client.get(url, auth=auth)433+ assert response.status_code == 200434+ assert response.json() == {"auth": "Repeat abc.abc"}435+436+ assert len(response.history) == 2437+ resp1, resp2 = response.history438+ assert resp1.json() == {"auth": "Repeat 0"}439+ assert resp2.json() == {"auth": "Repeat 1"}440+441+ assert len(resp2.history) == 1442+ assert resp2.history == [resp1]443+444+ assert len(resp1.history) == 0