test_auth.py
This file
Path
tests/client/test_auth.py
383 lines · 12.4 KiB · Python
Last changed by
Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
History of this fileTake it
1import hashlib2import json3import os4import typing56import pytest78from httpx import URL, AsyncClient, DigestAuth, ProtocolError, Request, Response9from httpx.config import CertTypes, TimeoutTypes, VerifyTypes10from httpx.dispatch.base import Dispatcher111213class MockDispatch(Dispatcher):14 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:15 self.auth_header = auth_header16 self.status_code = status_code1718 async def send(19 self,20 request: Request,21 verify: VerifyTypes = None,22 cert: CertTypes = None,23 timeout: TimeoutTypes = None,24 ) -> Response:25 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []26 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()27 return Response(28 self.status_code, headers=headers, content=body, request=request29 )303132class MockDigestAuthDispatch(Dispatcher):33 def __init__(34 self,35 algorithm: str = "SHA-256",36 send_response_after_attempt: int = 1,37 qop: str = "auth",38 regenerate_nonce: bool = True,39 ) -> None:40 self.algorithm = algorithm41 self.send_response_after_attempt = send_response_after_attempt42 self.qop = qop43 self._regenerate_nonce = regenerate_nonce44 self._response_count = 04546 async def send(47 self,48 request: Request,49 verify: VerifyTypes = None,50 cert: CertTypes = None,51 timeout: TimeoutTypes = None,52 ) -> Response:53 if self._response_count < self.send_response_after_attempt:54 return self.challenge_send(request)5556 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()57 return Response(200, content=body, request=request)5859 def challenge_send(self, request: Request) -> Response:60 self._response_count += 161 nonce = (62 hashlib.sha256(os.urandom(8)).hexdigest()63 if self._regenerate_nonce64 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"65 )66 challenge_data = {67 "nonce": nonce,68 "qop": self.qop,69 "opaque": (70 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"71 ),72 "algorithm": self.algorithm,73 "stale": "FALSE",74 }75 challenge_str = ", ".join(76 '{}="{}"'.format(key, value)77 for key, value in challenge_data.items()78 if value79 )8081 headers = [82 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)83 ]84 return Response(401, headers=headers, content=b"", request=request)858687@pytest.mark.asyncio88async def test_basic_auth() -> None:89 url = "https://example.org/"90 auth = ("tomchristie", "password123")9192 client = AsyncClient(dispatch=MockDispatch())93 response = await client.get(url, auth=auth)9495 assert response.status_code == 20096 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}979899@pytest.mark.asyncio100async def test_basic_auth_in_url() -> None:101 url = "https://tomchristie:password123@example.org/"102103 client = AsyncClient(dispatch=MockDispatch())104 response = await client.get(url)105106 assert response.status_code == 200107 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}108109110@pytest.mark.asyncio111async def test_basic_auth_on_session() -> None:112 url = "https://example.org/"113 auth = ("tomchristie", "password123")114115 client = AsyncClient(dispatch=MockDispatch(), auth=auth)116 response = await client.get(url)117118 assert response.status_code == 200119 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}120121122@pytest.mark.asyncio123async def test_custom_auth() -> None:124 url = "https://example.org/"125126 def auth(request: Request) -> Request:127 request.headers["Authorization"] = "Token 123"128 return request129130 client = AsyncClient(dispatch=MockDispatch())131 response = await client.get(url, auth=auth)132133 assert response.status_code == 200134 assert response.json() == {"auth": "Token 123"}135136137@pytest.mark.asyncio138async def test_netrc_auth() -> None:139 os.environ["NETRC"] = "tests/.netrc"140 url = "http://netrcexample.org"141142 client = AsyncClient(dispatch=MockDispatch())143 response = await client.get(url)144145 assert response.status_code == 200146 assert response.json() == {147 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"148 }149150151@pytest.mark.asyncio152async def test_auth_header_has_priority_over_netrc() -> None:153 os.environ["NETRC"] = "tests/.netrc"154 url = "http://netrcexample.org"155156 client = AsyncClient(dispatch=MockDispatch())157 response = await client.get(url, headers={"Authorization": "Override"})158159 assert response.status_code == 200160 assert response.json() == {"auth": "Override"}161162163@pytest.mark.asyncio164async def test_trust_env_auth() -> None:165 os.environ["NETRC"] = "tests/.netrc"166 url = "http://netrcexample.org"167168 client = AsyncClient(dispatch=MockDispatch(), trust_env=False)169 response = await client.get(url)170171 assert response.status_code == 200172 assert response.json() == {"auth": None}173174 client = AsyncClient(dispatch=MockDispatch(), trust_env=True)175 response = await client.get(url)176177 assert response.status_code == 200178 assert response.json() == {179 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"180 }181182183def test_auth_hidden_url() -> None:184 url = "http://example-username:example-password@example.org/"185 expected = "URL('http://example-username:[secure]@example.org/')"186 assert url == URL(url)187 assert expected == repr(URL(url))188189190@pytest.mark.asyncio191async def test_auth_hidden_header() -> None:192 url = "https://example.org/"193 auth = ("example-username", "example-password")194195 client = AsyncClient(dispatch=MockDispatch())196 response = await client.get(url, auth=auth)197198 assert "'authorization': '[secure]'" in str(response.request.headers)199200201@pytest.mark.asyncio202async def test_auth_invalid_type() -> None:203 url = "https://example.org/"204 client = AsyncClient(205 dispatch=MockDispatch(), auth="not a tuple, not a callable", # type: ignore206 )207 with pytest.raises(TypeError):208 await client.get(url)209210211@pytest.mark.asyncio212async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:213 url = "https://example.org/"214 auth = DigestAuth(username="tomchristie", password="password123")215216 client = AsyncClient(dispatch=MockDispatch())217 response = await client.get(url, auth=auth)218219 assert response.status_code == 200220 assert response.json() == {"auth": None}221222223@pytest.mark.asyncio224async def test_digest_auth_200_response_including_digest_auth_header() -> None:225 url = "https://example.org/"226 auth = DigestAuth(username="tomchristie", password="password123")227 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'228229 client = AsyncClient(230 dispatch=MockDispatch(auth_header=auth_header, status_code=200)231 )232 response = await client.get(url, auth=auth)233234 assert response.status_code == 200235 assert response.json() == {"auth": None}236237238@pytest.mark.asyncio239async def test_digest_auth_401_response_without_digest_auth_header() -> None:240 url = "https://example.org/"241 auth = DigestAuth(username="tomchristie", password="password123")242243 client = AsyncClient(dispatch=MockDispatch(auth_header="", status_code=401))244 response = await client.get(url, auth=auth)245246 assert response.status_code == 401247 assert response.json() == {"auth": None}248249250@pytest.mark.parametrize(251 "algorithm,expected_hash_length,expected_response_length",252 [253 ("MD5", 64, 32),254 ("MD5-SESS", 64, 32),255 ("SHA", 64, 40),256 ("SHA-SESS", 64, 40),257 ("SHA-256", 64, 64),258 ("SHA-256-SESS", 64, 64),259 ("SHA-512", 64, 128),260 ("SHA-512-SESS", 64, 128),261 ],262)263@pytest.mark.asyncio264async def test_digest_auth(265 algorithm: str, expected_hash_length: int, expected_response_length: int266) -> None:267 url = "https://example.org/"268 auth = DigestAuth(username="tomchristie", password="password123")269270 client = AsyncClient(dispatch=MockDigestAuthDispatch(algorithm=algorithm))271 response = await client.get(url, auth=auth)272273 assert response.status_code == 200274 authorization = typing.cast(dict, response.json())["auth"]275 scheme, _, fields = authorization.partition(" ")276 assert scheme == "Digest"277278 response_fields = [field.strip() for field in fields.split(",")]279 digest_data = dict(field.split("=") for field in response_fields)280281 assert digest_data["username"] == '"tomchristie"'282 assert digest_data["realm"] == '"httpx@example.org"'283 assert "nonce" in digest_data284 assert digest_data["uri"] == '"/"'285 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes286 assert len(digest_data["opaque"]) == expected_hash_length + 2287 assert digest_data["algorithm"] == algorithm288 assert digest_data["qop"] == "auth"289 assert digest_data["nc"] == "00000001"290 assert len(digest_data["cnonce"]) == 16 + 2291292293@pytest.mark.asyncio294async def test_digest_auth_no_specified_qop() -> None:295 url = "https://example.org/"296 auth = DigestAuth(username="tomchristie", password="password123")297298 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=""))299 response = await client.get(url, auth=auth)300301 assert response.status_code == 200302 authorization = typing.cast(dict, response.json())["auth"]303 scheme, _, fields = authorization.partition(" ")304 assert scheme == "Digest"305306 response_fields = [field.strip() for field in fields.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) -> None:324 url = "https://example.org/"325 auth = DigestAuth(username="tomchristie", password="password123")326327 client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop))328 await client.get(url, auth=auth)329330331@pytest.mark.asyncio332async def test_digest_auth_qop_auth_int_not_implemented() -> None:333 url = "https://example.org/"334 auth = DigestAuth(username="tomchristie", password="password123")335 client = AsyncClient(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() -> None:343 url = "https://example.org/"344 auth = DigestAuth(username="tomchristie", password="password123")345 client = AsyncClient(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() -> None:353 url = "https://example.org/"354 auth = DigestAuth(username="tomchristie", password="password123")355356 client = AsyncClient(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(374 auth_header: str,375) -> None:376 url = "https://example.org/"377 auth = DigestAuth(username="tomchristie", password="password123")378 client = AsyncClient(379 dispatch=MockDispatch(auth_header=auth_header, status_code=401)380 )381382 with pytest.raises(ProtocolError):383 await client.get(url, auth=auth)