Add DigestAuth middleware (#332)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Remove global variable, just return response from auth request * Add extra space to Digest header start assertion * Prevent unpacking errors limiting the number of splits
authored by Yeray Diaz Diaz · committed by Seth Michael Larson · parent 08edfac · Browse files · 6 files·+409 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+409 added−2 removed
- tests:+209 added−0 removed
- other:+200 added−2 removed
Provenance
- Commit
fd3b69d- Tree
dde4e19- Author
Yeray Diaz Diaz <yeraydiazdiaz@gmail.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
08edfac
6 files changed+409 added−2 removed
added:httpx/middleware/digest_auth.py+181 added
1+import hashlib2+import os3+import re4+import time5+import typing6+from urllib.request import parse_http_list7+8+from ..exceptions import ProtocolError9+from ..models import AsyncRequest, AsyncResponse, StatusCode10+from ..utils import to_bytes, to_str, unquote11+from .base import BaseMiddleware12+13+14+class DigestAuth(BaseMiddleware):15+ ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable] = {16+ "MD5": hashlib.md5,17+ "MD5-SESS": hashlib.md5,18+ "SHA": hashlib.sha1,19+ "SHA-SESS": hashlib.sha1,20+ "SHA-256": hashlib.sha256,21+ "SHA-256-SESS": hashlib.sha256,22+ "SHA-512": hashlib.sha512,23+ "SHA-512-SESS": hashlib.sha512,24+ }25+26+ def __init__(27+ self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]28+ ) -> None:29+ self.username = to_bytes(username)30+ self.password = to_bytes(password)31+32+ async def __call__(33+ self, request: AsyncRequest, get_response: typing.Callable34+ ) -> AsyncResponse:35+ response = await get_response(request)36+ if not (37+ StatusCode.is_client_error(response.status_code)38+ and "www-authenticate" in response.headers39+ ):40+ return response41+42+ header = response.headers["www-authenticate"]43+ try:44+ challenge = DigestAuthChallenge.from_header(header)45+ except ValueError:46+ raise ProtocolError("Malformed Digest authentication header")47+48+ request.headers["Authorization"] = self._build_auth_header(request, challenge)49+ return await get_response(request)50+51+ def _build_auth_header(52+ self, request: AsyncRequest, challenge: "DigestAuthChallenge"53+ ) -> str:54+ hash_func = self.ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm]55+56+ def digest(data: bytes) -> bytes:57+ return hash_func(data).hexdigest().encode()58+59+ A1 = b":".join((self.username, challenge.realm, self.password))60+61+ path = request.url.full_path.encode("utf-8")62+ A2 = b":".join((request.method.encode(), path))63+ # TODO: implement auth-int64+ HA2 = digest(A2)65+66+ nonce_count = 1 # TODO: implement nonce counting67+ nc_value = b"%08x" % nonce_count68+ cnonce = self._get_client_nonce(nonce_count, challenge.nonce)69+70+ HA1 = digest(A1)71+ if challenge.algorithm.lower().endswith("-sess"):72+ HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))73+74+ qop = self._resolve_qop(challenge.qop)75+ if qop is None:76+ digest_data = [HA1, challenge.nonce, HA2]77+ else:78+ digest_data = [challenge.nonce, nc_value, cnonce, qop, HA2]79+ key_digest = b":".join(digest_data)80+81+ format_args = {82+ "username": self.username,83+ "realm": challenge.realm,84+ "nonce": challenge.nonce,85+ "uri": path,86+ "response": digest(b":".join((HA1, key_digest))),87+ "algorithm": challenge.algorithm.encode(),88+ }89+ if challenge.opaque:90+ format_args["opaque"] = challenge.opaque91+ if qop:92+ format_args["qop"] = b"auth"93+ format_args["nc"] = nc_value94+ format_args["cnonce"] = cnonce95+96+ return "Digest " + self._get_header_value(format_args)97+98+ def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:99+ s = str(nonce_count).encode()100+ s += nonce101+ s += time.ctime().encode()102+ s += os.urandom(8)103+104+ return hashlib.sha1(s).hexdigest()[:16].encode()105+106+ def _get_header_value(self, header_fields: typing.Dict[str, bytes]) -> str:107+ NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")108+ QUOTED_TEMPLATE = '{}="{}"'109+ NON_QUOTED_TEMPLATE = "{}={}"110+111+ header_value = ""112+ for i, (field, value) in enumerate(header_fields.items()):113+ if i > 0:114+ header_value += ", "115+ template = (116+ QUOTED_TEMPLATE117+ if field not in NON_QUOTED_FIELDS118+ else NON_QUOTED_TEMPLATE119+ )120+ header_value += template.format(field, to_str(value))121+122+ return header_value123+124+ def _resolve_qop(self, qop: typing.Optional[bytes]) -> typing.Optional[bytes]:125+ if qop is None:126+ return None127+ qops = re.split(b", ?", qop)128+ if b"auth" in qops:129+ return b"auth"130+131+ if qops == [b"auth-int"]:132+ raise NotImplementedError("Digest auth-int support is not yet implemented")133+134+ raise ProtocolError(f'Unexpected qop value "{qop!r}" in digest auth')135+136+137+class DigestAuthChallenge:138+ def __init__(139+ self,140+ realm: bytes,141+ nonce: bytes,142+ algorithm: str = None,143+ opaque: typing.Optional[bytes] = None,144+ qop: typing.Optional[bytes] = None,145+ ) -> None:146+ self.realm = realm147+ self.nonce = nonce148+ self.algorithm = algorithm or "MD5"149+ self.opaque = opaque150+ self.qop = qop151+152+ @classmethod153+ def from_header(cls, header: str) -> "DigestAuthChallenge":154+ """Returns a challenge from a Digest WWW-Authenticate header.155+ These take the form of:156+ `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`157+ """158+ scheme, _, fields = header.partition(" ")159+ if scheme.lower() != "digest":160+ raise ValueError("Header does not start with 'Digest'")161+162+ header_dict: typing.Dict[str, str] = {}163+ for field in parse_http_list(fields):164+ key, value = field.strip().split("=", 1)165+ header_dict[key] = unquote(value)166+167+ try:168+ return cls.from_header_dict(header_dict)169+ except KeyError as exc:170+ raise ValueError("Malformed Digest WWW-Authenticate header") from exc171+172+ @classmethod173+ def from_header_dict(cls, header_dict: dict) -> "DigestAuthChallenge":174+ realm = header_dict["realm"].encode()175+ nonce = header_dict["nonce"].encode()176+ qop = header_dict["qop"].encode() if "qop" in header_dict else None177+ opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None178+ algorithm = header_dict.get("algorithm")179+ return cls(180+ realm=realm, nonce=nonce, qop=qop, opaque=opaque, algorithm=algorithm181+ )modified:httpx/__init__.py+2 added
38 unmodified lines39 Timeout,40 TooManyRedirects,41 WriteTimeout,42 )43+from .middleware.digest_auth import DigestAuth44 from .models import (45 URL,46 AsyncRequest,47 AsyncRequestData,85 unmodified lines133 "RequestData",134 "Response",135 "ResponseContent",136 "RequestFiles",137+ "DigestAuth",138 ]modified:httpx/client.py+3 added-2 removed
209 unmodified lines210 self, request: AsyncRequest, trust_env: bool, auth: AuthTypes = None211 ) -> typing.Optional[BaseMiddleware]:212 if isinstance(auth, tuple):213 return BasicAuthMiddleware(username=auth[0], password=auth[1])214-215- if callable(auth):214+ elif isinstance(auth, BaseMiddleware):215+ return auth216+ elif callable(auth):217 return CustomAuthMiddleware(auth=auth)218 219 if auth is not None:220 raise TypeError(745 unmodified linesmodified:httpx/models.py+4 added
37 unmodified lines38 parse_header_links,39 str_query_param,40 )41 42+if typing.TYPE_CHECKING:43+ from .middleware.base import BaseMiddleware # noqa: F40144+45 PrimitiveData = typing.Optional[typing.Union[str, int, float, bool]]46 47 URLTypes = typing.Union["URL", str]48 14 unmodified lines63 64 AuthTypes = typing.Union[65 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],66 typing.Callable[["AsyncRequest"], "AsyncRequest"],67+ "BaseMiddleware",68 ]69 70 AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]71 1170 unmodified linesmodified:httpx/utils.py+10 added
171 unmodified lines172 173 174 def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:175 return value.encode(encoding) if isinstance(value, str) else value176+177+178+def to_str(str_or_bytes: typing.Union[str, bytes], encoding: str = "utf-8") -> str:179+ return (180+ str_or_bytes if isinstance(str_or_bytes, str) else str_or_bytes.decode(encoding)181+ )182+183+184+def unquote(value: str) -> str:185+ return value[1:-1] if value[0] == value[-1] == '"' else valuemodified:tests/client/test_auth.py+209 added
1+import hashlib2 import json3 import os4 5 import pytest4 unmodified lines10 AsyncRequest,11 AsyncResponse,12 CertTypes,13 Client,14+ DigestAuth,15+ ProtocolError,16 TimeoutTypes,17 VerifyTypes,18 )19 9 unmodified lines29 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()30 return AsyncResponse(200, content=body, request=request)31 32 33+class 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 = 046+47+ 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)56+57+ body = json.dumps({"auth": request.headers.get("Authorization")}).encode()58+ return AsyncResponse(200, content=body, request=request)59+60+ 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+ )81+82+ headers = [83+ ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)84+ ]85+ return AsyncResponse(401, headers=headers, content=b"", request=request)86+87+ def reset(self) -> None:88+ self._response_count = 089+90+91+class MockAuthHeaderDispatch(AsyncDispatcher):92+ def __init__(self, auth_header: str) -> None:93+ self.auth_header = auth_header94+95+ 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)104+105+106 def test_basic_auth():107 url = "https://example.org/"108 auth = ("tomchristie", "password123")109 92 unmodified lines202 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)206+207+208+def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():209+ url = "https://example.org/"210+ auth = DigestAuth(username="tomchristie", password="password123")211+212+ with Client(dispatch=MockDispatch()) as client:213+ response = client.get(url, auth=auth)214+215+ assert response.status_code == 200216+ assert response.json() == {"auth": None}217+218+219+@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+)232+def test_digest_auth(algorithm, expected_hash_length, expected_response_length):233+ url = "https://example.org/"234+ auth = DigestAuth(username="tomchristie", password="password123")235+236+ with Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm)) as client:237+ response = client.get(url, auth=auth)238+239+ assert response.status_code == 200240+ auth = response.json()["auth"]241+ assert auth.startswith("Digest ")242+243+ response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]244+ digest_data = dict(field.split("=") for field in response_fields)245+246+ 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 + 2256+257+258+def test_digest_auth_no_specified_qop():259+ url = "https://example.org/"260+ auth = DigestAuth(username="tomchristie", password="password123")261+262+ with Client(dispatch=MockDigestAuthDispatch(qop=None)) as client:263+ response = client.get(url, auth=auth)264+265+ assert response.status_code == 200266+ auth = response.json()["auth"]267+ assert auth.startswith("Digest ")268+269+ response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]270+ digest_data = dict(field.split("=") for field in response_fields)271+272+ 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"282+283+284+def test_digest_auth_qop_including_spaces_and_auth_returns_auth():285+ url = "https://example.org/"286+ auth = DigestAuth(username="tomchristie", password="password123")287+288+ with Client(dispatch=MockDigestAuthDispatch(qop="auth, auth-int")) as client:289+ client.get(url, auth=auth)290+291+292+def test_digest_auth_qop_auth_int_not_implemented():293+ url = "https://example.org/"294+ auth = DigestAuth(username="tomchristie", password="password123")295+296+ with pytest.raises(NotImplementedError):297+ with Client(dispatch=MockDigestAuthDispatch(qop="auth-int")) as client:298+ client.get(url, auth=auth)299+300+301+def test_digest_auth_qop_must_be_auth_or_auth_int():302+ url = "https://example.org/"303+ auth = DigestAuth(username="tomchristie", password="password123")304+305+ with pytest.raises(ProtocolError):306+ with Client(dispatch=MockDigestAuthDispatch(qop="not-auth")) as client:307+ client.get(url, auth=auth)308+309+310+def test_digest_auth_incorrect_credentials():311+ url = "https://example.org/"312+ auth = DigestAuth(username="tomchristie", password="password123")313+314+ with Client(315+ dispatch=MockDigestAuthDispatch(send_response_after_attempt=2)316+ ) as client:317+ response = client.get(url, auth=auth)318+319+ assert response.status_code == 401320+321+322+@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+)332+def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):333+ url = "https://example.org/"334+ auth = DigestAuth(username="tomchristie", password="password123")335+336+ with pytest.raises(ProtocolError):337+ with Client(dispatch=MockAuthHeaderDispatch(auth_header=auth_header)) as client:338+ client.get(url, auth=auth)