test_auth.py
This file
Path
tests/client/test_auth.py
763 lines · 24.3 KiB · Python
Last changed by
Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
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 httpx16from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response1718from ..common import FIXTURES_DIR192021class App:22 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:23 self.auth_header = auth_header24 self.status_code = status_code2526 def __call__(self, request: httpx.Request) -> httpx.Response:27 headers = {"www-authenticate": self.auth_header} if self.auth_header else {}28 data = {"auth": request.headers.get("Authorization")}29 return httpx.Response(self.status_code, headers=headers, json=data)303132class DigestApp: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 def __call__(self, request: httpx.Request) -> httpx.Response:47 if self._response_count < self.send_response_after_attempt:48 return self.challenge_send(request)4950 data = {"auth": request.headers.get("Authorization")}51 return httpx.Response(200, json=data)5253 def challenge_send(self, request: httpx.Request) -> httpx.Response:54 self._response_count += 155 nonce = (56 hashlib.sha256(os.urandom(8)).hexdigest()57 if self._regenerate_nonce58 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"59 )60 challenge_data = {61 "nonce": nonce,62 "qop": self.qop,63 "opaque": (64 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"65 ),66 "algorithm": self.algorithm,67 "stale": "FALSE",68 }69 challenge_str = ", ".join(70 '{}="{}"'.format(key, value)71 for key, value in challenge_data.items()72 if value73 )7475 headers = {76 "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',77 }78 return Response(401, headers=headers)798081class RepeatAuth(Auth):82 """83 A mock authentication scheme that requires clients to send84 the request a fixed number of times, and then send a last request containing85 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers86 of intermediate responses.87 """8889 requires_request_body = True9091 def __init__(self, repeat: int):92 self.repeat = repeat9394 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:95 nonces = []9697 for index in range(self.repeat):98 request.headers["Authorization"] = f"Repeat {index}"99 response = yield request100 nonces.append(response.headers["www-authenticate"])101102 key = ".".join(nonces)103 request.headers["Authorization"] = f"Repeat {key}"104 yield request105106107class ResponseBodyAuth(Auth):108 """109 A mock authentication scheme that requires clients to send an 'Authorization'110 header, then send back the contents of the response in the 'Authorization'111 header.112 """113114 requires_response_body = True115116 def __init__(self, token: str) -> None:117 self.token = token118119 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:120 request.headers["Authorization"] = self.token121 response = yield request122 data = response.text123 request.headers["Authorization"] = data124 yield request125126127class SyncOrAsyncAuth(Auth):128 """129 A mock authentication scheme that uses a different implementation for the130 sync and async cases.131 """132133 def __init__(self) -> None:134 self._lock = threading.Lock()135 self._async_lock = asyncio.Lock()136137 def sync_auth_flow(138 self, request: Request139 ) -> typing.Generator[Request, Response, None]:140 with self._lock:141 request.headers["Authorization"] = "sync-auth"142 yield request143144 async def async_auth_flow(145 self, request: Request146 ) -> typing.AsyncGenerator[Request, Response]:147 async with self._async_lock:148 request.headers["Authorization"] = "async-auth"149 yield request150151152@pytest.mark.asyncio153async def test_basic_auth() -> None:154 url = "https://example.org/"155 auth = ("user", "password123")156 app = App()157158 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:159 response = await client.get(url, auth=auth)160161 assert response.status_code == 200162 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}163164165@pytest.mark.asyncio166async def test_basic_auth_with_stream() -> None:167 """168 See: https://github.com/encode/httpx/pull/1312169 """170 url = "https://example.org/"171 auth = ("user", "password123")172 app = App()173174 async with httpx.AsyncClient(175 transport=httpx.MockTransport(app), auth=auth176 ) as client:177 async with client.stream("GET", url) as response:178 await response.aread()179180 assert response.status_code == 200181 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}182183184@pytest.mark.asyncio185async def test_basic_auth_in_url() -> None:186 url = "https://user:password123@example.org/"187 app = App()188189 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:190 response = await client.get(url)191192 assert response.status_code == 200193 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}194195196@pytest.mark.asyncio197async def test_basic_auth_on_session() -> None:198 url = "https://example.org/"199 auth = ("user", "password123")200 app = App()201202 async with httpx.AsyncClient(203 transport=httpx.MockTransport(app), auth=auth204 ) as client:205 response = await client.get(url)206207 assert response.status_code == 200208 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}209210211@pytest.mark.asyncio212async def test_custom_auth() -> None:213 url = "https://example.org/"214 app = App()215216 def auth(request: Request) -> Request:217 request.headers["Authorization"] = "Token 123"218 return request219220 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:221 response = await client.get(url, auth=auth)222223 assert response.status_code == 200224 assert response.json() == {"auth": "Token 123"}225226227@pytest.mark.asyncio228async def test_netrc_auth() -> None:229 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")230 url = "http://netrcexample.org"231 app = App()232233 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:234 response = await client.get(url)235236 assert response.status_code == 200237 assert response.json() == {238 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"239 }240241242@pytest.mark.asyncio243async def test_auth_header_has_priority_over_netrc() -> None:244 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")245 url = "http://netrcexample.org"246 app = App()247248 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:249 response = await client.get(url, headers={"Authorization": "Override"})250251 assert response.status_code == 200252 assert response.json() == {"auth": "Override"}253254255@pytest.mark.asyncio256async def test_trust_env_auth() -> None:257 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")258 url = "http://netrcexample.org"259 app = App()260261 async with httpx.AsyncClient(262 transport=httpx.MockTransport(app), trust_env=False263 ) as client:264 response = await client.get(url)265266 assert response.status_code == 200267 assert response.json() == {"auth": None}268269 async with httpx.AsyncClient(270 transport=httpx.MockTransport(app), trust_env=True271 ) as client:272 response = await client.get(url)273274 assert response.status_code == 200275 assert response.json() == {276 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"277 }278279280@pytest.mark.asyncio281async def test_auth_disable_per_request() -> None:282 url = "https://example.org/"283 auth = ("user", "password123")284 app = App()285286 async with httpx.AsyncClient(287 transport=httpx.MockTransport(app), auth=auth288 ) as client:289 response = await client.get(url, auth=None)290291 assert response.status_code == 200292 assert response.json() == {"auth": None}293294295def test_auth_hidden_url() -> None:296 url = "http://example-username:example-password@example.org/"297 expected = "URL('http://example-username:[secure]@example.org/')"298 assert url == URL(url)299 assert expected == repr(URL(url))300301302@pytest.mark.asyncio303async def test_auth_hidden_header() -> None:304 url = "https://example.org/"305 auth = ("example-username", "example-password")306 app = App()307308 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:309 response = await client.get(url, auth=auth)310311 assert "'authorization': '[secure]'" in str(response.request.headers)312313314@pytest.mark.asyncio315async def test_auth_property() -> None:316 app = App()317318 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:319 assert client.auth is None320321 client.auth = ("user", "password123") # type: ignore322 assert isinstance(client.auth, BasicAuth)323324 url = "https://example.org/"325 response = await client.get(url)326 assert response.status_code == 200327 assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}328329330@pytest.mark.asyncio331async def test_auth_invalid_type() -> None:332 app = App()333334 with pytest.raises(TypeError):335 client = httpx.AsyncClient(336 transport=httpx.MockTransport(app),337 auth="not a tuple, not a callable", # type: ignore338 )339340 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:341 with pytest.raises(TypeError):342 await client.get(auth="not a tuple, not a callable") # type: ignore343344 with pytest.raises(TypeError):345 client.auth = "not a tuple, not a callable" # type: ignore346347348@pytest.mark.asyncio349async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:350 url = "https://example.org/"351 auth = DigestAuth(username="user", password="password123")352 app = App()353354 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:355 response = await client.get(url, auth=auth)356357 assert response.status_code == 200358 assert response.json() == {"auth": None}359 assert len(response.history) == 0360361362def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:363 url = "https://example.org/"364 auth = DigestAuth(username="user", password="password123")365 auth_header = "Token ..."366 app = App(auth_header=auth_header, status_code=401)367368 client = httpx.Client(transport=httpx.MockTransport(app))369 response = client.get(url, auth=auth)370371 assert response.status_code == 401372 assert response.json() == {"auth": None}373 assert len(response.history) == 0374375376@pytest.mark.asyncio377async def test_digest_auth_200_response_including_digest_auth_header() -> None:378 url = "https://example.org/"379 auth = DigestAuth(username="user", password="password123")380 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'381 app = App(auth_header=auth_header, status_code=200)382383 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) 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) == 0389390391@pytest.mark.asyncio392async def test_digest_auth_401_response_without_digest_auth_header() -> None:393 url = "https://example.org/"394 auth = DigestAuth(username="user", password="password123")395 app = App(auth_header="", status_code=401)396397 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:398 response = await client.get(url, auth=auth)399400 assert response.status_code == 401401 assert response.json() == {"auth": None}402 assert len(response.history) == 0403404405@pytest.mark.parametrize(406 "algorithm,expected_hash_length,expected_response_length",407 [408 ("MD5", 64, 32),409 ("MD5-SESS", 64, 32),410 ("SHA", 64, 40),411 ("SHA-SESS", 64, 40),412 ("SHA-256", 64, 64),413 ("SHA-256-SESS", 64, 64),414 ("SHA-512", 64, 128),415 ("SHA-512-SESS", 64, 128),416 ],417)418@pytest.mark.asyncio419async def test_digest_auth(420 algorithm: str, expected_hash_length: int, expected_response_length: int421) -> None:422 url = "https://example.org/"423 auth = DigestAuth(username="user", password="password123")424 app = DigestApp(algorithm=algorithm)425426 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:427 response = await client.get(url, auth=auth)428429 assert response.status_code == 200430 assert len(response.history) == 1431432 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]433 scheme, _, fields = authorization.partition(" ")434 assert scheme == "Digest"435436 response_fields = [field.strip() for field in fields.split(",")]437 digest_data = dict(field.split("=") for field in response_fields)438439 assert digest_data["username"] == '"user"'440 assert digest_data["realm"] == '"httpx@example.org"'441 assert "nonce" in digest_data442 assert digest_data["uri"] == '"/"'443 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes444 assert len(digest_data["opaque"]) == expected_hash_length + 2445 assert digest_data["algorithm"] == algorithm446 assert digest_data["qop"] == "auth"447 assert digest_data["nc"] == "00000001"448 assert len(digest_data["cnonce"]) == 16 + 2449450451@pytest.mark.asyncio452async def test_digest_auth_no_specified_qop() -> None:453 url = "https://example.org/"454 auth = DigestAuth(username="user", password="password123")455 app = DigestApp(qop="")456457 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:458 response = await client.get(url, auth=auth)459460 assert response.status_code == 200461 assert len(response.history) == 1462463 authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]464 scheme, _, fields = authorization.partition(" ")465 assert scheme == "Digest"466467 response_fields = [field.strip() for field in fields.split(",")]468 digest_data = dict(field.split("=") for field in response_fields)469470 assert "qop" not in digest_data471 assert "nc" not in digest_data472 assert "cnonce" not in digest_data473 assert digest_data["username"] == '"user"'474 assert digest_data["realm"] == '"httpx@example.org"'475 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes476 assert digest_data["uri"] == '"/"'477 assert len(digest_data["response"]) == 64 + 2478 assert len(digest_data["opaque"]) == 64 + 2479 assert digest_data["algorithm"] == "SHA-256"480481482@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))483@pytest.mark.asyncio484async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:485 url = "https://example.org/"486 auth = DigestAuth(username="user", password="password123")487 app = DigestApp(qop=qop)488489 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:490 response = await client.get(url, auth=auth)491492 assert response.status_code == 200493 assert len(response.history) == 1494495496@pytest.mark.asyncio497async def test_digest_auth_qop_auth_int_not_implemented() -> None:498 url = "https://example.org/"499 auth = DigestAuth(username="user", password="password123")500 app = DigestApp(qop="auth-int")501502 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:503 with pytest.raises(NotImplementedError):504 await client.get(url, auth=auth)505506507@pytest.mark.asyncio508async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:509 url = "https://example.org/"510 auth = DigestAuth(username="user", password="password123")511 app = DigestApp(qop="not-auth")512513 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:514 with pytest.raises(ProtocolError):515 await client.get(url, auth=auth)516517518@pytest.mark.asyncio519async def test_digest_auth_incorrect_credentials() -> None:520 url = "https://example.org/"521 auth = DigestAuth(username="user", password="password123")522 app = DigestApp(send_response_after_attempt=2)523524 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:525 response = await client.get(url, auth=auth)526527 assert response.status_code == 401528 assert len(response.history) == 1529530531@pytest.mark.asyncio532async def test_digest_auth_reuses_challenge() -> None:533 url = "https://example.org/"534 auth = DigestAuth(username="user", password="password123")535 app = DigestApp()536537 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:538 response_1 = await client.get(url, auth=auth)539 response_2 = await client.get(url, auth=auth)540541 assert response_1.status_code == 200542 assert response_2.status_code == 200543544 assert len(response_1.history) == 1545 assert len(response_2.history) == 0546547548@pytest.mark.asyncio549async def test_digest_auth_resets_nonce_count_after_401() -> None:550 url = "https://example.org/"551 auth = DigestAuth(username="user", password="password123")552 app = DigestApp()553554 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:555 response_1 = await client.get(url, auth=auth)556 assert response_1.status_code == 200557 assert len(response_1.history) == 1558559 first_nonce = parse_keqv_list(560 response_1.request.headers["Authorization"].split(", ")561 )["nonce"]562 first_nc = parse_keqv_list(563 response_1.request.headers["Authorization"].split(", ")564 )["nc"]565566 # with this we now force a 401 on a subsequent (but initial) request567 app.send_response_after_attempt = 2568569 # we expect the client again to try to authenticate, i.e. the history length must be 1570 response_2 = await client.get(url, auth=auth)571 assert response_2.status_code == 200572 assert len(response_2.history) == 1573574 second_nonce = parse_keqv_list(575 response_2.request.headers["Authorization"].split(", ")576 )["nonce"]577 second_nc = parse_keqv_list(578 response_2.request.headers["Authorization"].split(", ")579 )["nc"]580581 assert first_nonce != second_nonce # ensures that the auth challenge was reset582 assert (583 first_nc == second_nc584 ) # ensures the nonce count is reset when the authentication failed585586587@pytest.mark.parametrize(588 "auth_header",589 [590 'Digest realm="httpx@example.org", qop="auth"', # missing fields591 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list592 ],593)594@pytest.mark.asyncio595async def test_async_digest_auth_raises_protocol_error_on_malformed_header(596 auth_header: str,597) -> None:598 url = "https://example.org/"599 auth = DigestAuth(username="user", password="password123")600 app = App(auth_header=auth_header, status_code=401)601602 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:603 with pytest.raises(ProtocolError):604 await client.get(url, auth=auth)605606607@pytest.mark.parametrize(608 "auth_header",609 [610 'Digest realm="httpx@example.org", qop="auth"', # missing fields611 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list612 ],613)614def test_sync_digest_auth_raises_protocol_error_on_malformed_header(615 auth_header: str,616) -> None:617 url = "https://example.org/"618 auth = DigestAuth(username="user", password="password123")619 app = App(auth_header=auth_header, status_code=401)620621 with httpx.Client(transport=httpx.MockTransport(app)) as client:622 with pytest.raises(ProtocolError):623 client.get(url, auth=auth)624625626@pytest.mark.asyncio627async def test_async_auth_history() -> None:628 """629 Test that intermediate requests sent as part of an authentication flow630 are recorded in the response history.631 """632 url = "https://example.org/"633 auth = RepeatAuth(repeat=2)634 app = App(auth_header="abc")635636 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:637 response = await client.get(url, auth=auth)638639 assert response.status_code == 200640 assert response.json() == {"auth": "Repeat abc.abc"}641642 assert len(response.history) == 2643 resp1, resp2 = response.history644 assert resp1.json() == {"auth": "Repeat 0"}645 assert resp2.json() == {"auth": "Repeat 1"}646647 assert len(resp2.history) == 1648 assert resp2.history == [resp1]649650 assert len(resp1.history) == 0651652653def test_sync_auth_history() -> None:654 """655 Test that intermediate requests sent as part of an authentication flow656 are recorded in the response history.657 """658 url = "https://example.org/"659 auth = RepeatAuth(repeat=2)660 app = App(auth_header="abc")661662 with httpx.Client(transport=httpx.MockTransport(app)) as client:663 response = client.get(url, auth=auth)664665 assert response.status_code == 200666 assert response.json() == {"auth": "Repeat abc.abc"}667668 assert len(response.history) == 2669 resp1, resp2 = response.history670 assert resp1.json() == {"auth": "Repeat 0"}671 assert resp2.json() == {"auth": "Repeat 1"}672673 assert len(resp2.history) == 1674 assert resp2.history == [resp1]675676 assert len(resp1.history) == 0677678679class ConsumeBodyTransport(httpx.MockTransport):680 async def handle_async_request(self, request: Request) -> Response:681 assert isinstance(request.stream, httpx.AsyncByteStream)682 [_ async for _ in request.stream]683 return self.handler(request)684685686@pytest.mark.asyncio687async def test_digest_auth_unavailable_streaming_body():688 url = "https://example.org/"689 auth = DigestAuth(username="user", password="password123")690 app = DigestApp()691692 async def streaming_body() -> typing.AsyncIterator[bytes]:693 yield b"Example request body" # pragma: no cover694695 async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:696 with pytest.raises(httpx.StreamConsumed):697 await client.post(url, content=streaming_body(), auth=auth)698699700@pytest.mark.asyncio701async def test_async_auth_reads_response_body() -> None:702 """703 Test that we can read the response body in an auth flow if `requires_response_body`704 is set.705 """706 url = "https://example.org/"707 auth = ResponseBodyAuth("xyz")708 app = App()709710 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:711 response = await client.get(url, auth=auth)712713 assert response.status_code == 200714 assert response.json() == {"auth": '{"auth": "xyz"}'}715716717def test_sync_auth_reads_response_body() -> None:718 """719 Test that we can read the response body in an auth flow if `requires_response_body`720 is set.721 """722 url = "https://example.org/"723 auth = ResponseBodyAuth("xyz")724 app = App()725726 with httpx.Client(transport=httpx.MockTransport(app)) as client:727 response = client.get(url, auth=auth)728729 assert response.status_code == 200730 assert response.json() == {"auth": '{"auth": "xyz"}'}731732733@pytest.mark.asyncio734async def test_async_auth() -> None:735 """736 Test that we can use an auth implementation specific to the async case, to737 support cases that require performing I/O or using concurrency primitives (such738 as checking a disk-based cache or fetching a token from a remote auth server).739 """740 url = "https://example.org/"741 auth = SyncOrAsyncAuth()742 app = App()743744 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:745 response = await client.get(url, auth=auth)746747 assert response.status_code == 200748 assert response.json() == {"auth": "async-auth"}749750751def test_sync_auth() -> None:752 """753 Test that we can use an auth implementation specific to the sync case.754 """755 url = "https://example.org/"756 auth = SyncOrAsyncAuth()757 app = App()758759 with httpx.Client(transport=httpx.MockTransport(app)) as client:760 response = client.get(url, auth=auth)761762 assert response.status_code == 200763 assert response.json() == {"auth": "sync-auth"}