test_auth.py
This file
Path
tests/client/test_auth.py
444 lines · 14.3 KiB · Python
Last changed by
Record history of requests made during authentication (#718)Florimond Mancabefore adoptionbc6163c
History of this fileTake it
1import hashlib2import json3import os4import typing56import pytest78from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response9from httpx.auth import Auth, AuthFlow10from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11from httpx.dispatch.base import Dispatcher121314class MockDispatch(Dispatcher):15 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:16 self.auth_header = auth_header17 self.status_code = status_code1819 async def send(20 self,21 request: Request,22 verify: VerifyTypes = None,23 cert: CertTypes = None,24 timeout: TimeoutTypes = None,25 ) -> Response:26 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []27 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()28 return Response(29 self.status_code, headers=headers, content=body, request=request30 )313233class MockDigestAuthDispatch(Dispatcher):34 def __init__(35 self,36 algorithm: str = "SHA-256",37 send_response_after_attempt: int = 1,38 qop: str = "auth",39 regenerate_nonce: bool = True,40 ) -> None:41 self.algorithm = algorithm42 self.send_response_after_attempt = send_response_after_attempt43 self.qop = qop44 self._regenerate_nonce = regenerate_nonce45 self._response_count = 04647 async def send(48 self,49 request: Request,50 verify: VerifyTypes = None,51 cert: CertTypes = None,52 timeout: TimeoutTypes = None,53 ) -> Response:54 if self._response_count < self.send_response_after_attempt:55 return self.challenge_send(request)5657 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()58 return Response(200, content=body, request=request)5960 def challenge_send(self, request: Request) -> Response:61 self._response_count += 162 nonce = (63 hashlib.sha256(os.urandom(8)).hexdigest()64 if self._regenerate_nonce65 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"66 )67 challenge_data = {68 "nonce": nonce,69 "qop": self.qop,70 "opaque": (71 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"72 ),73 "algorithm": self.algorithm,74 "stale": "FALSE",75 }76 challenge_str = ", ".join(77 '{}="{}"'.format(key, value)78 for key, value in challenge_data.items()79 if value80 )8182 headers = [83 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)84 ]85 return Response(401, headers=headers, content=b"", request=request)868788@pytest.mark.asyncio89async def test_basic_auth() -> None:90 url = "https://example.org/"91 auth = ("tomchristie", "password123")9293 client = AsyncClient(dispatch=MockDispatch())94 response = await client.get(url, auth=auth)9596 assert response.status_code == 20097 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}9899100@pytest.mark.asyncio101async def test_basic_auth_in_url() -> None:102 url = "https://tomchristie:password123@example.org/"103104 client = AsyncClient(dispatch=MockDispatch())105 response = await client.get(url)106107 assert response.status_code == 200108 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}109110111@pytest.mark.asyncio112async def test_basic_auth_on_session() -> None:113 url = "https://example.org/"114 auth = ("tomchristie", "password123")115116 client = AsyncClient(dispatch=MockDispatch(), auth=auth)117 response = await client.get(url)118119 assert response.status_code == 200120 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}121122123@pytest.mark.asyncio124async def test_custom_auth() -> None:125 url = "https://example.org/"126127 def auth(request: Request) -> Request:128 request.headers["Authorization"] = "Token 123"129 return request130131 client = AsyncClient(dispatch=MockDispatch())132 response = await client.get(url, auth=auth)133134 assert response.status_code == 200135 assert response.json() == {"auth": "Token 123"}136137138@pytest.mark.asyncio139async def test_netrc_auth() -> None:140 os.environ["NETRC"] = "tests/.netrc"141 url = "http://netrcexample.org"142143 client = AsyncClient(dispatch=MockDispatch())144 response = await client.get(url)145146 assert response.status_code == 200147 assert response.json() == {148 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"149 }150151152@pytest.mark.asyncio153async def test_auth_header_has_priority_over_netrc() -> None:154 os.environ["NETRC"] = "tests/.netrc"155 url = "http://netrcexample.org"156157 client = AsyncClient(dispatch=MockDispatch())158 response = await client.get(url, headers={"Authorization": "Override"})159160 assert response.status_code == 200161 assert response.json() == {"auth": "Override"}162163164@pytest.mark.asyncio165async def test_trust_env_auth() -> None:166 os.environ["NETRC"] = "tests/.netrc"167 url = "http://netrcexample.org"168169 client = AsyncClient(dispatch=MockDispatch(), trust_env=False)170 response = await client.get(url)171172 assert response.status_code == 200173 assert response.json() == {"auth": None}174175 client = AsyncClient(dispatch=MockDispatch(), trust_env=True)176 response = await client.get(url)177178 assert response.status_code == 200179 assert response.json() == {180 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"181 }182183184def test_auth_hidden_url() -> None:185 url = "http://example-username:example-password@example.org/"186 expected = "URL('http://example-username:[secure]@example.org/')"187 assert url == URL(url)188 assert expected == repr(URL(url))189190191@pytest.mark.asyncio192async def test_auth_hidden_header() -> None:193 url = "https://example.org/"194 auth = ("example-username", "example-password")195196 client = AsyncClient(dispatch=MockDispatch())197 response = await client.get(url, auth=auth)198199 assert "'authorization': '[secure]'" in str(response.request.headers)200201202@pytest.mark.asyncio203async def test_auth_invalid_type() -> None:204 url = "https://example.org/"205 client = AsyncClient(206 dispatch=MockDispatch(), auth="not a tuple, not a callable", # type: ignore207 )208 with pytest.raises(TypeError):209 await client.get(url)210211212@pytest.mark.asyncio213async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:214 url = "https://example.org/"215 auth = DigestAuth(username="tomchristie", password="password123")216217 client = AsyncClient(dispatch=MockDispatch())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:227 url = "https://example.org/"228 auth = DigestAuth(username="tomchristie", password="password123")229 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'230231 client = AsyncClient(232 dispatch=MockDispatch(auth_header=auth_header, status_code=200)233 )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:243 url = "https://example.org/"244 auth = DigestAuth(username="tomchristie", password="password123")245246 client = AsyncClient(dispatch=MockDispatch(auth_header="", status_code=401))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",256 [257 ("MD5", 64, 32),258 ("MD5-SESS", 64, 32),259 ("SHA", 64, 40),260 ("SHA-SESS", 64, 40),261 ("SHA-256", 64, 64),262 ("SHA-256-SESS", 64, 64),263 ("SHA-512", 64, 128),264 ("SHA-512-SESS", 64, 128),265 ],266)267@pytest.mark.asyncio268async def test_digest_auth(269 algorithm: str, expected_hash_length: int, expected_response_length: int270) -> None:271 url = "https://example.org/"272 auth = DigestAuth(username="tomchristie", password="password123")273274 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"283284 response_fields = [field.strip() for field in fields.split(",")]285 digest_data = dict(field.split("=") for field in response_fields)286287 assert digest_data["username"] == '"tomchristie"'288 assert digest_data["realm"] == '"httpx@example.org"'289 assert "nonce" in digest_data290 assert digest_data["uri"] == '"/"'291 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes292 assert len(digest_data["opaque"]) == expected_hash_length + 2293 assert digest_data["algorithm"] == algorithm294 assert digest_data["qop"] == "auth"295 assert digest_data["nc"] == "00000001"296 assert len(digest_data["cnonce"]) == 16 + 2297298299@pytest.mark.asyncio300async def test_digest_auth_no_specified_qop() -> None:301 url = "https://example.org/"302 auth = DigestAuth(username="tomchristie", password="password123")303304 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"313314 response_fields = [field.strip() for field in fields.split(",")]315 digest_data = dict(field.split("=") for field in response_fields)316317 assert "qop" not in digest_data318 assert "nc" not in digest_data319 assert "cnonce" not in digest_data320 assert digest_data["username"] == '"tomchristie"'321 assert digest_data["realm"] == '"httpx@example.org"'322 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes323 assert digest_data["uri"] == '"/"'324 assert len(digest_data["response"]) == 64 + 2325 assert len(digest_data["opaque"]) == 64 + 2326 assert digest_data["algorithm"] == "SHA-256"327328329@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))330@pytest.mark.asyncio331async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:332 url = "https://example.org/"333 auth = DigestAuth(username="tomchristie", password="password123")334335 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop))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")346 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop="auth-int"))347348 with pytest.raises(NotImplementedError):349 await client.get(url, auth=auth)350351352@pytest.mark.asyncio353async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:354 url = "https://example.org/"355 auth = DigestAuth(username="tomchristie", password="password123")356 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop="not-auth"))357358 with pytest.raises(ProtocolError):359 await client.get(url, auth=auth)360361362@pytest.mark.asyncio363async def test_digest_auth_incorrect_credentials() -> None:364 url = "https://example.org/"365 auth = DigestAuth(username="tomchristie", password="password123")366367 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",376 [377 'Digest realm="httpx@example.org", qop="auth"', # missing fields378 'realm="httpx@example.org", qop="auth"', # not starting with Digest379 'DigestZ realm="httpx@example.org", qop="auth"'380 'qop="auth,auth-int",nonce="abc",opaque="xyz"',381 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list382 ],383)384@pytest.mark.asyncio385async def test_digest_auth_raises_protocol_error_on_malformed_header(386 auth_header: str,387) -> None:388 url = "https://example.org/"389 auth = DigestAuth(username="tomchristie", password="password123")390 client = AsyncClient(391 dispatch=MockDispatch(auth_header=auth_header, status_code=401)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