Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

338 lines · 10.6 KiB · Python

Last changed by

Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d

History of this file

Take it

Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d

line 1why, one step back
1import hashlib

Auth (#65)Tom Christiebefore adoption5afa7dd

line 2why, one step back
2import json

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

line 3why, one step back
3import os

Auth (#65)Tom Christiebefore adoption5afa7dd

line 4why, one step back
4

Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c

lines 5–6why, one step back
5import pytest
6

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 7why, one step back
7from httpx import (

fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d

line 8why, one step back
8 URL,

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

lines 9–11why, one step back
9 AsyncDispatcher,
10 AsyncRequest,11 AsyncResponse,

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

line 12why, one step back
12 CertTypes,

Auth (#65)Tom Christiebefore adoption5afa7dd

line 13why, one step back
13 Client,

Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d

lines 14–15why, one step back
14 DigestAuth,
15 ProtocolError,

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

lines 16–17why, one step back
16 TimeoutTypes,
17 VerifyTypes,

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 18–20why, one step back
18)
1920

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

line 21why, one step back
21class MockDispatch(AsyncDispatcher):

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 22–23why, one step back
22 async def send(
23 self,

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

line 24why, one step back
24 request: AsyncRequest,

Work on bringing API into parity with `requests`. (#76)Tom Christiebefore adoption9574041

lines 25–27why, one step back
25 verify: VerifyTypes = None,
26 cert: CertTypes = None,27 timeout: TimeoutTypes = None,

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

line 28why, one step back
28 ) -> AsyncResponse:

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

line 29why, one step back
29 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()

Sync or Async dispatch (#83)Tom Christiebefore adoption0cbf3c7

line 30why, one step back
30 return AsyncResponse(200, content=body, request=request)

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 31–32why, one step back
31
32

Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d

lines 33–105why, one step back
33class MockDigestAuthDispatch(AsyncDispatcher):
34 def __init__(35 self,36 algorithm: str = "SHA-256",37 send_response_after_attempt: int = 1,38 qop: str = "auth",39 regenerate_nonce: bool = True,40 ) -> None:41 self.algorithm = algorithm42 self.send_response_after_attempt = send_response_after_attempt43 self.qop = qop44 self._regenerate_nonce = regenerate_nonce45 self._response_count = 04647 async def send(48 self,49 request: AsyncRequest,50 verify: VerifyTypes = None,51 cert: CertTypes = None,52 timeout: TimeoutTypes = None,53 ) -> AsyncResponse:54 if self._response_count < self.send_response_after_attempt:55 return self.challenge_send(request)5657 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()58 return AsyncResponse(200, content=body, request=request)5960 def challenge_send(self, request: AsyncRequest) -> AsyncResponse:61 self._response_count += 162 nonce = (63 hashlib.sha256(os.urandom(8)).hexdigest()64 if self._regenerate_nonce65 else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"66 )67 challenge_data = {68 "nonce": nonce,69 "qop": self.qop,70 "opaque": (71 "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"72 ),73 "algorithm": self.algorithm,74 "stale": "FALSE",75 }76 challenge_str = ", ".join(77 '{}="{}"'.format(key, value)78 for key, value in challenge_data.items()79 if value80 )8182 headers = [83 ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)84 ]85 return AsyncResponse(401, headers=headers, content=b"", request=request)8687 def reset(self) -> None:88 self._response_count = 0899091class MockAuthHeaderDispatch(AsyncDispatcher):92 def __init__(self, auth_header: str) -> None:93 self.auth_header = auth_header9495 async def send(96 self,97 request: AsyncRequest,98 verify: VerifyTypes = None,99 cert: CertTypes = None,100 timeout: TimeoutTypes = None,101 ) -> AsyncResponse:102 headers = [("www-authenticate", self.auth_header)]103 return AsyncResponse(401, headers=headers, content=b"", request=request)104105

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 106–107why, one step back
106def test_basic_auth():
107 url = "https://example.org/"

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

line 108why, one step back
108 auth = ("tomchristie", "password123")

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 109–113why, one step back
109
110 with Client(dispatch=MockDispatch()) as client:111 response = client.get(url, auth=auth)112113 assert response.status_code == 200

Add response.json()Tom Christiebefore adoption2116d44

line 114why, one step back
114 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 115–123why, one step back
115
116117def test_basic_auth_in_url():118 url = "https://tomchristie:password123@example.org/"119120 with Client(dispatch=MockDispatch()) as client:121 response = client.get(url)122123 assert response.status_code == 200

Add response.json()Tom Christiebefore adoption2116d44

line 124why, one step back
124 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 125–128why, one step back
125
126127def test_basic_auth_on_session():128 url = "https://example.org/"

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

line 129why, one step back
129 auth = ("tomchristie", "password123")

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 130–134why, one step back
130
131 with Client(dispatch=MockDispatch(), auth=auth) as client:132 response = client.get(url)133134 assert response.status_code == 200

Add response.json()Tom Christiebefore adoption2116d44

line 135why, one step back
135 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 136–141why, one step back
136
137138def test_custom_auth():139 url = "https://example.org/"140141 def auth(request):

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

line 142why, one step back
142 request.headers["Authorization"] = "Token 123"

Auth (#65)Tom Christiebefore adoption5afa7dd

lines 143–148why, one step back
143 return request
144145 with Client(dispatch=MockDispatch()) as client:146 response = client.get(url, auth=auth)147148 assert response.status_code == 200

Add response.json()Tom Christiebefore adoption2116d44

line 149why, one step back
149 assert response.json() == {"auth": "Token 123"}

added netrc support (#177)Can Sarıgölbefore adoption919e8d3

lines 150–173why, one step back
150
151152def test_netrc_auth():153 os.environ["NETRC"] = "tests/.netrc"154 url = "http://netrcexample.org"155156 with Client(dispatch=MockDispatch()) as client:157 response = client.get(url)158159 assert response.status_code == 200160 assert response.json() == {161 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"162 }163164165def test_trust_env_auth():166 os.environ["NETRC"] = "tests/.netrc"167 url = "http://netrcexample.org"168169 with Client(dispatch=MockDispatch()) as client:170 response = client.get(url, trust_env=False)171172 assert response.status_code == 200173 assert response.json() == {"auth": None}

Add trust_env property to BaseClient (#187)Can Sarıgölbefore adoption04d5ffb

lines 174–181why, one step back
174
175 with Client(dispatch=MockDispatch(), trust_env=False) as client:176 response = client.get(url, trust_env=True)177178 assert response.status_code == 200179 assert response.json() == {180 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"181 }

fixed __repr__ function of Headers and Url classes (#222)Can Sarıgölbefore adoptiona0aff8d

lines 182–198why, one step back
182
183184def test_auth_hidden_url():185 url = "http://example-username:example-password@example.org/"186 expected = "URL('http://example-username:[secure]@example.org/')"187 assert url == URL(url)188 assert expected == repr(URL(url))189190191def test_auth_hidden_header():192 url = "https://example.org/"193 auth = ("example-username", "example-password")194195 with Client(dispatch=MockDispatch()) as client:196 response = client.get(url, auth=auth)197198 assert "'authorization': '[secure]'" in str(response.request.headers)

Refactor client functionality into middleware (#268)Florimond Mancabefore adoption40e6e8c

lines 199–205why, one step back
199
200201def test_auth_invalid_type():202 url = "https://example.org/"203 with Client(dispatch=MockDispatch(), auth="not a tuple, not a callable") as client:204 with pytest.raises(TypeError):205 client.get(url)

Add DigestAuth middleware (#332)Yeray Diaz Diazbefore adoptionfd3b69d

lines 206–338why, one step back
206
207208def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():209 url = "https://example.org/"210 auth = DigestAuth(username="tomchristie", password="password123")211212 with Client(dispatch=MockDispatch()) as client:213 response = client.get(url, auth=auth)214215 assert response.status_code == 200216 assert response.json() == {"auth": None}217218219@pytest.mark.parametrize(220 "algorithm,expected_hash_length,expected_response_length",221 [222 ("MD5", 64, 32),223 ("MD5-SESS", 64, 32),224 ("SHA", 64, 40),225 ("SHA-SESS", 64, 40),226 ("SHA-256", 64, 64),227 ("SHA-256-SESS", 64, 64),228 ("SHA-512", 64, 128),229 ("SHA-512-SESS", 64, 128),230 ],231)232def test_digest_auth(algorithm, expected_hash_length, expected_response_length):233 url = "https://example.org/"234 auth = DigestAuth(username="tomchristie", password="password123")235236 with Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm)) as client:237 response = client.get(url, auth=auth)238239 assert response.status_code == 200240 auth = response.json()["auth"]241 assert auth.startswith("Digest ")242243 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]244 digest_data = dict(field.split("=") for field in response_fields)245246 assert digest_data["username"] == '"tomchristie"'247 assert digest_data["realm"] == '"httpx@example.org"'248 assert "nonce" in digest_data249 assert digest_data["uri"] == '"/"'250 assert len(digest_data["response"]) == expected_response_length + 2 # extra quotes251 assert len(digest_data["opaque"]) == expected_hash_length + 2252 assert digest_data["algorithm"] == algorithm253 assert digest_data["qop"] == "auth"254 assert digest_data["nc"] == "00000001"255 assert len(digest_data["cnonce"]) == 16 + 2256257258def test_digest_auth_no_specified_qop():259 url = "https://example.org/"260 auth = DigestAuth(username="tomchristie", password="password123")261262 with Client(dispatch=MockDigestAuthDispatch(qop=None)) as client:263 response = client.get(url, auth=auth)264265 assert response.status_code == 200266 auth = response.json()["auth"]267 assert auth.startswith("Digest ")268269 response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]270 digest_data = dict(field.split("=") for field in response_fields)271272 assert "qop" not in digest_data273 assert "nc" not in digest_data274 assert "cnonce" not in digest_data275 assert digest_data["username"] == '"tomchristie"'276 assert digest_data["realm"] == '"httpx@example.org"'277 assert len(digest_data["nonce"]) == 64 + 2 # extra quotes278 assert digest_data["uri"] == '"/"'279 assert len(digest_data["response"]) == 64 + 2280 assert len(digest_data["opaque"]) == 64 + 2281 assert digest_data["algorithm"] == "SHA-256"282283284def test_digest_auth_qop_including_spaces_and_auth_returns_auth():285 url = "https://example.org/"286 auth = DigestAuth(username="tomchristie", password="password123")287288 with Client(dispatch=MockDigestAuthDispatch(qop="auth, auth-int")) as client:289 client.get(url, auth=auth)290291292def test_digest_auth_qop_auth_int_not_implemented():293 url = "https://example.org/"294 auth = DigestAuth(username="tomchristie", password="password123")295296 with pytest.raises(NotImplementedError):297 with Client(dispatch=MockDigestAuthDispatch(qop="auth-int")) as client:298 client.get(url, auth=auth)299300301def test_digest_auth_qop_must_be_auth_or_auth_int():302 url = "https://example.org/"303 auth = DigestAuth(username="tomchristie", password="password123")304305 with pytest.raises(ProtocolError):306 with Client(dispatch=MockDigestAuthDispatch(qop="not-auth")) as client:307 client.get(url, auth=auth)308309310def test_digest_auth_incorrect_credentials():311 url = "https://example.org/"312 auth = DigestAuth(username="tomchristie", password="password123")313314 with Client(315 dispatch=MockDigestAuthDispatch(send_response_after_attempt=2)316 ) as client:317 response = client.get(url, auth=auth)318319 assert response.status_code == 401320321322@pytest.mark.parametrize(323 "auth_header",324 [325 'Digest realm="httpx@example.org", qop="auth"', # missing fields326 'realm="httpx@example.org", qop="auth"', # not starting with Digest327 'DigestZ realm="httpx@example.org", qop="auth"'328 'qop="auth,auth-int",nonce="abc",opaque="xyz"',329 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list330 ],331)332def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):333 url = "https://example.org/"334 auth = DigestAuth(username="tomchristie", password="password123")335336 with pytest.raises(ProtocolError):337 with Client(dispatch=MockAuthHeaderDispatch(auth_header=auth_header)) as client:338 client.get(url, auth=auth)