test_auth.py
This file
Path
tests/client/test_auth.py
370 lines · 11.9 KiB · Python
Last changed by
No I/O auth (#644)Tom Christiebefore adoption6c69e09
History of this fileTake it
1import hashlib2import json3import os45import pytest67from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response8from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9from httpx.dispatch.base import Dispatcher101112class MockDispatch(Dispatcher):13 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:14 self.auth_header = auth_header15 self.status_code = status_code1617 async def send(18 self,19 request: Request,20 verify: VerifyTypes = None,21 cert: CertTypes = None,22 timeout: TimeoutTypes = None,23 ) -> Response:24 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []25 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()26 return Response(27 self.status_code, headers=headers, content=body, request=request28 )293031class MockDigestAuthDispatch(Dispatcher):32 def __init__(33 self,34 algorithm: str = "SHA-256",35 send_response_after_attempt: int = 1,36 qop: str = "auth",37 regenerate_nonce: bool = True,38 ) -> None:39 self.algorithm = algorithm40 self.send_response_after_attempt = send_response_after_attempt41 self.qop = qop42 self._regenerate_nonce = regenerate_nonce43 self._response_count = 04445 async def send(46 self,47 request: Request,48 verify: VerifyTypes = None,49 cert: CertTypes = None,50 timeout: TimeoutTypes = None,51 ) -> Response:52 if self._response_count < self.send_response_after_attempt:53 return self.challenge_send(request)5455 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()56 return Response(200, content=body, request=request)5758 def challenge_send(self, request: Request) -> Response:59 self._response_count += 160 nonce = (61 hashlib.sha256(os.urandom(8)).hexdigest()62 if self._regenerate_nonce63 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"64 )65 challenge_data = {66 "nonce": nonce,67 "qop": self.qop,68 "opaque": (69 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"70 ),71 "algorithm": self.algorithm,72 "stale": "FALSE",73 }74 challenge_str = ", ".join(75 '{}="{}"'.format(key, value)76 for key, value in challenge_data.items()77 if value78 )7980 headers = [81 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)82 ]83 return Response(401, headers=headers, content=b"", request=request)848586@pytest.mark.asyncio87async def test_basic_auth():88 url = "https://example.org/"89 auth = ("tomchristie", "password123")9091 client = Client(dispatch=MockDispatch())92 response = await client.get(url, auth=auth)9394 assert response.status_code == 20095 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}969798@pytest.mark.asyncio99async def test_basic_auth_in_url():100 url = "https://tomchristie:password123@example.org/"101102 client = Client(dispatch=MockDispatch())103 response = await client.get(url)104105 assert response.status_code == 200106 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}107108109@pytest.mark.asyncio110async def test_basic_auth_on_session():111 url = "https://example.org/"112 auth = ("tomchristie", "password123")113114 client = Client(dispatch=MockDispatch(), auth=auth)115 response = await client.get(url)116117 assert response.status_code == 200118 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}119120121@pytest.mark.asyncio122async def test_custom_auth():123 url = "https://example.org/"124125 def auth(request):126 request.headers["Authorization"] = "Token 123"127 return request128129 client = Client(dispatch=MockDispatch())130 response = await client.get(url, auth=auth)131132 assert response.status_code == 200133 assert response.json() == {"auth": "Token 123"}134135136@pytest.mark.asyncio137async def test_netrc_auth():138 os.environ["NETRC"] = "tests/.netrc"139 url = "http://netrcexample.org"140141 client = Client(dispatch=MockDispatch())142 response = await client.get(url)143144 assert response.status_code == 200145 assert response.json() == {146 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"147 }148149150@pytest.mark.asyncio151async def test_auth_header_has_priority_over_netrc():152 os.environ["NETRC"] = "tests/.netrc"153 url = "http://netrcexample.org"154155 client = Client(dispatch=MockDispatch())156 response = await client.get(url, headers={"Authorization": "Override"})157158 assert response.status_code == 200159 assert response.json() == {"auth": "Override"}160161162@pytest.mark.asyncio163async def test_trust_env_auth():164 os.environ["NETRC"] = "tests/.netrc"165 url = "http://netrcexample.org"166167 client = Client(dispatch=MockDispatch(), trust_env=False)168 response = await client.get(url)169170 assert response.status_code == 200171 assert response.json() == {"auth": None}172173 client = Client(dispatch=MockDispatch(), trust_env=True)174 response = await client.get(url)175176 assert response.status_code == 200177 assert response.json() == {178 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"179 }180181182def test_auth_hidden_url():183 url = "http://example-username:example-password@example.org/"184 expected = "URL('http://example-username:[secure]@example.org/')"185 assert url == URL(url)186 assert expected == repr(URL(url))187188189@pytest.mark.asyncio190async def test_auth_hidden_header():191 url = "https://example.org/"192 auth = ("example-username", "example-password")193194 client = Client(dispatch=MockDispatch())195 response = await client.get(url, auth=auth)196197 assert "'authorization': '[secure]'" in str(response.request.headers)198199200@pytest.mark.asyncio201async def test_auth_invalid_type():202 url = "https://example.org/"203 client = Client(dispatch=MockDispatch(), auth="not a tuple, not a callable")204 with pytest.raises(TypeError):205 await client.get(url)206207208@pytest.mark.asyncio209async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():210 url = "https://example.org/"211 auth = DigestAuth(username="tomchristie", password="password123")212213 client = Client(dispatch=MockDispatch())214 response = await client.get(url, auth=auth)215216 assert response.status_code == 200217 assert response.json() == {"auth": None}218219220@pytest.mark.asyncio221async def test_digest_auth_200_response_including_digest_auth_header():222 url = "https://example.org/"223 auth = DigestAuth(username="tomchristie", password="password123")224 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'225226 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))227 response = await client.get(url, auth=auth)228229 assert response.status_code == 200230 assert response.json() == {"auth": None}231232233@pytest.mark.asyncio234async def test_digest_auth_401_response_without_digest_auth_header():235 url = "https://example.org/"236 auth = DigestAuth(username="tomchristie", password="password123")237238 client = Client(dispatch=MockDispatch(auth_header="", status_code=401))239 response = await client.get(url, auth=auth)240241 assert response.status_code == 401242 assert response.json() == {"auth": None}243244245@pytest.mark.parametrize(246 "algorithm,expected_hash_length,expected_response_length",247 [248 ("MD5", 64, 32),249 ("MD5-SESS", 64, 32),250 ("SHA", 64, 40),251 ("SHA-SESS", 64, 40),252 ("SHA-256", 64, 64),253 ("SHA-256-SESS", 64, 64),254 ("SHA-512", 64, 128),255 ("SHA-512-SESS", 64, 128),256 ],257)258@pytest.mark.asyncio259async def test_digest_auth(algorithm, expected_hash_length, expected_response_length):260 url = "https://example.org/"261 auth = DigestAuth(username="tomchristie", password="password123")262263 client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))264 response = await client.get(url, auth=auth)265266 assert response.status_code == 200267 auth = response.json()["auth"]268 assert auth.startswith("Digest ")269270 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]271 digest_data = dict(field.split("=") for field in response_fields)272273 assert digest_data["username"] == '"tomchristie"'274 assert digest_data["realm"] == '"httpx@example.org"'275 assert "nonce" in digest_data276 assert digest_data["uri"] == '"/"'277 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes278 assert len(digest_data["opaque"]) == expected_hash_length + 2279 assert digest_data["algorithm"] == algorithm280 assert digest_data["qop"] == "auth"281 assert digest_data["nc"] == "00000001"282 assert len(digest_data["cnonce"]) == 16 + 2283284285@pytest.mark.asyncio286async def test_digest_auth_no_specified_qop():287 url = "https://example.org/"288 auth = DigestAuth(username="tomchristie", password="password123")289290 client = Client(dispatch=MockDigestAuthDispatch(qop=None))291 response = await client.get(url, auth=auth)292293 assert response.status_code == 200294 auth = response.json()["auth"]295 assert auth.startswith("Digest ")296297 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]298 digest_data = dict(field.split("=") for field in response_fields)299300 assert "qop" not in digest_data301 assert "nc" not in digest_data302 assert "cnonce" not in digest_data303 assert digest_data["username"] == '"tomchristie"'304 assert digest_data["realm"] == '"httpx@example.org"'305 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes306 assert digest_data["uri"] == '"/"'307 assert len(digest_data["response"]) == 64 + 2308 assert len(digest_data["opaque"]) == 64 + 2309 assert digest_data["algorithm"] == "SHA-256"310311312@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))313@pytest.mark.asyncio314async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):315 url = "https://example.org/"316 auth = DigestAuth(username="tomchristie", password="password123")317318 client = Client(dispatch=MockDigestAuthDispatch(qop=qop))319 await client.get(url, auth=auth)320321322@pytest.mark.asyncio323async def test_digest_auth_qop_auth_int_not_implemented():324 url = "https://example.org/"325 auth = DigestAuth(username="tomchristie", password="password123")326 client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))327328 with pytest.raises(NotImplementedError):329 await client.get(url, auth=auth)330331332@pytest.mark.asyncio333async def test_digest_auth_qop_must_be_auth_or_auth_int():334 url = "https://example.org/"335 auth = DigestAuth(username="tomchristie", password="password123")336 client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))337338 with pytest.raises(ProtocolError):339 await client.get(url, auth=auth)340341342@pytest.mark.asyncio343async def test_digest_auth_incorrect_credentials():344 url = "https://example.org/"345 auth = DigestAuth(username="tomchristie", password="password123")346347 client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))348 response = await client.get(url, auth=auth)349350 assert response.status_code == 401351352353@pytest.mark.parametrize(354 "auth_header",355 [356 'Digest realm="httpx@example.org", qop="auth"', # missing fields357 'realm="httpx@example.org", qop="auth"', # not starting with Digest358 'DigestZ realm="httpx@example.org", qop="auth"'359 'qop="auth,auth-int",nonce="abc",opaque="xyz"',360 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list361 ],362)363@pytest.mark.asyncio364async def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):365 url = "https://example.org/"366 auth = DigestAuth(username="tomchristie", password="password123")367 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))368369 with pytest.raises(ProtocolError):370 await client.get(url, auth=auth)