test_auth.py
This file
Path
tests/client/test_auth.py
694 lines · 21.9 KiB · Python
Last changed by
Fix stream unsetting auth (#1312)Tom Christiebefore adoptiond25f2bf
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 pytest1314import httpx15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response16from tests.utils import MockTransport1718from ..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):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 = ("tomchristie", "password123")156 app = App()157158 async with httpx.AsyncClient(transport=MockTransport(app)) as client:159 response = await client.get(url, auth=auth)160161 assert response.status_code == 200162 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}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 = ("tomchristie", "password123")172 app = App()173174 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:175 async with client.stream("GET", url) as response:176 response.read()177178 assert response.status_code == 200179 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}180181182@pytest.mark.asyncio183async def test_basic_auth_in_url() -> None:184 url = "https://tomchristie:password123@example.org/"185 app = App()186187 async with httpx.AsyncClient(transport=MockTransport(app)) as client:188 response = await client.get(url)189190 assert response.status_code == 200191 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}192193194@pytest.mark.asyncio195async def test_basic_auth_on_session() -> None:196 url = "https://example.org/"197 auth = ("tomchristie", "password123")198 app = App()199200 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:201 response = await client.get(url)202203 assert response.status_code == 200204 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}205206207@pytest.mark.asyncio208async def test_custom_auth() -> None:209 url = "https://example.org/"210 app = App()211212 def auth(request: Request) -> Request:213 request.headers["Authorization"] = "Token 123"214 return request215216 async with httpx.AsyncClient(transport=MockTransport(app)) as client:217 response = await client.get(url, auth=auth)218219 assert response.status_code == 200220 assert response.json() == {"auth": "Token 123"}221222223@pytest.mark.asyncio224async def test_netrc_auth() -> None:225 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")226 url = "http://netrcexample.org"227 app = App()228229 async with httpx.AsyncClient(transport=MockTransport(app)) as client:230 response = await client.get(url)231232 assert response.status_code == 200233 assert response.json() == {234 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"235 }236237238@pytest.mark.asyncio239async def test_auth_header_has_priority_over_netrc() -> None:240 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")241 url = "http://netrcexample.org"242 app = App()243244 async with httpx.AsyncClient(transport=MockTransport(app)) as client:245 response = await client.get(url, headers={"Authorization": "Override"})246247 assert response.status_code == 200248 assert response.json() == {"auth": "Override"}249250251@pytest.mark.asyncio252async def test_trust_env_auth() -> None:253 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")254 url = "http://netrcexample.org"255 app = App()256257 async with httpx.AsyncClient(258 transport=MockTransport(app), trust_env=False259 ) as client:260 response = await client.get(url)261262 assert response.status_code == 200263 assert response.json() == {"auth": None}264265 async with httpx.AsyncClient(266 transport=MockTransport(app), trust_env=True267 ) as client:268 response = await client.get(url)269270 assert response.status_code == 200271 assert response.json() == {272 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"273 }274275276@pytest.mark.asyncio277async def test_auth_disable_per_request() -> None:278 url = "https://example.org/"279 auth = ("tomchristie", "password123")280 app = App()281282 async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:283 response = await client.get(url, auth=None)284285 assert response.status_code == 200286 assert response.json() == {"auth": None}287288289def test_auth_hidden_url() -> None:290 url = "http://example-username:example-password@example.org/"291 expected = "URL('http://example-username:[secure]@example.org/')"292 assert url == URL(url)293 assert expected == repr(URL(url))294295296@pytest.mark.asyncio297async def test_auth_hidden_header() -> None:298 url = "https://example.org/"299 auth = ("example-username", "example-password")300 app = App()301302 async with httpx.AsyncClient(transport=MockTransport(app)) as client:303 response = await client.get(url, auth=auth)304305 assert "'authorization': '[secure]'" in str(response.request.headers)306307308@pytest.mark.asyncio309async def test_auth_property() -> None:310 app = App()311312 async with httpx.AsyncClient(transport=MockTransport(app)) as client:313 assert client.auth is None314315 client.auth = ("tomchristie", "password123") # type: ignore316 assert isinstance(client.auth, BasicAuth)317318 url = "https://example.org/"319 response = await client.get(url)320 assert response.status_code == 200321 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}322323324@pytest.mark.asyncio325async def test_auth_invalid_type() -> None:326 app = App()327328 with pytest.raises(TypeError):329 client = httpx.AsyncClient(330 transport=MockTransport(app),331 auth="not a tuple, not a callable", # type: ignore332 )333334 async with httpx.AsyncClient(transport=MockTransport(app)) as client:335 with pytest.raises(TypeError):336 await client.get(auth="not a tuple, not a callable") # type: ignore337338 with pytest.raises(TypeError):339 client.auth = "not a tuple, not a callable" # type: ignore340341342@pytest.mark.asyncio343async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:344 url = "https://example.org/"345 auth = DigestAuth(username="tomchristie", password="password123")346 app = App()347348 async with httpx.AsyncClient(transport=MockTransport(app)) as client:349 response = await client.get(url, auth=auth)350351 assert response.status_code == 200352 assert response.json() == {"auth": None}353 assert len(response.history) == 0354355356def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:357 url = "https://example.org/"358 auth = DigestAuth(username="tomchristie", password="password123")359 auth_header = "Token ..."360 app = App(auth_header=auth_header, status_code=401)361362 client = httpx.Client(transport=MockTransport(app))363 response = client.get(url, auth=auth)364365 assert response.status_code == 401366 assert response.json() == {"auth": None}367 assert len(response.history) == 0368369370@pytest.mark.asyncio371async def test_digest_auth_200_response_including_digest_auth_header() -> None:372 url = "https://example.org/"373 auth = DigestAuth(username="tomchristie", password="password123")374 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'375 app = App(auth_header=auth_header, status_code=200)376377 async with httpx.AsyncClient(transport=MockTransport(app)) as client:378 response = await client.get(url, auth=auth)379380 assert response.status_code == 200381 assert response.json() == {"auth": None}382 assert len(response.history) == 0383384385@pytest.mark.asyncio386async def test_digest_auth_401_response_without_digest_auth_header() -> None:387 url = "https://example.org/"388 auth = DigestAuth(username="tomchristie", password="password123")389 app = App(auth_header="", status_code=401)390391 async with httpx.AsyncClient(transport=MockTransport(app)) as client:392 response = await client.get(url, auth=auth)393394 assert response.status_code == 401395 assert response.json() == {"auth": None}396 assert len(response.history) == 0397398399@pytest.mark.parametrize(400 "algorithm,expected_hash_length,expected_response_length",401 [402 ("MD5", 64, 32),403 ("MD5-SESS", 64, 32),404 ("SHA", 64, 40),405 ("SHA-SESS", 64, 40),406 ("SHA-256", 64, 64),407 ("SHA-256-SESS", 64, 64),408 ("SHA-512", 64, 128),409 ("SHA-512-SESS", 64, 128),410 ],411)412@pytest.mark.asyncio413async def test_digest_auth(414 algorithm: str, expected_hash_length: int, expected_response_length: int415) -> None:416 url = "https://example.org/"417 auth = DigestAuth(username="tomchristie", password="password123")418 app = DigestApp(algorithm=algorithm)419420 async with httpx.AsyncClient(transport=MockTransport(app)) as client:421 response = await client.get(url, auth=auth)422423 assert response.status_code == 200424 assert len(response.history) == 1425426 authorization = typing.cast(dict, response.json())["auth"]427 scheme, _, fields = authorization.partition(" ")428 assert scheme == "Digest"429430 response_fields = [field.strip() for field in fields.split(",")]431 digest_data = dict(field.split("=") for field in response_fields)432433 assert digest_data["username"] == '"tomchristie"'434 assert digest_data["realm"] == '"httpx@example.org"'435 assert "nonce" in digest_data436 assert digest_data["uri"] == '"/"'437 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes438 assert len(digest_data["opaque"]) == expected_hash_length + 2439 assert digest_data["algorithm"] == algorithm440 assert digest_data["qop"] == "auth"441 assert digest_data["nc"] == "00000001"442 assert len(digest_data["cnonce"]) == 16 + 2443444445@pytest.mark.asyncio446async def test_digest_auth_no_specified_qop() -> None:447 url = "https://example.org/"448 auth = DigestAuth(username="tomchristie", password="password123")449 app = DigestApp(qop="")450451 async with httpx.AsyncClient(transport=MockTransport(app)) as client:452 response = await client.get(url, auth=auth)453454 assert response.status_code == 200455 assert len(response.history) == 1456457 authorization = typing.cast(dict, response.json())["auth"]458 scheme, _, fields = authorization.partition(" ")459 assert scheme == "Digest"460461 response_fields = [field.strip() for field in fields.split(",")]462 digest_data = dict(field.split("=") for field in response_fields)463464 assert "qop" not in digest_data465 assert "nc" not in digest_data466 assert "cnonce" not in digest_data467 assert digest_data["username"] == '"tomchristie"'468 assert digest_data["realm"] == '"httpx@example.org"'469 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes470 assert digest_data["uri"] == '"/"'471 assert len(digest_data["response"]) == 64 + 2472 assert len(digest_data["opaque"]) == 64 + 2473 assert digest_data["algorithm"] == "SHA-256"474475476@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))477@pytest.mark.asyncio478async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:479 url = "https://example.org/"480 auth = DigestAuth(username="tomchristie", password="password123")481 app = DigestApp(qop=qop)482483 async with httpx.AsyncClient(transport=MockTransport(app)) as client:484 response = await client.get(url, auth=auth)485486 assert response.status_code == 200487 assert len(response.history) == 1488489490@pytest.mark.asyncio491async def test_digest_auth_qop_auth_int_not_implemented() -> None:492 url = "https://example.org/"493 auth = DigestAuth(username="tomchristie", password="password123")494 app = DigestApp(qop="auth-int")495496 async with httpx.AsyncClient(transport=MockTransport(app)) as client:497 with pytest.raises(NotImplementedError):498 await client.get(url, auth=auth)499500501@pytest.mark.asyncio502async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:503 url = "https://example.org/"504 auth = DigestAuth(username="tomchristie", password="password123")505 app = DigestApp(qop="not-auth")506507 async with httpx.AsyncClient(transport=MockTransport(app)) as client:508 with pytest.raises(ProtocolError):509 await client.get(url, auth=auth)510511512@pytest.mark.asyncio513async def test_digest_auth_incorrect_credentials() -> None:514 url = "https://example.org/"515 auth = DigestAuth(username="tomchristie", password="password123")516 app = DigestApp(send_response_after_attempt=2)517518 async with httpx.AsyncClient(transport=MockTransport(app)) as client:519 response = await client.get(url, auth=auth)520521 assert response.status_code == 401522 assert len(response.history) == 1523524525@pytest.mark.parametrize(526 "auth_header",527 [528 'Digest realm="httpx@example.org", qop="auth"', # missing fields529 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list530 ],531)532@pytest.mark.asyncio533async def test_async_digest_auth_raises_protocol_error_on_malformed_header(534 auth_header: str,535) -> None:536 url = "https://example.org/"537 auth = DigestAuth(username="tomchristie", password="password123")538 app = App(auth_header=auth_header, status_code=401)539540 async with httpx.AsyncClient(transport=MockTransport(app)) as client:541 with pytest.raises(ProtocolError):542 await client.get(url, auth=auth)543544545@pytest.mark.parametrize(546 "auth_header",547 [548 'Digest realm="httpx@example.org", qop="auth"', # missing fields549 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list550 ],551)552def test_sync_digest_auth_raises_protocol_error_on_malformed_header(553 auth_header: str,554) -> None:555 url = "https://example.org/"556 auth = DigestAuth(username="tomchristie", password="password123")557 app = App(auth_header=auth_header, status_code=401)558559 with httpx.Client(transport=MockTransport(app)) as client:560 with pytest.raises(ProtocolError):561 client.get(url, auth=auth)562563564@pytest.mark.asyncio565async def test_async_auth_history() -> None:566 """567 Test that intermediate requests sent as part of an authentication flow568 are recorded in the response history.569 """570 url = "https://example.org/"571 auth = RepeatAuth(repeat=2)572 app = App(auth_header="abc")573574 async with httpx.AsyncClient(transport=MockTransport(app)) as client:575 response = await client.get(url, auth=auth)576577 assert response.status_code == 200578 assert response.json() == {"auth": "Repeat abc.abc"}579580 assert len(response.history) == 2581 resp1, resp2 = response.history582 assert resp1.json() == {"auth": "Repeat 0"}583 assert resp2.json() == {"auth": "Repeat 1"}584585 assert len(resp2.history) == 1586 assert resp2.history == [resp1]587588 assert len(resp1.history) == 0589590591def test_sync_auth_history() -> None:592 """593 Test that intermediate requests sent as part of an authentication flow594 are recorded in the response history.595 """596 url = "https://example.org/"597 auth = RepeatAuth(repeat=2)598 app = App(auth_header="abc")599600 with httpx.Client(transport=MockTransport(app)) as client:601 response = client.get(url, auth=auth)602603 assert response.status_code == 200604 assert response.json() == {"auth": "Repeat abc.abc"}605606 assert len(response.history) == 2607 resp1, resp2 = response.history608 assert resp1.json() == {"auth": "Repeat 0"}609 assert resp2.json() == {"auth": "Repeat 1"}610611 assert len(resp2.history) == 1612 assert resp2.history == [resp1]613614 assert len(resp1.history) == 0615616617@pytest.mark.asyncio618async def test_digest_auth_unavailable_streaming_body():619 url = "https://example.org/"620 auth = DigestAuth(username="tomchristie", password="password123")621 app = DigestApp()622623 async def streaming_body():624 yield b"Example request body" # pragma: nocover625626 async with httpx.AsyncClient(transport=MockTransport(app)) as client:627 with pytest.raises(httpx.StreamConsumed):628 await client.post(url, data=streaming_body(), auth=auth)629630631@pytest.mark.asyncio632async def test_async_auth_reads_response_body() -> None:633 """634 Test that we can read the response body in an auth flow if `requires_response_body`635 is set.636 """637 url = "https://example.org/"638 auth = ResponseBodyAuth("xyz")639 app = App()640641 async with httpx.AsyncClient(transport=MockTransport(app)) as client:642 response = await client.get(url, auth=auth)643644 assert response.status_code == 200645 assert response.json() == {"auth": '{"auth": "xyz"}'}646647648def test_sync_auth_reads_response_body() -> None:649 """650 Test that we can read the response body in an auth flow if `requires_response_body`651 is set.652 """653 url = "https://example.org/"654 auth = ResponseBodyAuth("xyz")655 app = App()656657 with httpx.Client(transport=MockTransport(app)) as client:658 response = client.get(url, auth=auth)659660 assert response.status_code == 200661 assert response.json() == {"auth": '{"auth": "xyz"}'}662663664@pytest.mark.asyncio665async def test_async_auth() -> None:666 """667 Test that we can use an auth implementation specific to the async case, to668 support cases that require performing I/O or using concurrency primitives (such669 as checking a disk-based cache or fetching a token from a remote auth server).670 """671 url = "https://example.org/"672 auth = SyncOrAsyncAuth()673 app = App()674675 async with httpx.AsyncClient(transport=MockTransport(app)) as client:676 response = await client.get(url, auth=auth)677678 assert response.status_code == 200679 assert response.json() == {"auth": "async-auth"}680681682def test_sync_auth() -> None:683 """684 Test that we can use an auth implementation specific to the sync case.685 """686 url = "https://example.org/"687 auth = SyncOrAsyncAuth()688 app = App()689690 with httpx.Client(transport=MockTransport(app)) as client:691 response = client.get(url, auth=auth)692693 assert response.status_code == 200694 assert response.json() == {"auth": "sync-auth"}