test_auth.py
This file
Path
tests/client/test_auth.py
605 lines · 19.2 KiB · Python
Last changed by
Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
History of this fileTake it
1import hashlib2import os3import typing45import httpcore6import pytest78from httpx import (9 URL,10 AsyncClient,11 Auth,12 Client,13 DigestAuth,14 Headers,15 ProtocolError,16 Request,17 RequestBodyUnavailable,18 Response,19)20from httpx._content_streams import ContentStream, JSONStream212223def get_header_value(headers, key, default=None):24 lookup = key.encode("ascii").lower()25 for header_key, header_value in headers:26 if header_key.lower() == lookup:27 return header_value.decode("ascii")28 return default293031class MockTransport:32 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:33 self.auth_header = auth_header34 self.status_code = status_code3536 def _request(37 self,38 method: bytes,39 url: typing.Tuple[bytes, bytes, int, bytes],40 headers: typing.List[typing.Tuple[bytes, bytes]],41 stream: ContentStream,42 timeout: typing.Dict[str, typing.Optional[float]] = None,43 ) -> typing.Tuple[44 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream45 ]:46 authorization = get_header_value(headers, "Authorization")47 response_headers = (48 [(b"www-authenticate", self.auth_header)] if self.auth_header else []49 )50 response_stream = JSONStream({"auth": authorization})51 return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream525354class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):55 async def request(56 self, *args, **kwargs57 ) -> typing.Tuple[58 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream59 ]:60 return self._request(*args, **kwargs)616263class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):64 def request(65 self, *args, **kwargs66 ) -> typing.Tuple[67 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream68 ]:69 return self._request(*args, **kwargs)707172class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):73 def __init__(74 self,75 algorithm: str = "SHA-256",76 send_response_after_attempt: int = 1,77 qop: str = "auth",78 regenerate_nonce: bool = True,79 ) -> None:80 self.algorithm = algorithm81 self.send_response_after_attempt = send_response_after_attempt82 self.qop = qop83 self._regenerate_nonce = regenerate_nonce84 self._response_count = 08586 async def request(87 self,88 method: bytes,89 url: typing.Tuple[bytes, bytes, int, bytes],90 headers: typing.List[typing.Tuple[bytes, bytes]],91 stream: ContentStream,92 timeout: typing.Dict[str, typing.Optional[float]] = None,93 ) -> typing.Tuple[94 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream95 ]:96 if self._response_count < self.send_response_after_attempt:97 return self.challenge_send(method, url, headers, stream)9899 authorization = get_header_value(headers, "Authorization")100 body = JSONStream({"auth": authorization})101 return b"HTTP/1.1", 200, b"", [], body102103 def challenge_send(104 self, method: bytes, url: URL, headers: Headers, stream: ContentStream,105 ) -> typing.Tuple[int, bytes, Headers, ContentStream]:106 self._response_count += 1107 nonce = (108 hashlib.sha256(os.urandom(8)).hexdigest()109 if self._regenerate_nonce110 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"111 )112 challenge_data = {113 "nonce": nonce,114 "qop": self.qop,115 "opaque": (116 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"117 ),118 "algorithm": self.algorithm,119 "stale": "FALSE",120 }121 challenge_str = ", ".join(122 '{}="{}"'.format(key, value)123 for key, value in challenge_data.items()124 if value125 )126127 headers = [128 (129 b"www-authenticate",130 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),131 )132 ]133 return b"HTTP/1.1", 401, b"", headers, ContentStream()134135136class RepeatAuth(Auth):137 """138 A mock authentication scheme that requires clients to send139 the request a fixed number of times, and then send a last request containing140 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers141 of intermediate responses.142 """143144 requires_request_body = True145146 def __init__(self, repeat: int):147 self.repeat = repeat148149 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:150 nonces = []151152 for index in range(self.repeat):153 request.headers["Authorization"] = f"Repeat {index}"154 response = yield request155 nonces.append(response.headers["www-authenticate"])156157 key = ".".join(nonces)158 request.headers["Authorization"] = f"Repeat {key}"159 yield request160161162class ResponseBodyAuth(Auth):163 """164 A mock authentication scheme that requires clients to send an 'Authorization'165 header, then send back the contents of the response in the 'Authorization'166 header.167 """168169 requires_response_body = True170171 def __init__(self, token):172 self.token = token173174 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:175 request.headers["Authorization"] = self.token176 response = yield request177 data = response.text178 request.headers["Authorization"] = data179 yield request180181182@pytest.mark.asyncio183async def test_basic_auth() -> None:184 url = "https://example.org/"185 auth = ("tomchristie", "password123")186187 client = AsyncClient(transport=AsyncMockTransport())188 response = await client.get(url, auth=auth)189190 assert response.status_code == 200191 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}192193194@pytest.mark.asyncio195async def test_basic_auth_in_url() -> None:196 url = "https://tomchristie:password123@example.org/"197198 client = AsyncClient(transport=AsyncMockTransport())199 response = await client.get(url)200201 assert response.status_code == 200202 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}203204205@pytest.mark.asyncio206async def test_basic_auth_on_session() -> None:207 url = "https://example.org/"208 auth = ("tomchristie", "password123")209210 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)211 response = await client.get(url)212213 assert response.status_code == 200214 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}215216217@pytest.mark.asyncio218async def test_custom_auth() -> None:219 url = "https://example.org/"220221 def auth(request: Request) -> Request:222 request.headers["Authorization"] = "Token 123"223 return request224225 client = AsyncClient(transport=AsyncMockTransport())226 response = await client.get(url, auth=auth)227228 assert response.status_code == 200229 assert response.json() == {"auth": "Token 123"}230231232@pytest.mark.asyncio233async def test_netrc_auth() -> None:234 os.environ["NETRC"] = "tests/.netrc"235 url = "http://netrcexample.org"236237 client = AsyncClient(transport=AsyncMockTransport())238 response = await client.get(url)239240 assert response.status_code == 200241 assert response.json() == {242 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"243 }244245246@pytest.mark.asyncio247async def test_auth_header_has_priority_over_netrc() -> None:248 os.environ["NETRC"] = "tests/.netrc"249 url = "http://netrcexample.org"250251 client = AsyncClient(transport=AsyncMockTransport())252 response = await client.get(url, headers={"Authorization": "Override"})253254 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}256257258@pytest.mark.asyncio259async def test_trust_env_auth() -> None:260 os.environ["NETRC"] = "tests/.netrc"261 url = "http://netrcexample.org"262263 client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)264 response = await client.get(url)265266 assert response.status_code == 200267 assert response.json() == {"auth": None}268269 client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)270 response = await client.get(url)271272 assert response.status_code == 200273 assert response.json() == {274 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"275 }276277278def test_auth_hidden_url() -> None:279 url = "http://example-username:example-password@example.org/"280 expected = "URL('http://example-username:[secure]@example.org/')"281 assert url == URL(url)282 assert expected == repr(URL(url))283284285@pytest.mark.asyncio286async def test_auth_hidden_header() -> None:287 url = "https://example.org/"288 auth = ("example-username", "example-password")289290 client = AsyncClient(transport=AsyncMockTransport())291 response = await client.get(url, auth=auth)292293 assert "'authorization': '[secure]'" in str(response.request.headers)294295296@pytest.mark.asyncio297async def test_auth_invalid_type() -> None:298 url = "https://example.org/"299 client = AsyncClient(300 transport=AsyncMockTransport(), auth="not a tuple, not a callable",301 )302 with pytest.raises(TypeError):303 await client.get(url)304305306@pytest.mark.asyncio307async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:308 url = "https://example.org/"309 auth = DigestAuth(username="tomchristie", password="password123")310311 client = AsyncClient(transport=AsyncMockTransport())312 response = await client.get(url, auth=auth)313314 assert response.status_code == 200315 assert response.json() == {"auth": None}316 assert len(response.history) == 0317318319@pytest.mark.asyncio320async def test_digest_auth_200_response_including_digest_auth_header() -> None:321 url = "https://example.org/"322 auth = DigestAuth(username="tomchristie", password="password123")323 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'324325 client = AsyncClient(326 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)327 )328 response = await client.get(url, auth=auth)329330 assert response.status_code == 200331 assert response.json() == {"auth": None}332 assert len(response.history) == 0333334335@pytest.mark.asyncio336async def test_digest_auth_401_response_without_digest_auth_header() -> None:337 url = "https://example.org/"338 auth = DigestAuth(username="tomchristie", password="password123")339340 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))341 response = await client.get(url, auth=auth)342343 assert response.status_code == 401344 assert response.json() == {"auth": None}345 assert len(response.history) == 0346347348@pytest.mark.parametrize(349 "algorithm,expected_hash_length,expected_response_length",350 [351 ("MD5", 64, 32),352 ("MD5-SESS", 64, 32),353 ("SHA", 64, 40),354 ("SHA-SESS", 64, 40),355 ("SHA-256", 64, 64),356 ("SHA-256-SESS", 64, 64),357 ("SHA-512", 64, 128),358 ("SHA-512-SESS", 64, 128),359 ],360)361@pytest.mark.asyncio362async def test_digest_auth(363 algorithm: str, expected_hash_length: int, expected_response_length: int364) -> None:365 url = "https://example.org/"366 auth = DigestAuth(username="tomchristie", password="password123")367368 client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))369 response = await client.get(url, auth=auth)370371 assert response.status_code == 200372 assert len(response.history) == 1373374 authorization = typing.cast(dict, response.json())["auth"]375 scheme, _, fields = authorization.partition(" ")376 assert scheme == "Digest"377378 response_fields = [field.strip() for field in fields.split(",")]379 digest_data = dict(field.split("=") for field in response_fields)380381 assert digest_data["username"] == '"tomchristie"'382 assert digest_data["realm"] == '"httpx@example.org"'383 assert "nonce" in digest_data384 assert digest_data["uri"] == '"/"'385 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes386 assert len(digest_data["opaque"]) == expected_hash_length + 2387 assert digest_data["algorithm"] == algorithm388 assert digest_data["qop"] == "auth"389 assert digest_data["nc"] == "00000001"390 assert len(digest_data["cnonce"]) == 16 + 2391392393@pytest.mark.asyncio394async def test_digest_auth_no_specified_qop() -> None:395 url = "https://example.org/"396 auth = DigestAuth(username="tomchristie", password="password123")397398 client = AsyncClient(transport=MockDigestAuthTransport(qop=""))399 response = await client.get(url, auth=auth)400401 assert response.status_code == 200402 assert len(response.history) == 1403404 authorization = typing.cast(dict, response.json())["auth"]405 scheme, _, fields = authorization.partition(" ")406 assert scheme == "Digest"407408 response_fields = [field.strip() for field in fields.split(",")]409 digest_data = dict(field.split("=") for field in response_fields)410411 assert "qop" not in digest_data412 assert "nc" not in digest_data413 assert "cnonce" not in digest_data414 assert digest_data["username"] == '"tomchristie"'415 assert digest_data["realm"] == '"httpx@example.org"'416 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes417 assert digest_data["uri"] == '"/"'418 assert len(digest_data["response"]) == 64 + 2419 assert len(digest_data["opaque"]) == 64 + 2420 assert digest_data["algorithm"] == "SHA-256"421422423@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))424@pytest.mark.asyncio425async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:426 url = "https://example.org/"427 auth = DigestAuth(username="tomchristie", password="password123")428429 client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))430 response = await client.get(url, auth=auth)431432 assert response.status_code == 200433 assert len(response.history) == 1434435436@pytest.mark.asyncio437async def test_digest_auth_qop_auth_int_not_implemented() -> None:438 url = "https://example.org/"439 auth = DigestAuth(username="tomchristie", password="password123")440 client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))441442 with pytest.raises(NotImplementedError):443 await client.get(url, auth=auth)444445446@pytest.mark.asyncio447async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:448 url = "https://example.org/"449 auth = DigestAuth(username="tomchristie", password="password123")450 client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))451452 with pytest.raises(ProtocolError):453 await client.get(url, auth=auth)454455456@pytest.mark.asyncio457async def test_digest_auth_incorrect_credentials() -> None:458 url = "https://example.org/"459 auth = DigestAuth(username="tomchristie", password="password123")460461 client = AsyncClient(462 transport=MockDigestAuthTransport(send_response_after_attempt=2)463 )464 response = await client.get(url, auth=auth)465466 assert response.status_code == 401467 assert len(response.history) == 1468469470@pytest.mark.parametrize(471 "auth_header",472 [473 b'Digest realm="httpx@example.org", qop="auth"', # missing fields474 b'realm="httpx@example.org", qop="auth"', # not starting with Digest475 b'DigestZ realm="httpx@example.org", qop="auth"'476 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',477 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list478 ],479)480@pytest.mark.asyncio481async def test_async_digest_auth_raises_protocol_error_on_malformed_header(482 auth_header: bytes,483) -> None:484 url = "https://example.org/"485 auth = DigestAuth(username="tomchristie", password="password123")486 client = AsyncClient(487 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)488 )489490 with pytest.raises(ProtocolError):491 await client.get(url, auth=auth)492493494@pytest.mark.parametrize(495 "auth_header",496 [497 b'Digest realm="httpx@example.org", qop="auth"', # missing fields498 b'realm="httpx@example.org", qop="auth"', # not starting with Digest499 b'DigestZ realm="httpx@example.org", qop="auth"'500 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',501 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list502 ],503)504def test_sync_digest_auth_raises_protocol_error_on_malformed_header(505 auth_header: bytes,506) -> None:507 url = "https://example.org/"508 auth = DigestAuth(username="tomchristie", password="password123")509 client = Client(510 transport=SyncMockTransport(auth_header=auth_header, status_code=401)511 )512513 with pytest.raises(ProtocolError):514 client.get(url, auth=auth)515516517@pytest.mark.asyncio518async def test_async_auth_history() -> None:519 """520 Test that intermediate requests sent as part of an authentication flow521 are recorded in the response history.522 """523 url = "https://example.org/"524 auth = RepeatAuth(repeat=2)525 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))526527 response = await client.get(url, auth=auth)528 assert response.status_code == 200529 assert response.json() == {"auth": "Repeat abc.abc"}530531 assert len(response.history) == 2532 resp1, resp2 = response.history533 assert resp1.json() == {"auth": "Repeat 0"}534 assert resp2.json() == {"auth": "Repeat 1"}535536 assert len(resp2.history) == 1537 assert resp2.history == [resp1]538539 assert len(resp1.history) == 0540541542def test_sync_auth_history() -> None:543 """544 Test that intermediate requests sent as part of an authentication flow545 are recorded in the response history.546 """547 url = "https://example.org/"548 auth = RepeatAuth(repeat=2)549 client = Client(transport=SyncMockTransport(auth_header=b"abc"))550551 response = client.get(url, auth=auth)552 assert response.status_code == 200553 assert response.json() == {"auth": "Repeat abc.abc"}554555 assert len(response.history) == 2556 resp1, resp2 = response.history557 assert resp1.json() == {"auth": "Repeat 0"}558 assert resp2.json() == {"auth": "Repeat 1"}559560 assert len(resp2.history) == 1561 assert resp2.history == [resp1]562563 assert len(resp1.history) == 0564565566@pytest.mark.asyncio567async def test_digest_auth_unavailable_streaming_body():568 url = "https://example.org/"569 auth = DigestAuth(username="tomchristie", password="password123")570 client = AsyncClient(transport=AsyncMockTransport())571572 async def streaming_body():573 yield b"Example request body" # pragma: nocover574575 with pytest.raises(RequestBodyUnavailable):576 await client.post(url, data=streaming_body(), auth=auth)577578579@pytest.mark.asyncio580async def test_async_auth_reads_response_body() -> None:581 """582 Test that we can read the response body in an auth flow if `requires_response_body`583 is set.584 """585 url = "https://example.org/"586 auth = ResponseBodyAuth("xyz")587 client = AsyncClient(transport=AsyncMockTransport())588589 response = await client.get(url, auth=auth)590 assert response.status_code == 200591 assert response.json() == {"auth": '{"auth": "xyz"}'}592593594def test_sync_auth_reads_response_body() -> None:595 """596 Test that we can read the response body in an auth flow if `requires_response_body`597 is set.598 """599 url = "https://example.org/"600 auth = ResponseBodyAuth("xyz")601 client = Client(transport=SyncMockTransport())602603 response = client.get(url, auth=auth)604 assert response.status_code == 200605 assert response.json() == {"auth": '{"auth": "xyz"}'}