test_auth.py
This file
Path
tests/client/test_auth.py
379 lines · 11.9 KiB · Python
Last changed by
Ensure Authorization header has priority over .netrcTom Christiebefore adoption43331cf
History of this fileTake it
The walk stopped after 200 commits: lines older than edd7029 point at it.
Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 1why, one step back1import hashlibUpdate README.mdTom Christiebefore adoptionedd7029
line 2why, one step back2import jsonadded netrc support (#177)Can Sarıgölbefore adoption919e8d3
line 3why, one step back3import osUpdate README.mdTom Christiebefore adoptionedd7029
line 4why, one step back4Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
lines 5–6why, one step back5import pytest6Update README.mdTom Christiebefore adoptionedd7029
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,Update README.mdTom Christiebefore adoptionedd7029
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,Update README.mdTom Christiebefore adoptionedd7029
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_code25Update README.mdTom Christiebefore adoptionedd7029
lines 26–27why, one step back26 async def send(27 self,Drop sync (#544)Tom Christiebefore adoption206c537
line 28why, one step back28 request: Request,Update README.mdTom Christiebefore adoptionedd7029
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 []Update README.mdTom Christiebefore adoptionedd7029
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 )Update README.mdTom Christiebefore adoptionedd7029
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():Update README.mdTom Christiebefore adoptionedd7029
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)Update README.mdTom Christiebefore adoptionedd7029
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():Update README.mdTom Christiebefore adoptionedd7029
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)Update README.mdTom Christiebefore adoptionedd7029
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():Update README.mdTom Christiebefore adoptionedd7029
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)Update README.mdTom Christiebefore adoptionedd7029
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():Update README.mdTom Christiebefore adoptionedd7029
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)Update README.mdTom Christiebefore adoptionedd7029
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
line 159why, one step back159@pytest.mark.asyncioEnsure Authorization header has priority over .netrcTom Christiebefore adoption43331cf
lines 160–171why, one step back160async def test_auth_header_has_priority_over_netrc():161 os.environ["NETRC"] = "tests/.netrc"162 url = "http://netrcexample.org"163164 client = Client(dispatch=MockDispatch())165 response = await client.get(url, headers={"Authorization": "Override"})166167 assert response.status_code == 200168 assert response.json() == {"auth": "Override"}169170171@pytest.mark.asyncioDrop sync (#544)Tom Christiebefore adoption206c537
line 172why, one step back172async def test_trust_env_auth():added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 173–175why, one step back173 os.environ["NETRC"] = "tests/.netrc"174 url = "http://netrcexample.org"175Drop sync (#544)Tom Christiebefore adoption206c537
lines 176–177why, one step back176 client = Client(dispatch=MockDispatch())177 response = await client.get(url, trust_env=False)added netrc support (#177)Can Sarıgölbefore adoption919e8d3
lines 178–180why, one step back178179 assert response.status_code == 200180 assert response.json() == {"auth": None}Add trust_env property to BaseClient (#187)Can Sarıgölbefore adoption04d5ffb
line 181why, one step back181Drop sync (#544)Tom Christiebefore adoption206c537
lines 182–183why, one step back182 client = Client(dispatch=MockDispatch(), trust_env=False)183 response = await client.get(url, trust_env=True)Add trust_env property to BaseClient (#187)Can Sarıgölbefore adoption04d5ffb
lines 184–188why, one step back184185 assert response.status_code == 200186 assert response.json() == {187 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"188 }fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
lines 189–197why, one step back189190191def test_auth_hidden_url():192 url = "http://example-username:example-password@example.org/"193 expected = "URL('http://example-username:[secure]@example.org/')"194 assert url == URL(url)195 assert expected == repr(URL(url))196197Drop sync (#544)Tom Christiebefore adoption206c537
lines 198–199why, one step back198@pytest.mark.asyncio199async def test_auth_hidden_header():fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
lines 200–202why, one step back200 url = "https://example.org/"201 auth = ("example-username", "example-password")202Drop sync (#544)Tom Christiebefore adoption206c537
lines 203–204why, one step back203 client = Client(dispatch=MockDispatch())204 response = await client.get(url, auth=auth)fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d
lines 205–206why, one step back205206 assert "'authorization': '[secure]'" in str(response.request.headers)Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
lines 207–208why, one step back207208Drop sync (#544)Tom Christiebefore adoption206c537
lines 209–210why, one step back209@pytest.mark.asyncio210async def test_auth_invalid_type():Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
line 211why, one step back211 url = "https://example.org/"Drop sync (#544)Tom Christiebefore adoption206c537
lines 212–214why, one step back212 client = Client(dispatch=MockDispatch(), auth="not a tuple, not a callable")213 with pytest.raises(TypeError):214 await client.get(url)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 215–216why, one step back215216Drop sync (#544)Tom Christiebefore adoption206c537
lines 217–218why, one step back217@pytest.mark.asyncio218async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 219–221why, one step back219 url = "https://example.org/"220 auth = DigestAuth(username="tomchristie", password="password123")221Drop sync (#544)Tom Christiebefore adoption206c537
lines 222–223why, one step back222 client = Client(dispatch=MockDispatch())223 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 224–228why, one step back224225 assert response.status_code == 200226 assert response.json() == {"auth": None}227228Drop sync (#544)Tom Christiebefore adoption206c537
lines 229–230why, one step back229@pytest.mark.asyncio230async def test_digest_auth_200_response_including_digest_auth_header():Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 231–234why, one step back231 url = "https://example.org/"232 auth = DigestAuth(username="tomchristie", password="password123")233 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'234Drop sync (#544)Tom Christiebefore adoption206c537
lines 235–236why, one step back235 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))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 == 200239 assert response.json() == {"auth": None}240241Drop sync (#544)Tom Christiebefore adoption206c537
lines 242–243why, one step back242@pytest.mark.asyncio243async def test_digest_auth_401_response_without_digest_auth_header():Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 244–246why, one step back244 url = "https://example.org/"245 auth = DigestAuth(username="tomchristie", password="password123")246Drop sync (#544)Tom Christiebefore adoption206c537
lines 247–248why, one step back247 client = Client(dispatch=MockDispatch(auth_header="", status_code=401))248 response = await client.get(url, auth=auth)Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 249–253why, one step back249250 assert response.status_code == 401251 assert response.json() == {"auth": None}252253Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 254–266why, one step back254@pytest.mark.parametrize(255 "algorithm,expected_hash_length,expected_response_length",256 [257 ("MD5", 64, 32),258 ("MD5-SESS", 64, 32),259 ("SHA", 64, 40),260 ("SHA-SESS", 64, 40),261 ("SHA-256", 64, 64),262 ("SHA-256-SESS", 64, 64),263 ("SHA-512", 64, 128),264 ("SHA-512-SESS", 64, 128),265 ],266)Drop sync (#544)Tom Christiebefore adoption206c537
lines 267–268why, one step back267@pytest.mark.asyncio268async def test_digest_auth(algorithm, expected_hash_length, expected_response_length):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 269–271why, one step back269 url = "https://example.org/"270 auth = DigestAuth(username="tomchristie", password="password123")271Drop sync (#544)Tom Christiebefore adoption206c537
lines 272–273why, one step back272 client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))273 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 274–293why, one step back274275 assert response.status_code == 200276 auth = response.json()["auth"]277 assert auth.startswith("Digest ")278279 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]280 digest_data = dict(field.split("=") for field in response_fields)281282 assert digest_data["username"] == '"tomchristie"'283 assert digest_data["realm"] == '"httpx@example.org"'284 assert "nonce" in digest_data285 assert digest_data["uri"] == '"/"'286 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes287 assert len(digest_data["opaque"]) == expected_hash_length + 2288 assert digest_data["algorithm"] == algorithm289 assert digest_data["qop"] == "auth"290 assert digest_data["nc"] == "00000001"291 assert len(digest_data["cnonce"]) == 16 + 2292293Drop sync (#544)Tom Christiebefore adoption206c537
lines 294–295why, one step back294@pytest.mark.asyncio295async def test_digest_auth_no_specified_qop():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 296–298why, one step back296 url = "https://example.org/"297 auth = DigestAuth(username="tomchristie", password="password123")298Drop sync (#544)Tom Christiebefore adoption206c537
lines 299–300why, one step back299 client = Client(dispatch=MockDigestAuthDispatch(qop=None))300 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 301–320why, one step back301302 assert response.status_code == 200303 auth = response.json()["auth"]304 assert auth.startswith("Digest ")305306 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]307 digest_data = dict(field.split("=") for field in response_fields)308309 assert "qop" not in digest_data310 assert "nc" not in digest_data311 assert "cnonce" not in digest_data312 assert digest_data["username"] == '"tomchristie"'313 assert digest_data["realm"] == '"httpx@example.org"'314 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes315 assert digest_data["uri"] == '"/"'316 assert len(digest_data["response"]) == 64 + 2317 assert len(digest_data["opaque"]) == 64 + 2318 assert digest_data["algorithm"] == "SHA-256"319320Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
line 321why, one step back321@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))Drop sync (#544)Tom Christiebefore adoption206c537
lines 322–323why, one step back322@pytest.mark.asyncio323async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 324–326why, one step back324 url = "https://example.org/"325 auth = DigestAuth(username="tomchristie", password="password123")326Drop sync (#544)Tom Christiebefore adoption206c537
lines 327–328why, one step back327 client = Client(dispatch=MockDigestAuthDispatch(qop=qop))328 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 329–330why, one step back329330Drop sync (#544)Tom Christiebefore adoption206c537
lines 331–332why, one step back331@pytest.mark.asyncio332async def test_digest_auth_qop_auth_int_not_implemented():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 333–334why, one step back333 url = "https://example.org/"334 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 335why, one step back335 client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 336–337why, one step back336337 with pytest.raises(NotImplementedError):Drop sync (#544)Tom Christiebefore adoption206c537
line 338why, one step back338 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 339–340why, one step back339340Drop sync (#544)Tom Christiebefore adoption206c537
lines 341–342why, one step back341@pytest.mark.asyncio342async def test_digest_auth_qop_must_be_auth_or_auth_int():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 343–344why, one step back343 url = "https://example.org/"344 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 345why, one step back345 client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 346–347why, one step back346347 with pytest.raises(ProtocolError):Drop sync (#544)Tom Christiebefore adoption206c537
line 348why, one step back348 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 349–350why, one step back349350Drop sync (#544)Tom Christiebefore adoption206c537
lines 351–352why, one step back351@pytest.mark.asyncio352async def test_digest_auth_incorrect_credentials():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 353–355why, one step back353 url = "https://example.org/"354 auth = DigestAuth(username="tomchristie", password="password123")355Drop sync (#544)Tom Christiebefore adoption206c537
lines 356–357why, one step back356 client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))357 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 358–371why, one step back358359 assert response.status_code == 401360361362@pytest.mark.parametrize(363 "auth_header",364 [365 'Digest realm="httpx@example.org", qop="auth"', # missing fields366 'realm="httpx@example.org", qop="auth"', # not starting with Digest367 'DigestZ realm="httpx@example.org", qop="auth"'368 'qop="auth,auth-int",nonce="abc",opaque="xyz"',369 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list370 ],371)Drop sync (#544)Tom Christiebefore adoption206c537
lines 372–373why, one step back372@pytest.mark.asyncio373async def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 374–375why, one step back374 url = "https://example.org/"375 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 376why, one step back376 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 377–378why, one step back377378 with pytest.raises(ProtocolError):Drop sync (#544)Tom Christiebefore adoption206c537
line 379why, one step back379 await client.get(url, auth=auth)