test_auth.py
This file
Path
tests/client/test_auth.py
358 lines · 11.4 KiB · Python
Last changed by
Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
History of this fileTake it
Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 1why, one step back1import hashlibAuth (#65)Tom Christiebefore adoption5afa7dd
line 2why, one step back2import jsonadded netrc support (#177)Can Sarıgölbefore adoption919e8d3
line 3why, one step back3import osAuth (#65)Tom Christiebefore adoption5afa7dd
line 4why, one step back4Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
lines 5–6why, one step back5import pytest6Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b
line 7why, one step back7from httpx import (fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
line 8why, one step back8 URL,Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
lines 9–11why, one step back9 AsyncDispatcher,10 AsyncRequest,11 AsyncResponse,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
line 12why, one step back12 CertTypes,Auth (#65)Tom Christiebefore adoption5afa7dd
line 13why, one step back13 Client,Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 14–15why, one step back14 DigestAuth,15 ProtocolError,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
lines 16–17why, one step back16 TimeoutTypes,17 VerifyTypes,Auth (#65)Tom Christiebefore adoption5afa7dd
lines 18–20why, one step back18)1920Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 21why, one step back21class MockDispatch(AsyncDispatcher):Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 22–25why, one step back22 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:23 self.auth_header = auth_header24 self.status_code = status_code25Auth (#65)Tom Christiebefore adoption5afa7dd
lines 26–27why, one step back26 async def send(27 self,Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 28why, one step back28 request: AsyncRequest,Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041
lines 29–31why, one step back29 verify: VerifyTypes = None,30 cert: CertTypes = None,31 timeout: TimeoutTypes = None,Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7
line 32why, one step back32 ) -> AsyncResponse:Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
line 33why, one step back33 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 34why, one step back34 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 35–37why, one step back35 return AsyncResponse(36 self.status_code, headers=headers, content=body, request=request37 )Auth (#65)Tom Christiebefore adoption5afa7dd
lines 38–39why, one step back3839Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 40–97why, one step back40class MockDigestAuthDispatch(AsyncDispatcher):41 def __init__(42 self,43 algorithm: str = "SHA-256",44 send_response_after_attempt: int = 1,45 qop: str = "auth",46 regenerate_nonce: bool = True,47 ) -> None:48 self.algorithm = algorithm49 self.send_response_after_attempt = send_response_after_attempt50 self.qop = qop51 self._regenerate_nonce = regenerate_nonce52 self._response_count = 05354 async def send(55 self,56 request: AsyncRequest,57 verify: VerifyTypes = None,58 cert: CertTypes = None,59 timeout: TimeoutTypes = None,60 ) -> AsyncResponse:61 if self._response_count < self.send_response_after_attempt:62 return self.challenge_send(request)6364 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()65 return AsyncResponse(200, content=body, request=request)6667 def challenge_send(self, request: AsyncRequest) -> AsyncResponse:68 self._response_count += 169 nonce = (70 hashlib.sha256(os.urandom(8)).hexdigest()71 if self._regenerate_nonce72 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"73 )74 challenge_data = {75 "nonce": nonce,76 "qop": self.qop,77 "opaque": (78 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"79 ),80 "algorithm": self.algorithm,81 "stale": "FALSE",82 }83 challenge_str = ", ".join(84 '{}="{}"'.format(key, value)85 for key, value in challenge_data.items()86 if value87 )8889 headers = [90 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)91 ]92 return AsyncResponse(401, headers=headers, content=b"", request=request)9394 def reset(self) -> None:95 self._response_count = 09697Auth (#65)Tom Christiebefore adoption5afa7dd
lines 98–99why, one step back98def test_basic_auth():99 url = "https://example.org/"Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 100why, one step back100 auth = ("tomchristie", "password123")Auth (#65)Tom Christiebefore adoption5afa7dd
lines 101–105why, one step back101102 with Client(dispatch=MockDispatch()) as client:103 response = client.get(url, auth=auth)104105 assert response.status_code == 200Add response.json()Tom Christiebefore adoption2116d44
line 106why, one step back106 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}Auth (#65)Tom Christiebefore adoption5afa7dd
lines 107–115why, one step back107108109def test_basic_auth_in_url():110 url = "https://tomchristie:password123@example.org/"111112 with Client(dispatch=MockDispatch()) as client:113 response = client.get(url)114115 assert response.status_code == 200Add response.json()Tom Christiebefore adoption2116d44
line 116why, one step back116 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}Auth (#65)Tom Christiebefore adoption5afa7dd
lines 117–120why, one step back117118119def test_basic_auth_on_session():120 url = "https://example.org/"Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 121why, one step back121 auth = ("tomchristie", "password123")Auth (#65)Tom Christiebefore adoption5afa7dd
lines 122–126why, one step back122123 with Client(dispatch=MockDispatch(), auth=auth) as client:124 response = client.get(url)125126 assert response.status_code == 200Add response.json()Tom Christiebefore adoption2116d44
line 127why, one step back127 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}Auth (#65)Tom Christiebefore adoption5afa7dd
lines 128–133why, one step back128129130def test_custom_auth():131 url = "https://example.org/"132133 def auth(request):Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 134why, one step back134 request.headers["Authorization"] = "Token 123"Auth (#65)Tom Christiebefore adoption5afa7dd
lines 135–140why, one step back135 return request136137 with Client(dispatch=MockDispatch()) as client:138 response = client.get(url, auth=auth)139140 assert response.status_code == 200Add response.json()Tom Christiebefore adoption2116d44
line 141why, one step back141 assert response.json() == {"auth": "Token 123"}added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 142–165why, one step back142143144def test_netrc_auth():145 os.environ["NETRC"] = "tests/.netrc"146 url = "http://netrcexample.org"147148 with Client(dispatch=MockDispatch()) as client:149 response = client.get(url)150151 assert response.status_code == 200152 assert response.json() == {153 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"154 }155156157def test_trust_env_auth():158 os.environ["NETRC"] = "tests/.netrc"159 url = "http://netrcexample.org"160161 with Client(dispatch=MockDispatch()) as client:162 response = client.get(url, trust_env=False)163164 assert response.status_code == 200165 assert response.json() == {"auth": None}Add trust_env property to BaseClient (#187)Can Sarıgölbefore adoption04d5ffb
lines 166–173why, one step back166167 with Client(dispatch=MockDispatch(), trust_env=False) as client:168 response = client.get(url, trust_env=True)169170 assert response.status_code == 200171 assert response.json() == {172 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"173 }fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
lines 174–190why, one step back174175176def test_auth_hidden_url():177 url = "http://example-username:example-password@example.org/"178 expected = "URL('http://example-username:[secure]@example.org/')"179 assert url == URL(url)180 assert expected == repr(URL(url))181182183def test_auth_hidden_header():184 url = "https://example.org/"185 auth = ("example-username", "example-password")186187 with Client(dispatch=MockDispatch()) as client:188 response = client.get(url, auth=auth)189190 assert "'authorization': '[secure]'" in str(response.request.headers)Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
lines 191–197why, one step back191192193def test_auth_invalid_type():194 url = "https://example.org/"195 with Client(dispatch=MockDispatch(), auth="not a tuple, not a callable") as client:196 with pytest.raises(TypeError):197 client.get(url)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 198–210why, one step back198199200def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():201 url = "https://example.org/"202 auth = DigestAuth(username="tomchristie", password="password123")203204 with Client(dispatch=MockDispatch()) as client:205 response = client.get(url, auth=auth)206207 assert response.status_code == 200208 assert response.json() == {"auth": None}209210Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 211–235why, one step back211def test_digest_auth_200_response_including_digest_auth_header_is_returned_as_is():212 url = "https://example.org/"213 auth = DigestAuth(username="tomchristie", password="password123")214 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'215216 with Client(217 dispatch=MockDispatch(auth_header=auth_header, status_code=200)218 ) as client:219 response = client.get(url, auth=auth)220221 assert response.status_code == 200222 assert response.json() == {"auth": None}223224225def test_digest_auth_401_response_without_digest_auth_header_is_returned_as_is():226 url = "https://example.org/"227 auth = DigestAuth(username="tomchristie", password="password123")228229 with Client(dispatch=MockDispatch(auth_header="", status_code=401)) as client:230 response = client.get(url, auth=auth)231232 assert response.status_code == 401233 assert response.json() == {"auth": None}234235Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 236–300why, one step back236@pytest.mark.parametrize(237 "algorithm,expected_hash_length,expected_response_length",238 [239 ("MD5", 64, 32),240 ("MD5-SESS", 64, 32),241 ("SHA", 64, 40),242 ("SHA-SESS", 64, 40),243 ("SHA-256", 64, 64),244 ("SHA-256-SESS", 64, 64),245 ("SHA-512", 64, 128),246 ("SHA-512-SESS", 64, 128),247 ],248)249def test_digest_auth(algorithm, expected_hash_length, expected_response_length):250 url = "https://example.org/"251 auth = DigestAuth(username="tomchristie", password="password123")252253 with Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm)) as client:254 response = client.get(url, auth=auth)255256 assert response.status_code == 200257 auth = response.json()["auth"]258 assert auth.startswith("Digest ")259260 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]261 digest_data = dict(field.split("=") for field in response_fields)262263 assert digest_data["username"] == '"tomchristie"'264 assert digest_data["realm"] == '"httpx@example.org"'265 assert "nonce" in digest_data266 assert digest_data["uri"] == '"/"'267 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes268 assert len(digest_data["opaque"]) == expected_hash_length + 2269 assert digest_data["algorithm"] == algorithm270 assert digest_data["qop"] == "auth"271 assert digest_data["nc"] == "00000001"272 assert len(digest_data["cnonce"]) == 16 + 2273274275def test_digest_auth_no_specified_qop():276 url = "https://example.org/"277 auth = DigestAuth(username="tomchristie", password="password123")278279 with Client(dispatch=MockDigestAuthDispatch(qop=None)) as client:280 response = client.get(url, auth=auth)281282 assert response.status_code == 200283 auth = response.json()["auth"]284 assert auth.startswith("Digest ")285286 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]287 digest_data = dict(field.split("=") for field in response_fields)288289 assert "qop" not in digest_data290 assert "nc" not in digest_data291 assert "cnonce" not in digest_data292 assert digest_data["username"] == '"tomchristie"'293 assert digest_data["realm"] == '"httpx@example.org"'294 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes295 assert digest_data["uri"] == '"/"'296 assert len(digest_data["response"]) == 64 + 2297 assert len(digest_data["opaque"]) == 64 + 2298 assert digest_data["algorithm"] == "SHA-256"299300Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 301–302why, one step back301@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))302def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 303–305why, one step back303 url = "https://example.org/"304 auth = DigestAuth(username="tomchristie", password="password123")305Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
line 306why, one step back306 with Client(dispatch=MockDigestAuthDispatch(qop=qop)) as client:Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 307–354why, one step back307 client.get(url, auth=auth)308309310def test_digest_auth_qop_auth_int_not_implemented():311 url = "https://example.org/"312 auth = DigestAuth(username="tomchristie", password="password123")313314 with pytest.raises(NotImplementedError):315 with Client(dispatch=MockDigestAuthDispatch(qop="auth-int")) as client:316 client.get(url, auth=auth)317318319def test_digest_auth_qop_must_be_auth_or_auth_int():320 url = "https://example.org/"321 auth = DigestAuth(username="tomchristie", password="password123")322323 with pytest.raises(ProtocolError):324 with Client(dispatch=MockDigestAuthDispatch(qop="not-auth")) as client:325 client.get(url, auth=auth)326327328def test_digest_auth_incorrect_credentials():329 url = "https://example.org/"330 auth = DigestAuth(username="tomchristie", password="password123")331332 with Client(333 dispatch=MockDigestAuthDispatch(send_response_after_attempt=2)334 ) as client:335 response = client.get(url, auth=auth)336337 assert response.status_code == 401338339340@pytest.mark.parametrize(341 "auth_header",342 [343 'Digest realm="httpx@example.org", qop="auth"', # missing fields344 'realm="httpx@example.org", qop="auth"', # not starting with Digest345 'DigestZ realm="httpx@example.org", qop="auth"'346 'qop="auth,auth-int",nonce="abc",opaque="xyz"',347 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list348 ],349)350def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):351 url = "https://example.org/"352 auth = DigestAuth(username="tomchristie", password="password123")353354 with pytest.raises(ProtocolError):Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 355–357why, one step back355 with Client(356 dispatch=MockDispatch(auth_header=auth_header, status_code=401)357 ) as client:Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 358why, one step back358 client.get(url, auth=auth)