test_auth.py
This file
Path
tests/client/test_auth.py
766 lines · 24.5 KiB · Python
Last changed by
Use consistent import style (#2493)Tom Christiebefore adoption7985f68
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 typing11from urllib.request import parse_keqv_list1213import pytest1415import httpx1617from ..common import FIXTURES_DIR181920class App:21 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:22 self.auth_header = auth_header23 self.status_code = status_code2425 def __call__(self, request: httpx.Request) -> httpx.Response:26 headers = {"www-authenticate": self.auth_header} if self.auth_header else {}27 data = {"auth": request.headers.get("Authorization")}28 return httpx.Response(self.status_code, headers=headers, json=data)293031class DigestApp: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 def __call__(self, request: httpx.Request) -> httpx.Response:46 if self._response_count < self.send_response_after_attempt:47 return self.challenge_send(request)4849 data = {"auth": request.headers.get("Authorization")}50 return httpx.Response(200, json=data)5152 def challenge_send(self, request: httpx.Request) -> httpx.Response:53 self._response_count += 154 nonce = (55 hashlib.sha256(os.urandom(8)).hexdigest()56 if self._regenerate_nonce57 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"58 )59 challenge_data = {60 "nonce": nonce,61 "qop": self.qop,62 "opaque": (63 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"64 ),65 "algorithm": self.algorithm,66 "stale": "FALSE",67 }68 challenge_str = ", ".join(69 '{}="{}"'.format(key, value)70 for key, value in challenge_data.items()71 if value72 )7374 headers = {75 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',76 }77 return httpx.Response(401, headers=headers)787980class RepeatAuth(httpx.Auth):81 """82 A mock authentication scheme that requires clients to send83 the request a fixed number of times, and then send a last request containing84 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers85 of intermediate responses.86 """8788 requires_request_body = True8990 def __init__(self, repeat: int):91 self.repeat = repeat9293 def auth_flow(94 self, request: httpx.Request95 ) -> typing.Generator[httpx.Request, httpx.Response, None]:96 nonces = []9798 for index in range(self.repeat):99 request.headers["Authorization"] = f"Repeat {index}"100 response = yield request101 nonces.append(response.headers["www-authenticate"])102103 key = ".".join(nonces)104 request.headers["Authorization"] = f"Repeat {key}"105 yield request106107108class ResponseBodyAuth(httpx.Auth):109 """110 A mock authentication scheme that requires clients to send an 'Authorization'111 header, then send back the contents of the response in the 'Authorization'112 header.113 """114115 requires_response_body = True116117 def __init__(self, token: str) -> None:118 self.token = token119120 def auth_flow(121 self, request: httpx.Request122 ) -> typing.Generator[httpx.Request, httpx.Response, None]:123 request.headers["Authorization"] = self.token124 response = yield request125 data = response.text126 request.headers["Authorization"] = data127 yield request128129130class SyncOrAsyncAuth(httpx.Auth):131 """132 A mock authentication scheme that uses a different implementation for the133 sync and async cases.134 """135136 def __init__(self) -> None:137 self._lock = threading.Lock()138 self._async_lock = asyncio.Lock()139140 def sync_auth_flow(141 self, request: httpx.Request142 ) -> typing.Generator[httpx.Request, httpx.Response, None]:143 with self._lock:144 request.headers["Authorization"] = "sync-auth"145 yield request146147 async def async_auth_flow(148 self, request: httpx.Request149 ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:150 async with self._async_lock:151 request.headers["Authorization"] = "async-auth"152 yield request153154155@pytest.mark.asyncio156async def test_basic_auth() -> None:157 url = "https://example.org/"158 auth = ("user", "password123")159 app = App()160161 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:162 response = await client.get(url, auth=auth)163164 assert response.status_code == 200165 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}166167168@pytest.mark.asyncio169async def test_basic_auth_with_stream() -> None:170 """171 See: https://github.com/encode/httpx/pull/1312172 """173 url = "https://example.org/"174 auth = ("user", "password123")175 app = App()176177 async with httpx.AsyncClient(178 transport=httpx.MockTransport(app), auth=auth179 ) as client:180 async with client.stream("GET", url) as response:181 await response.aread()182183 assert response.status_code == 200184 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}185186187@pytest.mark.asyncio188async def test_basic_auth_in_url() -> None:189 url = "https://user:password123@example.org/"190 app = App()191192 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:193 response = await client.get(url)194195 assert response.status_code == 200196 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}197198199@pytest.mark.asyncio200async def test_basic_auth_on_session() -> None:201 url = "https://example.org/"202 auth = ("user", "password123")203 app = App()204205 async with httpx.AsyncClient(206 transport=httpx.MockTransport(app), auth=auth207 ) as client:208 response = await client.get(url)209210 assert response.status_code == 200211 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}212213214@pytest.mark.asyncio215async def test_custom_auth() -> None:216 url = "https://example.org/"217 app = App()218219 def auth(request: httpx.Request) -> httpx.Request:220 request.headers["Authorization"] = "Token 123"221 return request222223 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:224 response = await client.get(url, auth=auth)225226 assert response.status_code == 200227 assert response.json() == {"auth": "Token 123"}228229230@pytest.mark.asyncio231async def test_netrc_auth() -> None:232 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")233 url = "http://netrcexample.org"234 app = App()235236 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:237 response = await client.get(url)238239 assert response.status_code == 200240 assert response.json() == {241 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"242 }243244245@pytest.mark.asyncio246async def test_auth_header_has_priority_over_netrc() -> None:247 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")248 url = "http://netrcexample.org"249 app = App()250251 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: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"] = str(FIXTURES_DIR / ".netrc")261 url = "http://netrcexample.org"262 app = App()263264 async with httpx.AsyncClient(265 transport=httpx.MockTransport(app), trust_env=False266 ) as client:267 response = await client.get(url)268269 assert response.status_code == 200270 assert response.json() == {"auth": None}271272 async with httpx.AsyncClient(273 transport=httpx.MockTransport(app), trust_env=True274 ) as client:275 response = await client.get(url)276277 assert response.status_code == 200278 assert response.json() == {279 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280 }281282283@pytest.mark.asyncio284async def test_auth_disable_per_request() -> None:285 url = "https://example.org/"286 auth = ("user", "password123")287 app = App()288289 async with httpx.AsyncClient(290 transport=httpx.MockTransport(app), auth=auth291 ) as client:292 response = await client.get(url, auth=None)293294 assert response.status_code == 200295 assert response.json() == {"auth": None}296297298def test_auth_hidden_url() -> None:299 url = "http://example-username:example-password@example.org/"300 expected = "URL('http://example-username:[secure]@example.org/')"301 assert url == httpx.URL(url)302 assert expected == repr(httpx.URL(url))303304305@pytest.mark.asyncio306async def test_auth_hidden_header() -> None:307 url = "https://example.org/"308 auth = ("example-username", "example-password")309 app = App()310311 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:312 response = await client.get(url, auth=auth)313314 assert "'authorization': '[secure]'" in str(response.request.headers)315316317@pytest.mark.asyncio318async def test_auth_property() -> None:319 app = App()320321 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:322 assert client.auth is None323324 client.auth = ("user", "password123") # type: ignore325 assert isinstance(client.auth, httpx.BasicAuth)326327 url = "https://example.org/"328 response = await client.get(url)329 assert response.status_code == 200330 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}331332333@pytest.mark.asyncio334async def test_auth_invalid_type() -> None:335 app = App()336337 with pytest.raises(TypeError):338 client = httpx.AsyncClient(339 transport=httpx.MockTransport(app),340 auth="not a tuple, not a callable", # type: ignore341 )342343 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:344 with pytest.raises(TypeError):345 await client.get(auth="not a tuple, not a callable") # type: ignore346347 with pytest.raises(TypeError):348 client.auth = "not a tuple, not a callable" # type: ignore349350351@pytest.mark.asyncio352async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:353 url = "https://example.org/"354 auth = httpx.DigestAuth(username="user", password="password123")355 app = App()356357 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:358 response = await client.get(url, auth=auth)359360 assert response.status_code == 200361 assert response.json() == {"auth": None}362 assert len(response.history) == 0363364365def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:366 url = "https://example.org/"367 auth = httpx.DigestAuth(username="user", password="password123")368 auth_header = "Token ..."369 app = App(auth_header=auth_header, status_code=401)370371 client = httpx.Client(transport=httpx.MockTransport(app))372 response = client.get(url, auth=auth)373374 assert response.status_code == 401375 assert response.json() == {"auth": None}376 assert len(response.history) == 0377378379@pytest.mark.asyncio380async def test_digest_auth_200_response_including_digest_auth_header() -> None:381 url = "https://example.org/"382 auth = httpx.DigestAuth(username="user", password="password123")383 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'384 app = App(auth_header=auth_header, status_code=200)385386 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:387 response = await client.get(url, auth=auth)388389 assert response.status_code == 200390 assert response.json() == {"auth": None}391 assert len(response.history) == 0392393394@pytest.mark.asyncio395async def test_digest_auth_401_response_without_digest_auth_header() -> None:396 url = "https://example.org/"397 auth = httpx.DigestAuth(username="user", password="password123")398 app = App(auth_header="", status_code=401)399400 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:401 response = await client.get(url, auth=auth)402403 assert response.status_code == 401404 assert response.json() == {"auth": None}405 assert len(response.history) == 0406407408@pytest.mark.parametrize(409 "algorithm,expected_hash_length,expected_response_length",410 [411 ("MD5", 64, 32),412 ("MD5-SESS", 64, 32),413 ("SHA", 64, 40),414 ("SHA-SESS", 64, 40),415 ("SHA-256", 64, 64),416 ("SHA-256-SESS", 64, 64),417 ("SHA-512", 64, 128),418 ("SHA-512-SESS", 64, 128),419 ],420)421@pytest.mark.asyncio422async def test_digest_auth(423 algorithm: str, expected_hash_length: int, expected_response_length: int424) -> None:425 url = "https://example.org/"426 auth = httpx.DigestAuth(username="user", password="password123")427 app = DigestApp(algorithm=algorithm)428429 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:430 response = await client.get(url, auth=auth)431432 assert response.status_code == 200433 assert len(response.history) == 1434435 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]436 scheme, _, fields = authorization.partition(" ")437 assert scheme == "Digest"438439 response_fields = [field.strip() for field in fields.split(",")]440 digest_data = dict(field.split("=") for field in response_fields)441442 assert digest_data["username"] == '"user"'443 assert digest_data["realm"] == '"httpx@example.org"'444 assert "nonce" in digest_data445 assert digest_data["uri"] == '"/"'446 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes447 assert len(digest_data["opaque"]) == expected_hash_length + 2448 assert digest_data["algorithm"] == algorithm449 assert digest_data["qop"] == "auth"450 assert digest_data["nc"] == "00000001"451 assert len(digest_data["cnonce"]) == 16 + 2452453454@pytest.mark.asyncio455async def test_digest_auth_no_specified_qop() -> None:456 url = "https://example.org/"457 auth = httpx.DigestAuth(username="user", password="password123")458 app = DigestApp(qop="")459460 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:461 response = await client.get(url, auth=auth)462463 assert response.status_code == 200464 assert len(response.history) == 1465466 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]467 scheme, _, fields = authorization.partition(" ")468 assert scheme == "Digest"469470 response_fields = [field.strip() for field in fields.split(",")]471 digest_data = dict(field.split("=") for field in response_fields)472473 assert "qop" not in digest_data474 assert "nc" not in digest_data475 assert "cnonce" not in digest_data476 assert digest_data["username"] == '"user"'477 assert digest_data["realm"] == '"httpx@example.org"'478 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes479 assert digest_data["uri"] == '"/"'480 assert len(digest_data["response"]) == 64 + 2481 assert len(digest_data["opaque"]) == 64 + 2482 assert digest_data["algorithm"] == "SHA-256"483484485@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))486@pytest.mark.asyncio487async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:488 url = "https://example.org/"489 auth = httpx.DigestAuth(username="user", password="password123")490 app = DigestApp(qop=qop)491492 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:493 response = await client.get(url, auth=auth)494495 assert response.status_code == 200496 assert len(response.history) == 1497498499@pytest.mark.asyncio500async def test_digest_auth_qop_auth_int_not_implemented() -> None:501 url = "https://example.org/"502 auth = httpx.DigestAuth(username="user", password="password123")503 app = DigestApp(qop="auth-int")504505 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:506 with pytest.raises(NotImplementedError):507 await client.get(url, auth=auth)508509510@pytest.mark.asyncio511async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:512 url = "https://example.org/"513 auth = httpx.DigestAuth(username="user", password="password123")514 app = DigestApp(qop="not-auth")515516 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:517 with pytest.raises(httpx.ProtocolError):518 await client.get(url, auth=auth)519520521@pytest.mark.asyncio522async def test_digest_auth_incorrect_credentials() -> None:523 url = "https://example.org/"524 auth = httpx.DigestAuth(username="user", password="password123")525 app = DigestApp(send_response_after_attempt=2)526527 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:528 response = await client.get(url, auth=auth)529530 assert response.status_code == 401531 assert len(response.history) == 1532533534@pytest.mark.asyncio535async def test_digest_auth_reuses_challenge() -> None:536 url = "https://example.org/"537 auth = httpx.DigestAuth(username="user", password="password123")538 app = DigestApp()539540 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:541 response_1 = await client.get(url, auth=auth)542 response_2 = await client.get(url, auth=auth)543544 assert response_1.status_code == 200545 assert response_2.status_code == 200546547 assert len(response_1.history) == 1548 assert len(response_2.history) == 0549550551@pytest.mark.asyncio552async def test_digest_auth_resets_nonce_count_after_401() -> None:553 url = "https://example.org/"554 auth = httpx.DigestAuth(username="user", password="password123")555 app = DigestApp()556557 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:558 response_1 = await client.get(url, auth=auth)559 assert response_1.status_code == 200560 assert len(response_1.history) == 1561562 first_nonce = parse_keqv_list(563 response_1.request.headers["Authorization"].split(", ")564 )["nonce"]565 first_nc = parse_keqv_list(566 response_1.request.headers["Authorization"].split(", ")567 )["nc"]568569 # with this we now force a 401 on a subsequent (but initial) request570 app.send_response_after_attempt = 2571572 # we expect the client again to try to authenticate, i.e. the history length must be 1573 response_2 = await client.get(url, auth=auth)574 assert response_2.status_code == 200575 assert len(response_2.history) == 1576577 second_nonce = parse_keqv_list(578 response_2.request.headers["Authorization"].split(", ")579 )["nonce"]580 second_nc = parse_keqv_list(581 response_2.request.headers["Authorization"].split(", ")582 )["nc"]583584 assert first_nonce != second_nonce # ensures that the auth challenge was reset585 assert (586 first_nc == second_nc587 ) # ensures the nonce count is reset when the authentication failed588589590@pytest.mark.parametrize(591 "auth_header",592 [593 'Digest realm="httpx@example.org", qop="auth"', # missing fields594 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list595 ],596)597@pytest.mark.asyncio598async def test_async_digest_auth_raises_protocol_error_on_malformed_header(599 auth_header: str,600) -> None:601 url = "https://example.org/"602 auth = httpx.DigestAuth(username="user", password="password123")603 app = App(auth_header=auth_header, status_code=401)604605 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:606 with pytest.raises(httpx.ProtocolError):607 await client.get(url, auth=auth)608609610@pytest.mark.parametrize(611 "auth_header",612 [613 'Digest realm="httpx@example.org", qop="auth"', # missing fields614 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list615 ],616)617def test_sync_digest_auth_raises_protocol_error_on_malformed_header(618 auth_header: str,619) -> None:620 url = "https://example.org/"621 auth = httpx.DigestAuth(username="user", password="password123")622 app = App(auth_header=auth_header, status_code=401)623624 with httpx.Client(transport=httpx.MockTransport(app)) as client:625 with pytest.raises(httpx.ProtocolError):626 client.get(url, auth=auth)627628629@pytest.mark.asyncio630async def test_async_auth_history() -> None:631 """632 Test that intermediate requests sent as part of an authentication flow633 are recorded in the response history.634 """635 url = "https://example.org/"636 auth = RepeatAuth(repeat=2)637 app = App(auth_header="abc")638639 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:640 response = await client.get(url, auth=auth)641642 assert response.status_code == 200643 assert response.json() == {"auth": "Repeat abc.abc"}644645 assert len(response.history) == 2646 resp1, resp2 = response.history647 assert resp1.json() == {"auth": "Repeat 0"}648 assert resp2.json() == {"auth": "Repeat 1"}649650 assert len(resp2.history) == 1651 assert resp2.history == [resp1]652653 assert len(resp1.history) == 0654655656def test_sync_auth_history() -> None:657 """658 Test that intermediate requests sent as part of an authentication flow659 are recorded in the response history.660 """661 url = "https://example.org/"662 auth = RepeatAuth(repeat=2)663 app = App(auth_header="abc")664665 with httpx.Client(transport=httpx.MockTransport(app)) as client:666 response = client.get(url, auth=auth)667668 assert response.status_code == 200669 assert response.json() == {"auth": "Repeat abc.abc"}670671 assert len(response.history) == 2672 resp1, resp2 = response.history673 assert resp1.json() == {"auth": "Repeat 0"}674 assert resp2.json() == {"auth": "Repeat 1"}675676 assert len(resp2.history) == 1677 assert resp2.history == [resp1]678679 assert len(resp1.history) == 0680681682class ConsumeBodyTransport(httpx.MockTransport):683 async def handle_async_request(self, request: httpx.Request) -> httpx.Response:684 assert isinstance(request.stream, httpx.AsyncByteStream)685 [_ async for _ in request.stream]686 return self.handler(request)687688689@pytest.mark.asyncio690async def test_digest_auth_unavailable_streaming_body():691 url = "https://example.org/"692 auth = httpx.DigestAuth(username="user", password="password123")693 app = DigestApp()694695 async def streaming_body() -> typing.AsyncIterator[bytes]:696 yield b"Example request body" # pragma: no cover697698 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:699 with pytest.raises(httpx.StreamConsumed):700 await client.post(url, content=streaming_body(), auth=auth)701702703@pytest.mark.asyncio704async def test_async_auth_reads_response_body() -> None:705 """706 Test that we can read the response body in an auth flow if `requires_response_body`707 is set.708 """709 url = "https://example.org/"710 auth = ResponseBodyAuth("xyz")711 app = App()712713 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:714 response = await client.get(url, auth=auth)715716 assert response.status_code == 200717 assert response.json() == {"auth": '{"auth": "xyz"}'}718719720def test_sync_auth_reads_response_body() -> None:721 """722 Test that we can read the response body in an auth flow if `requires_response_body`723 is set.724 """725 url = "https://example.org/"726 auth = ResponseBodyAuth("xyz")727 app = App()728729 with httpx.Client(transport=httpx.MockTransport(app)) as client:730 response = client.get(url, auth=auth)731732 assert response.status_code == 200733 assert response.json() == {"auth": '{"auth": "xyz"}'}734735736@pytest.mark.asyncio737async def test_async_auth() -> None:738 """739 Test that we can use an auth implementation specific to the async case, to740 support cases that require performing I/O or using concurrency primitives (such741 as checking a disk-based cache or fetching a token from a remote auth server).742 """743 url = "https://example.org/"744 auth = SyncOrAsyncAuth()745 app = App()746747 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:748 response = await client.get(url, auth=auth)749750 assert response.status_code == 200751 assert response.json() == {"auth": "async-auth"}752753754def test_sync_auth() -> None:755 """756 Test that we can use an auth implementation specific to the sync case.757 """758 url = "https://example.org/"759 auth = SyncOrAsyncAuth()760 app = App()761762 with httpx.Client(transport=httpx.MockTransport(app)) as client:763 response = client.get(url, auth=auth)764765 assert response.status_code == 200766 assert response.json() == {"auth": "sync-auth"}