test_auth.py
This file
Path
tests/client/test_auth.py
379 lines · 11.9 KiB · Python
Last changed by
Ensure Authorization header has priority over .netrcTom Christiebefore adoption43331cf
History of this fileTake it
1import hashlib2import json3import os45import pytest67from httpx import (8 URL,9 CertTypes,10 Client,11 DigestAuth,12 Dispatcher,13 ProtocolError,14 Request,15 Response,16 TimeoutTypes,17 VerifyTypes,18)192021class MockDispatch(Dispatcher):22 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:23 self.auth_header = auth_header24 self.status_code = status_code2526 async def send(27 self,28 request: Request,29 verify: VerifyTypes = None,30 cert: CertTypes = None,31 timeout: TimeoutTypes = None,32 ) -> Response:33 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []34 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()35 return Response(36 self.status_code, headers=headers, content=body, request=request37 )383940class MockDigestAuthDispatch(Dispatcher):41 def __init__(42 self,43 algorithm: str = "SHA-256",44 send_response_after_attempt: int = 1,45 qop: str = "auth",46 regenerate_nonce: bool = True,47 ) -> None:48 self.algorithm = algorithm49 self.send_response_after_attempt = send_response_after_attempt50 self.qop = qop51 self._regenerate_nonce = regenerate_nonce52 self._response_count = 05354 async def send(55 self,56 request: Request,57 verify: VerifyTypes = None,58 cert: CertTypes = None,59 timeout: TimeoutTypes = None,60 ) -> Response:61 if self._response_count < self.send_response_after_attempt:62 return self.challenge_send(request)6364 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()65 return Response(200, content=body, request=request)6667 def challenge_send(self, request: Request) -> Response:68 self._response_count += 169 nonce = (70 hashlib.sha256(os.urandom(8)).hexdigest()71 if self._regenerate_nonce72 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"73 )74 challenge_data = {75 "nonce": nonce,76 "qop": self.qop,77 "opaque": (78 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"79 ),80 "algorithm": self.algorithm,81 "stale": "FALSE",82 }83 challenge_str = ", ".join(84 '{}="{}"'.format(key, value)85 for key, value in challenge_data.items()86 if value87 )8889 headers = [90 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)91 ]92 return Response(401, headers=headers, content=b"", request=request)939495@pytest.mark.asyncio96async def test_basic_auth():97 url = "https://example.org/"98 auth = ("tomchristie", "password123")99100 client = Client(dispatch=MockDispatch())101 response = await client.get(url, auth=auth)102103 assert response.status_code == 200104 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}105106107@pytest.mark.asyncio108async def test_basic_auth_in_url():109 url = "https://tomchristie:password123@example.org/"110111 client = Client(dispatch=MockDispatch())112 response = await client.get(url)113114 assert response.status_code == 200115 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}116117118@pytest.mark.asyncio119async def test_basic_auth_on_session():120 url = "https://example.org/"121 auth = ("tomchristie", "password123")122123 client = Client(dispatch=MockDispatch(), auth=auth)124 response = await client.get(url)125126 assert response.status_code == 200127 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}128129130@pytest.mark.asyncio131async def test_custom_auth():132 url = "https://example.org/"133134 def auth(request):135 request.headers["Authorization"] = "Token 123"136 return request137138 client = Client(dispatch=MockDispatch())139 response = await client.get(url, auth=auth)140141 assert response.status_code == 200142 assert response.json() == {"auth": "Token 123"}143144145@pytest.mark.asyncio146async def test_netrc_auth():147 os.environ["NETRC"] = "tests/.netrc"148 url = "http://netrcexample.org"149150 client = Client(dispatch=MockDispatch())151 response = await client.get(url)152153 assert response.status_code == 200154 assert response.json() == {155 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"156 }157158159@pytest.mark.asyncio160async def test_auth_header_has_priority_over_netrc():161 os.environ["NETRC"] = "tests/.netrc"162 url = "http://netrcexample.org"163164 client = Client(dispatch=MockDispatch())165 response = await client.get(url, headers={"Authorization": "Override"})166167 assert response.status_code == 200168 assert response.json() == {"auth": "Override"}169170171@pytest.mark.asyncio172async def test_trust_env_auth():173 os.environ["NETRC"] = "tests/.netrc"174 url = "http://netrcexample.org"175176 client = Client(dispatch=MockDispatch())177 response = await client.get(url, trust_env=False)178179 assert response.status_code == 200180 assert response.json() == {"auth": None}181182 client = Client(dispatch=MockDispatch(), trust_env=False)183 response = await client.get(url, trust_env=True)184185 assert response.status_code == 200186 assert response.json() == {187 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"188 }189190191def test_auth_hidden_url():192 url = "http://example-username:example-password@example.org/"193 expected = "URL('http://example-username:[secure]@example.org/')"194 assert url == URL(url)195 assert expected == repr(URL(url))196197198@pytest.mark.asyncio199async def test_auth_hidden_header():200 url = "https://example.org/"201 auth = ("example-username", "example-password")202203 client = Client(dispatch=MockDispatch())204 response = await client.get(url, auth=auth)205206 assert "'authorization': '[secure]'" in str(response.request.headers)207208209@pytest.mark.asyncio210async def test_auth_invalid_type():211 url = "https://example.org/"212 client = Client(dispatch=MockDispatch(), auth="not a tuple, not a callable")213 with pytest.raises(TypeError):214 await client.get(url)215216217@pytest.mark.asyncio218async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():219 url = "https://example.org/"220 auth = DigestAuth(username="tomchristie", password="password123")221222 client = Client(dispatch=MockDispatch())223 response = await client.get(url, auth=auth)224225 assert response.status_code == 200226 assert response.json() == {"auth": None}227228229@pytest.mark.asyncio230async def test_digest_auth_200_response_including_digest_auth_header():231 url = "https://example.org/"232 auth = DigestAuth(username="tomchristie", password="password123")233 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'234235 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))236 response = await client.get(url, auth=auth)237238 assert response.status_code == 200239 assert response.json() == {"auth": None}240241242@pytest.mark.asyncio243async def test_digest_auth_401_response_without_digest_auth_header():244 url = "https://example.org/"245 auth = DigestAuth(username="tomchristie", password="password123")246247 client = Client(dispatch=MockDispatch(auth_header="", status_code=401))248 response = await client.get(url, auth=auth)249250 assert response.status_code == 401251 assert response.json() == {"auth": None}252253254@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(algorithm, expected_hash_length, expected_response_length):269 url = "https://example.org/"270 auth = DigestAuth(username="tomchristie", password="password123")271272 client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))273 response = await client.get(url, auth=auth)274275 assert response.status_code == 200276 auth = response.json()["auth"]277 assert auth.startswith("Digest ")278279 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]280 digest_data = dict(field.split("=") for field in response_fields)281282 assert digest_data["username"] == '"tomchristie"'283 assert digest_data["realm"] == '"httpx@example.org"'284 assert "nonce" in digest_data285 assert digest_data["uri"] == '"/"'286 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes287 assert len(digest_data["opaque"]) == expected_hash_length + 2288 assert digest_data["algorithm"] == algorithm289 assert digest_data["qop"] == "auth"290 assert digest_data["nc"] == "00000001"291 assert len(digest_data["cnonce"]) == 16 + 2292293294@pytest.mark.asyncio295async def test_digest_auth_no_specified_qop():296 url = "https://example.org/"297 auth = DigestAuth(username="tomchristie", password="password123")298299 client = Client(dispatch=MockDigestAuthDispatch(qop=None))300 response = await client.get(url, auth=auth)301302 assert response.status_code == 200303 auth = response.json()["auth"]304 assert auth.startswith("Digest ")305306 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]307 digest_data = dict(field.split("=") for field in response_fields)308309 assert "qop" not in digest_data310 assert "nc" not in digest_data311 assert "cnonce" not in digest_data312 assert digest_data["username"] == '"tomchristie"'313 assert digest_data["realm"] == '"httpx@example.org"'314 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes315 assert digest_data["uri"] == '"/"'316 assert len(digest_data["response"]) == 64 + 2317 assert len(digest_data["opaque"]) == 64 + 2318 assert digest_data["algorithm"] == "SHA-256"319320321@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))322@pytest.mark.asyncio323async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):324 url = "https://example.org/"325 auth = DigestAuth(username="tomchristie", password="password123")326327 client = Client(dispatch=MockDigestAuthDispatch(qop=qop))328 await client.get(url, auth=auth)329330331@pytest.mark.asyncio332async def test_digest_auth_qop_auth_int_not_implemented():333 url = "https://example.org/"334 auth = DigestAuth(username="tomchristie", password="password123")335 client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))336337 with pytest.raises(NotImplementedError):338 await client.get(url, auth=auth)339340341@pytest.mark.asyncio342async def test_digest_auth_qop_must_be_auth_or_auth_int():343 url = "https://example.org/"344 auth = DigestAuth(username="tomchristie", password="password123")345 client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))346347 with pytest.raises(ProtocolError):348 await client.get(url, auth=auth)349350351@pytest.mark.asyncio352async def test_digest_auth_incorrect_credentials():353 url = "https://example.org/"354 auth = DigestAuth(username="tomchristie", password="password123")355356 client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))357 response = await client.get(url, auth=auth)358359 assert response.status_code == 401360361362@pytest.mark.parametrize(363 "auth_header",364 [365 'Digest realm="httpx@example.org", qop="auth"', # missing fields366 'realm="httpx@example.org", qop="auth"', # not starting with Digest367 'DigestZ realm="httpx@example.org", qop="auth"'368 'qop="auth,auth-int",nonce="abc",opaque="xyz"',369 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list370 ],371)372@pytest.mark.asyncio373async def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):374 url = "https://example.org/"375 auth = DigestAuth(username="tomchristie", password="password123")376 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))377378 with pytest.raises(ProtocolError):379 await client.get(url, auth=auth)