test_auth.py
This file
Path
tests/client/test_auth.py
367 lines · 11.5 KiB · Python
Last changed by
Drop sync (#544)Tom Christiebefore adoption206c537
History of this fileTake it
The walk stopped after 200 commits: lines older than f4f05e3 point at it.
Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 1why, one step back1import hashlibRead/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
line 2why, one step back2import jsonadded netrc support (#177)Can Sarıgölbefore adoption919e8d3
line 3why, one step back3import osRead/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
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,Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 9–10why, one step back9 CertTypes,10 Client,Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 11why, one step back11 DigestAuth,Drop sync (#544)Tom Christiebefore adoption206c537
line 12why, one step back12 Dispatcher,Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 13why, one step back13 ProtocolError,Drop sync (#544)Tom Christiebefore adoption206c537
lines 14–15why, one step back14 Request,15 Response,Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 16–20why, one step back16 TimeoutTypes,17 VerifyTypes,18)1920Drop sync (#544)Tom Christiebefore adoption206c537
line 21why, one step back21class MockDispatch(Dispatcher):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_code25Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 26–27why, one step back26 async def send(27 self,Drop sync (#544)Tom Christiebefore adoption206c537
line 28why, one step back28 request: Request,Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 29–31why, one step back29 verify: VerifyTypes = None,30 cert: CertTypes = None,31 timeout: TimeoutTypes = None,Drop sync (#544)Tom Christiebefore adoption206c537
line 32why, one step back32 ) -> Response:Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
line 33why, one step back33 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
line 34why, one step back34 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()Drop sync (#544)Tom Christiebefore adoption206c537
line 35why, one step back35 return Response(Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 36–37why, one step back36 self.status_code, headers=headers, content=body, request=request37 )Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 38–39why, one step back3839Drop sync (#544)Tom Christiebefore adoption206c537
line 40why, one step back40class MockDigestAuthDispatch(Dispatcher):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 41–55why, one step back41 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,Drop sync (#544)Tom Christiebefore adoption206c537
line 56why, one step back56 request: Request,Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 57–59why, one step back57 verify: VerifyTypes = None,58 cert: CertTypes = None,59 timeout: TimeoutTypes = None,Drop sync (#544)Tom Christiebefore adoption206c537
line 60why, one step back60 ) -> Response:Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 61–64why, one step back61 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()Drop sync (#544)Tom Christiebefore adoption206c537
line 65why, one step back65 return Response(200, content=body, request=request)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 66why, one step back66Drop sync (#544)Tom Christiebefore adoption206c537
line 67why, one step back67 def challenge_send(self, request: Request) -> Response:Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 68–91why, one step back68 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 ]Drop sync (#544)Tom Christiebefore adoption206c537
line 92why, one step back92 return Response(401, headers=headers, content=b"", request=request)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 93–94why, one step back9394Drop sync (#544)Tom Christiebefore adoption206c537
lines 95–96why, one step back95@pytest.mark.asyncio96async def test_basic_auth():Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 97–99why, one step back97 url = "https://example.org/"98 auth = ("tomchristie", "password123")99Drop sync (#544)Tom Christiebefore adoption206c537
lines 100–101why, one step back100 client = Client(dispatch=MockDispatch())101 response = await client.get(url, auth=auth)Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 102–106why, one step back102103 assert response.status_code == 200104 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}105106Drop sync (#544)Tom Christiebefore adoption206c537
lines 107–108why, one step back107@pytest.mark.asyncio108async def test_basic_auth_in_url():Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 109–110why, one step back109 url = "https://tomchristie:password123@example.org/"110Drop sync (#544)Tom Christiebefore adoption206c537
lines 111–112why, one step back111 client = Client(dispatch=MockDispatch())112 response = await client.get(url)Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 113–117why, one step back113114 assert response.status_code == 200115 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}116117Drop sync (#544)Tom Christiebefore adoption206c537
lines 118–119why, one step back118@pytest.mark.asyncio119async def test_basic_auth_on_session():Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 120–122why, one step back120 url = "https://example.org/"121 auth = ("tomchristie", "password123")122Drop sync (#544)Tom Christiebefore adoption206c537
lines 123–124why, one step back123 client = Client(dispatch=MockDispatch(), auth=auth)124 response = await client.get(url)Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 125–129why, one step back125126 assert response.status_code == 200127 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}128129Drop sync (#544)Tom Christiebefore adoption206c537
lines 130–131why, one step back130@pytest.mark.asyncio131async def test_custom_auth():Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 132–137why, one step back132 url = "https://example.org/"133134 def auth(request):135 request.headers["Authorization"] = "Token 123"136 return request137Drop sync (#544)Tom Christiebefore adoption206c537
lines 138–139why, one step back138 client = Client(dispatch=MockDispatch())139 response = await client.get(url, auth=auth)Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
lines 140–142why, one step back140141 assert response.status_code == 200142 assert response.json() == {"auth": "Token 123"}added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 143–144why, one step back143144Drop sync (#544)Tom Christiebefore adoption206c537
lines 145–146why, one step back145@pytest.mark.asyncio146async def test_netrc_auth():added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 147–149why, one step back147 os.environ["NETRC"] = "tests/.netrc"148 url = "http://netrcexample.org"149Drop sync (#544)Tom Christiebefore adoption206c537
lines 150–151why, one step back150 client = Client(dispatch=MockDispatch())151 response = await client.get(url)added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 152–158why, one step back152153 assert response.status_code == 200154 assert response.json() == {155 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"156 }157158Drop sync (#544)Tom Christiebefore adoption206c537
lines 159–160why, one step back159@pytest.mark.asyncio160async def test_trust_env_auth():added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 161–163why, one step back161 os.environ["NETRC"] = "tests/.netrc"162 url = "http://netrcexample.org"163Drop sync (#544)Tom Christiebefore adoption206c537
lines 164–165why, one step back164 client = Client(dispatch=MockDispatch())165 response = await client.get(url, trust_env=False)added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 166–168why, one step back166167 assert response.status_code == 200168 assert response.json() == {"auth": None}Add trust_env property to BaseClient (#187)Can Sarıgölbefore adoption04d5ffb
line 169why, one step back169Drop sync (#544)Tom Christiebefore adoption206c537
lines 170–171why, one step back170 client = Client(dispatch=MockDispatch(), trust_env=False)171 response = await client.get(url, trust_env=True)Add trust_env property to BaseClient (#187)Can Sarıgölbefore adoption04d5ffb
lines 172–176why, one step back172173 assert response.status_code == 200174 assert response.json() == {175 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"176 }fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
lines 177–185why, one step back177178179def test_auth_hidden_url():180 url = "http://example-username:example-password@example.org/"181 expected = "URL('http://example-username:[secure]@example.org/')"182 assert url == URL(url)183 assert expected == repr(URL(url))184185Drop sync (#544)Tom Christiebefore adoption206c537
lines 186–187why, one step back186@pytest.mark.asyncio187async def test_auth_hidden_header():fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
lines 188–190why, one step back188 url = "https://example.org/"189 auth = ("example-username", "example-password")190Drop sync (#544)Tom Christiebefore adoption206c537
lines 191–192why, one step back191 client = Client(dispatch=MockDispatch())192 response = await client.get(url, auth=auth)fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
lines 193–194why, one step back193194 assert "'authorization': '[secure]'" in str(response.request.headers)Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
lines 195–196why, one step back195196Drop sync (#544)Tom Christiebefore adoption206c537
lines 197–198why, one step back197@pytest.mark.asyncio198async def test_auth_invalid_type():Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
line 199why, one step back199 url = "https://example.org/"Drop sync (#544)Tom Christiebefore adoption206c537
lines 200–202why, one step back200 client = Client(dispatch=MockDispatch(), auth="not a tuple, not a callable")201 with pytest.raises(TypeError):202 await client.get(url)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 203–204why, one step back203204Drop sync (#544)Tom Christiebefore adoption206c537
lines 205–206why, one step back205@pytest.mark.asyncio206async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 207–209why, one step back207 url = "https://example.org/"208 auth = DigestAuth(username="tomchristie", password="password123")209Drop sync (#544)Tom Christiebefore adoption206c537
lines 210–211why, one step back210 client = Client(dispatch=MockDispatch())211 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 212–216why, one step back212213 assert response.status_code == 200214 assert response.json() == {"auth": None}215216Drop sync (#544)Tom Christiebefore adoption206c537
lines 217–218why, one step back217@pytest.mark.asyncio218async def test_digest_auth_200_response_including_digest_auth_header():Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 219–222why, one step back219 url = "https://example.org/"220 auth = DigestAuth(username="tomchristie", password="password123")221 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'222Drop sync (#544)Tom Christiebefore adoption206c537
lines 223–224why, one step back223 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))224 response = await client.get(url, auth=auth)Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 225–229why, one step back225226 assert response.status_code == 200227 assert response.json() == {"auth": None}228229Drop sync (#544)Tom Christiebefore adoption206c537
lines 230–231why, one step back230@pytest.mark.asyncio231async def test_digest_auth_401_response_without_digest_auth_header():Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 232–234why, one step back232 url = "https://example.org/"233 auth = DigestAuth(username="tomchristie", password="password123")234Drop sync (#544)Tom Christiebefore adoption206c537
lines 235–236why, one step back235 client = Client(dispatch=MockDispatch(auth_header="", status_code=401))236 response = await client.get(url, auth=auth)Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 237–241why, one step back237238 assert response.status_code == 401239 assert response.json() == {"auth": None}240241Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 242–254why, one step back242@pytest.mark.parametrize(243 "algorithm,expected_hash_length,expected_response_length",244 [245 ("MD5", 64, 32),246 ("MD5-SESS", 64, 32),247 ("SHA", 64, 40),248 ("SHA-SESS", 64, 40),249 ("SHA-256", 64, 64),250 ("SHA-256-SESS", 64, 64),251 ("SHA-512", 64, 128),252 ("SHA-512-SESS", 64, 128),253 ],254)Drop sync (#544)Tom Christiebefore adoption206c537
lines 255–256why, one step back255@pytest.mark.asyncio256async def test_digest_auth(algorithm, expected_hash_length, expected_response_length):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 257–259why, one step back257 url = "https://example.org/"258 auth = DigestAuth(username="tomchristie", password="password123")259Drop sync (#544)Tom Christiebefore adoption206c537
lines 260–261why, one step back260 client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))261 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 262–281why, one step back262263 assert response.status_code == 200264 auth = response.json()["auth"]265 assert auth.startswith("Digest ")266267 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]268 digest_data = dict(field.split("=") for field in response_fields)269270 assert digest_data["username"] == '"tomchristie"'271 assert digest_data["realm"] == '"httpx@example.org"'272 assert "nonce" in digest_data273 assert digest_data["uri"] == '"/"'274 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes275 assert len(digest_data["opaque"]) == expected_hash_length + 2276 assert digest_data["algorithm"] == algorithm277 assert digest_data["qop"] == "auth"278 assert digest_data["nc"] == "00000001"279 assert len(digest_data["cnonce"]) == 16 + 2280281Drop sync (#544)Tom Christiebefore adoption206c537
lines 282–283why, one step back282@pytest.mark.asyncio283async def test_digest_auth_no_specified_qop():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 284–286why, one step back284 url = "https://example.org/"285 auth = DigestAuth(username="tomchristie", password="password123")286Drop sync (#544)Tom Christiebefore adoption206c537
lines 287–288why, one step back287 client = Client(dispatch=MockDigestAuthDispatch(qop=None))288 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 289–308why, one step back289290 assert response.status_code == 200291 auth = response.json()["auth"]292 assert auth.startswith("Digest ")293294 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]295 digest_data = dict(field.split("=") for field in response_fields)296297 assert "qop" not in digest_data298 assert "nc" not in digest_data299 assert "cnonce" not in digest_data300 assert digest_data["username"] == '"tomchristie"'301 assert digest_data["realm"] == '"httpx@example.org"'302 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes303 assert digest_data["uri"] == '"/"'304 assert len(digest_data["response"]) == 64 + 2305 assert len(digest_data["opaque"]) == 64 + 2306 assert digest_data["algorithm"] == "SHA-256"307308Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
line 309why, one step back309@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))Drop sync (#544)Tom Christiebefore adoption206c537
lines 310–311why, one step back310@pytest.mark.asyncio311async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 312–314why, one step back312 url = "https://example.org/"313 auth = DigestAuth(username="tomchristie", password="password123")314Drop sync (#544)Tom Christiebefore adoption206c537
lines 315–316why, one step back315 client = Client(dispatch=MockDigestAuthDispatch(qop=qop))316 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 317–318why, one step back317318Drop sync (#544)Tom Christiebefore adoption206c537
lines 319–320why, one step back319@pytest.mark.asyncio320async def test_digest_auth_qop_auth_int_not_implemented():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 321–322why, one step back321 url = "https://example.org/"322 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 323why, one step back323 client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 324–325why, one step back324325 with pytest.raises(NotImplementedError):Drop sync (#544)Tom Christiebefore adoption206c537
line 326why, one step back326 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 327–328why, one step back327328Drop sync (#544)Tom Christiebefore adoption206c537
lines 329–330why, one step back329@pytest.mark.asyncio330async def test_digest_auth_qop_must_be_auth_or_auth_int():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 331–332why, one step back331 url = "https://example.org/"332 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 333why, one step back333 client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 334–335why, one step back334335 with pytest.raises(ProtocolError):Drop sync (#544)Tom Christiebefore adoption206c537
line 336why, one step back336 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 337–338why, one step back337338Drop sync (#544)Tom Christiebefore adoption206c537
lines 339–340why, one step back339@pytest.mark.asyncio340async def test_digest_auth_incorrect_credentials():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 341–343why, one step back341 url = "https://example.org/"342 auth = DigestAuth(username="tomchristie", password="password123")343Drop sync (#544)Tom Christiebefore adoption206c537
lines 344–345why, one step back344 client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))345 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 346–359why, one step back346347 assert response.status_code == 401348349350@pytest.mark.parametrize(351 "auth_header",352 [353 'Digest realm="httpx@example.org", qop="auth"', # missing fields354 'realm="httpx@example.org", qop="auth"', # not starting with Digest355 'DigestZ realm="httpx@example.org", qop="auth"'356 'qop="auth,auth-int",nonce="abc",opaque="xyz"',357 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list358 ],359)Drop sync (#544)Tom Christiebefore adoption206c537
lines 360–361why, one step back360@pytest.mark.asyncio361async def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 362–363why, one step back362 url = "https://example.org/"363 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 364why, one step back364 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 365–366why, one step back365366 with pytest.raises(ProtocolError):Drop sync (#544)Tom Christiebefore adoption206c537
line 367why, one step back367 await client.get(url, auth=auth)