test_auth.py
This file
Path
tests/client/test_auth.py
729 lines · 23.1 KiB · Python
Last changed by
Add support for sync-specific or async-specific auth flows (#1217)Florimond Mancabefore adoption016e4ee
History of this fileTake it
1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import os9import threading10import typing1112import httpcore13import pytest1415import httpx16from httpx import (17 URL,18 Auth,19 BasicAuth,20 DigestAuth,21 ProtocolError,22 Request,23 RequestBodyUnavailable,24 Response,25)26from httpx._content_streams import ContentStream, JSONStream2728from ..common import FIXTURES_DIR293031def get_header_value(headers, key, default=None):32 lookup = key.encode("ascii").lower()33 for header_key, header_value in headers:34 if header_key.lower() == lookup:35 return header_value.decode("ascii")36 return default373839class MockTransport:40 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:41 self.auth_header = auth_header42 self.status_code = status_code4344 def _request(45 self,46 method: bytes,47 url: typing.Tuple[bytes, bytes, int, bytes],48 headers: typing.List[typing.Tuple[bytes, bytes]],49 stream: ContentStream,50 timeout: typing.Mapping[str, typing.Optional[float]] = None,51 ) -> typing.Tuple[52 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream53 ]:54 authorization = get_header_value(headers, "Authorization")55 response_headers = (56 [(b"www-authenticate", self.auth_header)] if self.auth_header else []57 )58 response_stream = JSONStream({"auth": authorization})59 return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream606162class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):63 async def request(64 self, *args, **kwargs65 ) -> typing.Tuple[66 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream67 ]:68 return self._request(*args, **kwargs)697071class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):72 def request(73 self, *args, **kwargs74 ) -> typing.Tuple[75 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream76 ]:77 return self._request(*args, **kwargs)787980class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):81 def __init__(82 self,83 algorithm: str = "SHA-256",84 send_response_after_attempt: int = 1,85 qop: str = "auth",86 regenerate_nonce: bool = True,87 ) -> None:88 self.algorithm = algorithm89 self.send_response_after_attempt = send_response_after_attempt90 self.qop = qop91 self._regenerate_nonce = regenerate_nonce92 self._response_count = 09394 async def request(95 self,96 method: bytes,97 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],98 headers: typing.List[typing.Tuple[bytes, bytes]] = None,99 stream: httpcore.AsyncByteStream = None,100 timeout: typing.Mapping[str, typing.Optional[float]] = None,101 ) -> typing.Tuple[102 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream103 ]:104 if self._response_count < self.send_response_after_attempt:105 assert headers is not None106 return self.challenge_send(method, headers)107108 authorization = get_header_value(headers, "Authorization")109 body = JSONStream({"auth": authorization})110 return b"HTTP/1.1", 200, b"", [], body111112 def challenge_send(113 self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]]114 ) -> typing.Tuple[115 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream116 ]:117 self._response_count += 1118 nonce = (119 hashlib.sha256(os.urandom(8)).hexdigest()120 if self._regenerate_nonce121 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"122 )123 challenge_data = {124 "nonce": nonce,125 "qop": self.qop,126 "opaque": (127 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"128 ),129 "algorithm": self.algorithm,130 "stale": "FALSE",131 }132 challenge_str = ", ".join(133 '{}="{}"'.format(key, value)134 for key, value in challenge_data.items()135 if value136 )137138 headers = [139 (140 b"www-authenticate",141 b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),142 )143 ]144 return b"HTTP/1.1", 401, b"", headers, ContentStream()145146147class RepeatAuth(Auth):148 """149 A mock authentication scheme that requires clients to send150 the request a fixed number of times, and then send a last request containing151 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers152 of intermediate responses.153 """154155 requires_request_body = True156157 def __init__(self, repeat: int):158 self.repeat = repeat159160 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:161 nonces = []162163 for index in range(self.repeat):164 request.headers["Authorization"] = f"Repeat {index}"165 response = yield request166 nonces.append(response.headers["www-authenticate"])167168 key = ".".join(nonces)169 request.headers["Authorization"] = f"Repeat {key}"170 yield request171172173class ResponseBodyAuth(Auth):174 """175 A mock authentication scheme that requires clients to send an 'Authorization'176 header, then send back the contents of the response in the 'Authorization'177 header.178 """179180 requires_response_body = True181182 def __init__(self, token):183 self.token = token184185 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:186 request.headers["Authorization"] = self.token187 response = yield request188 data = response.text189 request.headers["Authorization"] = data190 yield request191192193class SyncOrAsyncAuth(Auth):194 """195 A mock authentication scheme that uses a different implementation for the196 sync and async cases.197 """198199 def __init__(self) -> None:200 self._lock = threading.Lock()201 self._async_lock = asyncio.Lock()202203 def sync_auth_flow(204 self, request: Request205 ) -> typing.Generator[Request, Response, None]:206 with self._lock:207 request.headers["Authorization"] = "sync-auth"208 yield request209210 async def async_auth_flow(211 self, request: Request212 ) -> typing.AsyncGenerator[Request, Response]:213 async with self._async_lock:214 request.headers["Authorization"] = "async-auth"215 yield request216217218@pytest.mark.asyncio219async def test_basic_auth() -> None:220 url = "https://example.org/"221 auth = ("tomchristie", "password123")222223 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:224 response = await client.get(url, auth=auth)225226 assert response.status_code == 200227 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}228229230@pytest.mark.asyncio231async def test_basic_auth_in_url() -> None:232 url = "https://tomchristie:password123@example.org/"233234 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:235 response = await client.get(url)236237 assert response.status_code == 200238 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}239240241@pytest.mark.asyncio242async def test_basic_auth_on_session() -> None:243 url = "https://example.org/"244 auth = ("tomchristie", "password123")245246 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:247 response = await client.get(url)248249 assert response.status_code == 200250 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}251252253@pytest.mark.asyncio254async def test_custom_auth() -> None:255 url = "https://example.org/"256257 def auth(request: Request) -> Request:258 request.headers["Authorization"] = "Token 123"259 return request260261 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:262 response = await client.get(url, auth=auth)263264 assert response.status_code == 200265 assert response.json() == {"auth": "Token 123"}266267268@pytest.mark.asyncio269async def test_netrc_auth() -> None:270 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")271 url = "http://netrcexample.org"272273 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:274 response = await client.get(url)275276 assert response.status_code == 200277 assert response.json() == {278 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"279 }280281282@pytest.mark.asyncio283async def test_auth_header_has_priority_over_netrc() -> None:284 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")285 url = "http://netrcexample.org"286287 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:288 response = await client.get(url, headers={"Authorization": "Override"})289290 assert response.status_code == 200291 assert response.json() == {"auth": "Override"}292293294@pytest.mark.asyncio295async def test_trust_env_auth() -> None:296 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")297 url = "http://netrcexample.org"298299 async with httpx.AsyncClient(300 transport=AsyncMockTransport(), trust_env=False301 ) as client:302 response = await client.get(url)303304 assert response.status_code == 200305 assert response.json() == {"auth": None}306307 async with httpx.AsyncClient(308 transport=AsyncMockTransport(), trust_env=True309 ) as client:310 response = await client.get(url)311312 assert response.status_code == 200313 assert response.json() == {314 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"315 }316317318@pytest.mark.asyncio319async def test_auth_disable_per_request() -> None:320 url = "https://example.org/"321 auth = ("tomchristie", "password123")322323 async with httpx.AsyncClient(transport=AsyncMockTransport(), auth=auth) as client:324 response = await client.get(url, auth=None)325326 assert response.status_code == 200327 assert response.json() == {"auth": None}328329330def test_auth_hidden_url() -> None:331 url = "http://example-username:example-password@example.org/"332 expected = "URL('http://example-username:[secure]@example.org/')"333 assert url == URL(url)334 assert expected == repr(URL(url))335336337@pytest.mark.asyncio338async def test_auth_hidden_header() -> None:339 url = "https://example.org/"340 auth = ("example-username", "example-password")341342 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:343 response = await client.get(url, auth=auth)344345 assert "'authorization': '[secure]'" in str(response.request.headers)346347348@pytest.mark.asyncio349async def test_auth_property() -> None:350 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:351 assert client.auth is None352353 client.auth = ("tomchristie", "password123") # type: ignore354 assert isinstance(client.auth, BasicAuth)355356 url = "https://example.org/"357 response = await client.get(url)358 assert response.status_code == 200359 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}360361362@pytest.mark.asyncio363async def test_auth_invalid_type() -> None:364 with pytest.raises(TypeError):365 client = httpx.AsyncClient(366 transport=AsyncMockTransport(),367 auth="not a tuple, not a callable", # type: ignore368 )369370 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:371 with pytest.raises(TypeError):372 await client.get(auth="not a tuple, not a callable") # type: ignore373374 with pytest.raises(TypeError):375 client.auth = "not a tuple, not a callable" # type: ignore376377378@pytest.mark.asyncio379async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:380 url = "https://example.org/"381 auth = DigestAuth(username="tomchristie", password="password123")382383 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:384 response = await client.get(url, auth=auth)385386 assert response.status_code == 200387 assert response.json() == {"auth": None}388 assert len(response.history) == 0389390391def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:392 url = "https://example.org/"393 auth = DigestAuth(username="tomchristie", password="password123")394 auth_header = b"Token ..."395396 client = httpx.Client(397 transport=SyncMockTransport(auth_header=auth_header, status_code=401)398 )399 response = client.get(url, auth=auth)400401 assert response.status_code == 401402 assert response.json() == {"auth": None}403 assert len(response.history) == 0404405406@pytest.mark.asyncio407async def test_digest_auth_200_response_including_digest_auth_header() -> None:408 url = "https://example.org/"409 auth = DigestAuth(username="tomchristie", password="password123")410 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'411412 async with httpx.AsyncClient(413 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)414 ) as client:415 response = await client.get(url, auth=auth)416417 assert response.status_code == 200418 assert response.json() == {"auth": None}419 assert len(response.history) == 0420421422@pytest.mark.asyncio423async def test_digest_auth_401_response_without_digest_auth_header() -> None:424 url = "https://example.org/"425 auth = DigestAuth(username="tomchristie", password="password123")426427 async with httpx.AsyncClient(428 transport=AsyncMockTransport(auth_header=b"", status_code=401)429 ) as client:430 response = await client.get(url, auth=auth)431432 assert response.status_code == 401433 assert response.json() == {"auth": None}434 assert len(response.history) == 0435436437@pytest.mark.parametrize(438 "algorithm,expected_hash_length,expected_response_length",439 [440 ("MD5", 64, 32),441 ("MD5-SESS", 64, 32),442 ("SHA", 64, 40),443 ("SHA-SESS", 64, 40),444 ("SHA-256", 64, 64),445 ("SHA-256-SESS", 64, 64),446 ("SHA-512", 64, 128),447 ("SHA-512-SESS", 64, 128),448 ],449)450@pytest.mark.asyncio451async def test_digest_auth(452 algorithm: str, expected_hash_length: int, expected_response_length: int453) -> None:454 url = "https://example.org/"455 auth = DigestAuth(username="tomchristie", password="password123")456457 async with httpx.AsyncClient(458 transport=MockDigestAuthTransport(algorithm=algorithm)459 ) as client:460 response = await client.get(url, auth=auth)461462 assert response.status_code == 200463 assert len(response.history) == 1464465 authorization = typing.cast(dict, response.json())["auth"]466 scheme, _, fields = authorization.partition(" ")467 assert scheme == "Digest"468469 response_fields = [field.strip() for field in fields.split(",")]470 digest_data = dict(field.split("=") for field in response_fields)471472 assert digest_data["username"] == '"tomchristie"'473 assert digest_data["realm"] == '"httpx@example.org"'474 assert "nonce" in digest_data475 assert digest_data["uri"] == '"/"'476 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes477 assert len(digest_data["opaque"]) == expected_hash_length + 2478 assert digest_data["algorithm"] == algorithm479 assert digest_data["qop"] == "auth"480 assert digest_data["nc"] == "00000001"481 assert len(digest_data["cnonce"]) == 16 + 2482483484@pytest.mark.asyncio485async def test_digest_auth_no_specified_qop() -> None:486 url = "https://example.org/"487 auth = DigestAuth(username="tomchristie", password="password123")488489 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop="")) as client:490 response = await client.get(url, auth=auth)491492 assert response.status_code == 200493 assert len(response.history) == 1494495 authorization = typing.cast(dict, response.json())["auth"]496 scheme, _, fields = authorization.partition(" ")497 assert scheme == "Digest"498499 response_fields = [field.strip() for field in fields.split(",")]500 digest_data = dict(field.split("=") for field in response_fields)501502 assert "qop" not in digest_data503 assert "nc" not in digest_data504 assert "cnonce" not in digest_data505 assert digest_data["username"] == '"tomchristie"'506 assert digest_data["realm"] == '"httpx@example.org"'507 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes508 assert digest_data["uri"] == '"/"'509 assert len(digest_data["response"]) == 64 + 2510 assert len(digest_data["opaque"]) == 64 + 2511 assert digest_data["algorithm"] == "SHA-256"512513514@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))515@pytest.mark.asyncio516async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:517 url = "https://example.org/"518 auth = DigestAuth(username="tomchristie", password="password123")519520 async with httpx.AsyncClient(transport=MockDigestAuthTransport(qop=qop)) as client:521 response = await client.get(url, auth=auth)522523 assert response.status_code == 200524 assert len(response.history) == 1525526527@pytest.mark.asyncio528async def test_digest_auth_qop_auth_int_not_implemented() -> None:529 url = "https://example.org/"530 auth = DigestAuth(username="tomchristie", password="password123")531532 async with httpx.AsyncClient(533 transport=MockDigestAuthTransport(qop="auth-int")534 ) as client:535 with pytest.raises(NotImplementedError):536 await client.get(url, auth=auth)537538539@pytest.mark.asyncio540async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:541 url = "https://example.org/"542 auth = DigestAuth(username="tomchristie", password="password123")543544 async with httpx.AsyncClient(545 transport=MockDigestAuthTransport(qop="not-auth")546 ) as client:547 with pytest.raises(ProtocolError):548 await client.get(url, auth=auth)549550551@pytest.mark.asyncio552async def test_digest_auth_incorrect_credentials() -> None:553 url = "https://example.org/"554 auth = DigestAuth(username="tomchristie", password="password123")555556 async with httpx.AsyncClient(557 transport=MockDigestAuthTransport(send_response_after_attempt=2)558 ) as client:559 response = await client.get(url, auth=auth)560561 assert response.status_code == 401562 assert len(response.history) == 1563564565@pytest.mark.parametrize(566 "auth_header",567 [568 b'Digest realm="httpx@example.org", qop="auth"', # missing fields569 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list570 ],571)572@pytest.mark.asyncio573async def test_async_digest_auth_raises_protocol_error_on_malformed_header(574 auth_header: bytes,575) -> None:576 url = "https://example.org/"577 auth = DigestAuth(username="tomchristie", password="password123")578 async with httpx.AsyncClient(579 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)580 ) as client:581 with pytest.raises(ProtocolError):582 await client.get(url, auth=auth)583584585@pytest.mark.parametrize(586 "auth_header",587 [588 b'Digest realm="httpx@example.org", qop="auth"', # missing fields589 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list590 ],591)592def test_sync_digest_auth_raises_protocol_error_on_malformed_header(593 auth_header: bytes,594) -> None:595 url = "https://example.org/"596 auth = DigestAuth(username="tomchristie", password="password123")597598 with httpx.Client(599 transport=SyncMockTransport(auth_header=auth_header, status_code=401)600 ) as client:601 with pytest.raises(ProtocolError):602 client.get(url, auth=auth)603604605@pytest.mark.asyncio606async def test_async_auth_history() -> None:607 """608 Test that intermediate requests sent as part of an authentication flow609 are recorded in the response history.610 """611 url = "https://example.org/"612 auth = RepeatAuth(repeat=2)613614 async with httpx.AsyncClient(615 transport=AsyncMockTransport(auth_header=b"abc")616 ) as client:617 response = await client.get(url, auth=auth)618619 assert response.status_code == 200620 assert response.json() == {"auth": "Repeat abc.abc"}621622 assert len(response.history) == 2623 resp1, resp2 = response.history624 assert resp1.json() == {"auth": "Repeat 0"}625 assert resp2.json() == {"auth": "Repeat 1"}626627 assert len(resp2.history) == 1628 assert resp2.history == [resp1]629630 assert len(resp1.history) == 0631632633def test_sync_auth_history() -> None:634 """635 Test that intermediate requests sent as part of an authentication flow636 are recorded in the response history.637 """638 url = "https://example.org/"639 auth = RepeatAuth(repeat=2)640641 with httpx.Client(transport=SyncMockTransport(auth_header=b"abc")) as client:642 response = client.get(url, auth=auth)643644 assert response.status_code == 200645 assert response.json() == {"auth": "Repeat abc.abc"}646647 assert len(response.history) == 2648 resp1, resp2 = response.history649 assert resp1.json() == {"auth": "Repeat 0"}650 assert resp2.json() == {"auth": "Repeat 1"}651652 assert len(resp2.history) == 1653 assert resp2.history == [resp1]654655 assert len(resp1.history) == 0656657658@pytest.mark.asyncio659async def test_digest_auth_unavailable_streaming_body():660 url = "https://example.org/"661 auth = DigestAuth(username="tomchristie", password="password123")662663 async def streaming_body():664 yield b"Example request body" # pragma: nocover665666 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:667 with pytest.raises(RequestBodyUnavailable):668 await client.post(url, data=streaming_body(), auth=auth)669670671@pytest.mark.asyncio672async def test_async_auth_reads_response_body() -> None:673 """674 Test that we can read the response body in an auth flow if `requires_response_body`675 is set.676 """677 url = "https://example.org/"678 auth = ResponseBodyAuth("xyz")679 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:680 response = await client.get(url, auth=auth)681682 assert response.status_code == 200683 assert response.json() == {"auth": '{"auth": "xyz"}'}684685686def test_sync_auth_reads_response_body() -> None:687 """688 Test that we can read the response body in an auth flow if `requires_response_body`689 is set.690 """691 url = "https://example.org/"692 auth = ResponseBodyAuth("xyz")693694 with httpx.Client(transport=SyncMockTransport()) as client:695 response = client.get(url, auth=auth)696697 assert response.status_code == 200698 assert response.json() == {"auth": '{"auth": "xyz"}'}699700701@pytest.mark.asyncio702async def test_async_auth() -> None:703 """704 Test that we can use an auth implementation specific to the async case, to705 support cases that require performing I/O or using concurrency primitives (such706 as checking a disk-based cache or fetching a token from a remote auth server).707 """708 url = "https://example.org/"709 auth = SyncOrAsyncAuth()710711 async with httpx.AsyncClient(transport=AsyncMockTransport()) as client:712 response = await client.get(url, auth=auth)713714 assert response.status_code == 200715 assert response.json() == {"auth": "async-auth"}716717718def test_sync_auth() -> None:719 """720 Test that we can use an auth implementation specific to the sync case.721 """722 url = "https://example.org/"723 auth = SyncOrAsyncAuth()724725 with httpx.Client(transport=SyncMockTransport()) as client:726 response = client.get(url, auth=auth)727728 assert response.status_code == 200729 assert response.json() == {"auth": "sync-auth"}