test_auth.py
This file
Path
tests/client/test_auth.py
370 lines · 11.9 KiB · Python
Last changed by
No I/O auth (#644)Tom Christiebefore adoption6c69e09
History of this fileTake it
The walk stopped after 200 commits: lines older than 1872ae8 point at it.
Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 1why, one step back1import hashlibAdd ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 2–4why, one step back2import json3import os4Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
lines 5–6why, one step back5import pytest6Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
lines 7–9why, one step back7from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response8from httpx.config import CertTypes, TimeoutTypes, VerifyTypes9from httpx.dispatch.base import DispatcherAdd ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 10–11why, one step back1011Drop sync (#544)Tom Christiebefore adoption206c537
line 12why, one step back12class MockDispatch(Dispatcher):Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 13–16why, one step back13 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:14 self.auth_header = auth_header15 self.status_code = status_code16Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 17–18why, one step back17 async def send(18 self,Drop sync (#544)Tom Christiebefore adoption206c537
line 19why, one step back19 request: Request,Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 20–22why, one step back20 verify: VerifyTypes = None,21 cert: CertTypes = None,22 timeout: TimeoutTypes = None,Drop sync (#544)Tom Christiebefore adoption206c537
line 23why, one step back23 ) -> Response:Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
line 24why, one step back24 headers = [("www-authenticate", self.auth_header)] if self.auth_header else []Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
line 25why, one step back25 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()Drop sync (#544)Tom Christiebefore adoption206c537
line 26why, one step back26 return Response(Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 27–28why, one step back27 self.status_code, headers=headers, content=body, request=request28 )Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 29–30why, one step back2930Drop sync (#544)Tom Christiebefore adoption206c537
line 31why, one step back31class MockDigestAuthDispatch(Dispatcher):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 32–46why, one step back32 def __init__(33 self,34 algorithm: str = "SHA-256",35 send_response_after_attempt: int = 1,36 qop: str = "auth",37 regenerate_nonce: bool = True,38 ) -> None:39 self.algorithm = algorithm40 self.send_response_after_attempt = send_response_after_attempt41 self.qop = qop42 self._regenerate_nonce = regenerate_nonce43 self._response_count = 04445 async def send(46 self,Drop sync (#544)Tom Christiebefore adoption206c537
line 47why, one step back47 request: Request,Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 48–50why, one step back48 verify: VerifyTypes = None,49 cert: CertTypes = None,50 timeout: TimeoutTypes = None,Drop sync (#544)Tom Christiebefore adoption206c537
line 51why, one step back51 ) -> Response:Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 52–55why, one step back52 if self._response_count < self.send_response_after_attempt:53 return self.challenge_send(request)5455 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()Drop sync (#544)Tom Christiebefore adoption206c537
line 56why, one step back56 return Response(200, content=body, request=request)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
line 57why, one step back57Drop sync (#544)Tom Christiebefore adoption206c537
line 58why, one step back58 def challenge_send(self, request: Request) -> Response:Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 59–82why, one step back59 self._response_count += 160 nonce = (61 hashlib.sha256(os.urandom(8)).hexdigest()62 if self._regenerate_nonce63 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"64 )65 challenge_data = {66 "nonce": nonce,67 "qop": self.qop,68 "opaque": (69 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"70 ),71 "algorithm": self.algorithm,72 "stale": "FALSE",73 }74 challenge_str = ", ".join(75 '{}="{}"'.format(key, value)76 for key, value in challenge_data.items()77 if value78 )7980 headers = [81 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)82 ]Drop sync (#544)Tom Christiebefore adoption206c537
line 83why, one step back83 return Response(401, headers=headers, content=b"", request=request)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 84–85why, one step back8485Drop sync (#544)Tom Christiebefore adoption206c537
lines 86–87why, one step back86@pytest.mark.asyncio87async def test_basic_auth():Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 88–90why, one step back88 url = "https://example.org/"89 auth = ("tomchristie", "password123")90Drop sync (#544)Tom Christiebefore adoption206c537
lines 91–92why, one step back91 client = Client(dispatch=MockDispatch())92 response = await client.get(url, auth=auth)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 93–97why, one step back9394 assert response.status_code == 20095 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}9697Drop sync (#544)Tom Christiebefore adoption206c537
lines 98–99why, one step back98@pytest.mark.asyncio99async def test_basic_auth_in_url():Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 100–101why, one step back100 url = "https://tomchristie:password123@example.org/"101Drop sync (#544)Tom Christiebefore adoption206c537
lines 102–103why, one step back102 client = Client(dispatch=MockDispatch())103 response = await client.get(url)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 104–108why, one step back104105 assert response.status_code == 200106 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}107108Drop sync (#544)Tom Christiebefore adoption206c537
lines 109–110why, one step back109@pytest.mark.asyncio110async def test_basic_auth_on_session():Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 111–113why, one step back111 url = "https://example.org/"112 auth = ("tomchristie", "password123")113Drop sync (#544)Tom Christiebefore adoption206c537
lines 114–115why, one step back114 client = Client(dispatch=MockDispatch(), auth=auth)115 response = await client.get(url)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 116–120why, one step back116117 assert response.status_code == 200118 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}119120Drop sync (#544)Tom Christiebefore adoption206c537
lines 121–122why, one step back121@pytest.mark.asyncio122async def test_custom_auth():Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 123–128why, one step back123 url = "https://example.org/"124125 def auth(request):126 request.headers["Authorization"] = "Token 123"127 return request128Drop sync (#544)Tom Christiebefore adoption206c537
lines 129–130why, one step back129 client = Client(dispatch=MockDispatch())130 response = await client.get(url, auth=auth)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 131–135why, one step back131132 assert response.status_code == 200133 assert response.json() == {"auth": "Token 123"}134135Drop sync (#544)Tom Christiebefore adoption206c537
lines 136–137why, one step back136@pytest.mark.asyncio137async def test_netrc_auth():Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 138–140why, one step back138 os.environ["NETRC"] = "tests/.netrc"139 url = "http://netrcexample.org"140Drop sync (#544)Tom Christiebefore adoption206c537
lines 141–142why, one step back141 client = Client(dispatch=MockDispatch())142 response = await client.get(url)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 143–149why, one step back143144 assert response.status_code == 200145 assert response.json() == {146 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"147 }148149Drop sync (#544)Tom Christiebefore adoption206c537
line 150why, one step back150@pytest.mark.asyncioEnsure Authorization header has priority over .netrcTom Christiebefore adoption43331cf
lines 151–162why, one step back151async def test_auth_header_has_priority_over_netrc():152 os.environ["NETRC"] = "tests/.netrc"153 url = "http://netrcexample.org"154155 client = Client(dispatch=MockDispatch())156 response = await client.get(url, headers={"Authorization": "Override"})157158 assert response.status_code == 200159 assert response.json() == {"auth": "Override"}160161162@pytest.mark.asyncioDrop sync (#544)Tom Christiebefore adoption206c537
line 163why, one step back163async def test_trust_env_auth():Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 164–166why, one step back164 os.environ["NETRC"] = "tests/.netrc"165 url = "http://netrcexample.org"166No I/O auth (#644)Tom Christiebefore adoption6c69e09
lines 167–168why, one step back167 client = Client(dispatch=MockDispatch(), trust_env=False)168 response = await client.get(url)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 169–172why, one step back169170 assert response.status_code == 200171 assert response.json() == {"auth": None}172No I/O auth (#644)Tom Christiebefore adoption6c69e09
lines 173–174why, one step back173 client = Client(dispatch=MockDispatch(), trust_env=True)174 response = await client.get(url)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 175–188why, one step back175176 assert response.status_code == 200177 assert response.json() == {178 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"179 }180181182def test_auth_hidden_url():183 url = "http://example-username:example-password@example.org/"184 expected = "URL('http://example-username:[secure]@example.org/')"185 assert url == URL(url)186 assert expected == repr(URL(url))187188Drop sync (#544)Tom Christiebefore adoption206c537
lines 189–190why, one step back189@pytest.mark.asyncio190async def test_auth_hidden_header():Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 191–193why, one step back191 url = "https://example.org/"192 auth = ("example-username", "example-password")193Drop sync (#544)Tom Christiebefore adoption206c537
lines 194–195why, one step back194 client = Client(dispatch=MockDispatch())195 response = await client.get(url, auth=auth)Add ConcurrencyBackend.start_tls() (#263)Seth Michael Larsonbefore adoption1872ae8
lines 196–197why, one step back196197 assert "'authorization': '[secure]'" in str(response.request.headers)Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
lines 198–199why, one step back198199Drop sync (#544)Tom Christiebefore adoption206c537
lines 200–201why, one step back200@pytest.mark.asyncio201async def test_auth_invalid_type():Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c
line 202why, one step back202 url = "https://example.org/"Drop sync (#544)Tom Christiebefore adoption206c537
lines 203–205why, one step back203 client = Client(dispatch=MockDispatch(), auth="not a tuple, not a callable")204 with pytest.raises(TypeError):205 await client.get(url)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 206–207why, one step back206207Drop sync (#544)Tom Christiebefore adoption206c537
lines 208–209why, one step back208@pytest.mark.asyncio209async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 210–212why, one step back210 url = "https://example.org/"211 auth = DigestAuth(username="tomchristie", password="password123")212Drop sync (#544)Tom Christiebefore adoption206c537
lines 213–214why, one step back213 client = Client(dispatch=MockDispatch())214 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 215–219why, one step back215216 assert response.status_code == 200217 assert response.json() == {"auth": None}218219Drop sync (#544)Tom Christiebefore adoption206c537
lines 220–221why, one step back220@pytest.mark.asyncio221async def test_digest_auth_200_response_including_digest_auth_header():Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 222–225why, one step back222 url = "https://example.org/"223 auth = DigestAuth(username="tomchristie", password="password123")224 auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'225Drop sync (#544)Tom Christiebefore adoption206c537
lines 226–227why, one step back226 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))227 response = await client.get(url, auth=auth)Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 228–232why, one step back228229 assert response.status_code == 200230 assert response.json() == {"auth": None}231232Drop sync (#544)Tom Christiebefore adoption206c537
lines 233–234why, one step back233@pytest.mark.asyncio234async def test_digest_auth_401_response_without_digest_auth_header():Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 235–237why, one step back235 url = "https://example.org/"236 auth = DigestAuth(username="tomchristie", password="password123")237Drop sync (#544)Tom Christiebefore adoption206c537
lines 238–239why, one step back238 client = Client(dispatch=MockDispatch(auth_header="", status_code=401))239 response = await client.get(url, auth=auth)Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
lines 240–244why, one step back240241 assert response.status_code == 401242 assert response.json() == {"auth": None}243244Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 245–257why, one step back245@pytest.mark.parametrize(246 "algorithm,expected_hash_length,expected_response_length",247 [248 ("MD5", 64, 32),249 ("MD5-SESS", 64, 32),250 ("SHA", 64, 40),251 ("SHA-SESS", 64, 40),252 ("SHA-256", 64, 64),253 ("SHA-256-SESS", 64, 64),254 ("SHA-512", 64, 128),255 ("SHA-512-SESS", 64, 128),256 ],257)Drop sync (#544)Tom Christiebefore adoption206c537
lines 258–259why, one step back258@pytest.mark.asyncio259async def test_digest_auth(algorithm, expected_hash_length, expected_response_length):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 260–262why, one step back260 url = "https://example.org/"261 auth = DigestAuth(username="tomchristie", password="password123")262Drop sync (#544)Tom Christiebefore adoption206c537
lines 263–264why, one step back263 client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))264 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 265–284why, one step back265266 assert response.status_code == 200267 auth = response.json()["auth"]268 assert auth.startswith("Digest ")269270 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]271 digest_data = dict(field.split("=") for field in response_fields)272273 assert digest_data["username"] == '"tomchristie"'274 assert digest_data["realm"] == '"httpx@example.org"'275 assert "nonce" in digest_data276 assert digest_data["uri"] == '"/"'277 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes278 assert len(digest_data["opaque"]) == expected_hash_length + 2279 assert digest_data["algorithm"] == algorithm280 assert digest_data["qop"] == "auth"281 assert digest_data["nc"] == "00000001"282 assert len(digest_data["cnonce"]) == 16 + 2283284Drop sync (#544)Tom Christiebefore adoption206c537
lines 285–286why, one step back285@pytest.mark.asyncio286async def test_digest_auth_no_specified_qop():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 287–289why, one step back287 url = "https://example.org/"288 auth = DigestAuth(username="tomchristie", password="password123")289Drop sync (#544)Tom Christiebefore adoption206c537
lines 290–291why, one step back290 client = Client(dispatch=MockDigestAuthDispatch(qop=None))291 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 292–311why, one step back292293 assert response.status_code == 200294 auth = response.json()["auth"]295 assert auth.startswith("Digest ")296297 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]298 digest_data = dict(field.split("=") for field in response_fields)299300 assert "qop" not in digest_data301 assert "nc" not in digest_data302 assert "cnonce" not in digest_data303 assert digest_data["username"] == '"tomchristie"'304 assert digest_data["realm"] == '"httpx@example.org"'305 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes306 assert digest_data["uri"] == '"/"'307 assert len(digest_data["response"]) == 64 + 2308 assert len(digest_data["opaque"]) == 64 + 2309 assert digest_data["algorithm"] == "SHA-256"310311Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156
line 312why, one step back312@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))Drop sync (#544)Tom Christiebefore adoption206c537
lines 313–314why, one step back313@pytest.mark.asyncio314async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 315–317why, one step back315 url = "https://example.org/"316 auth = DigestAuth(username="tomchristie", password="password123")317Drop sync (#544)Tom Christiebefore adoption206c537
lines 318–319why, one step back318 client = Client(dispatch=MockDigestAuthDispatch(qop=qop))319 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 320–321why, one step back320321Drop sync (#544)Tom Christiebefore adoption206c537
lines 322–323why, one step back322@pytest.mark.asyncio323async def test_digest_auth_qop_auth_int_not_implemented():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 324–325why, one step back324 url = "https://example.org/"325 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 326why, one step back326 client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 327–328why, one step back327328 with pytest.raises(NotImplementedError):Drop sync (#544)Tom Christiebefore adoption206c537
line 329why, one step back329 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 330–331why, one step back330331Drop sync (#544)Tom Christiebefore adoption206c537
lines 332–333why, one step back332@pytest.mark.asyncio333async def test_digest_auth_qop_must_be_auth_or_auth_int():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 334–335why, one step back334 url = "https://example.org/"335 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 336why, one step back336 client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 337–338why, one step back337338 with pytest.raises(ProtocolError):Drop sync (#544)Tom Christiebefore adoption206c537
line 339why, one step back339 await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 340–341why, one step back340341Drop sync (#544)Tom Christiebefore adoption206c537
lines 342–343why, one step back342@pytest.mark.asyncio343async def test_digest_auth_incorrect_credentials():Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 344–346why, one step back344 url = "https://example.org/"345 auth = DigestAuth(username="tomchristie", password="password123")346Drop sync (#544)Tom Christiebefore adoption206c537
lines 347–348why, one step back347 client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))348 response = await client.get(url, auth=auth)Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 349–362why, one step back349350 assert response.status_code == 401351352353@pytest.mark.parametrize(354 "auth_header",355 [356 'Digest realm="httpx@example.org", qop="auth"', # missing fields357 'realm="httpx@example.org", qop="auth"', # not starting with Digest358 'DigestZ realm="httpx@example.org", qop="auth"'359 'qop="auth,auth-int",nonce="abc",opaque="xyz"',360 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list361 ],362)Drop sync (#544)Tom Christiebefore adoption206c537
lines 363–364why, one step back363@pytest.mark.asyncio364async def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 365–366why, one step back365 url = "https://example.org/"366 auth = DigestAuth(username="tomchristie", password="password123")Drop sync (#544)Tom Christiebefore adoption206c537
line 367why, one step back367 client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d
lines 368–369why, one step back368369 with pytest.raises(ProtocolError):Drop sync (#544)Tom Christiebefore adoption206c537
line 370why, one step back370 await client.get(url, auth=auth)