Skip to content
Myr

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

6 files+409 added−2 removed

added:httpx/middleware/digest_auth.py+181 added
1import hashlib2import os3import re4import time5import typing6from urllib.request import parse_http_list78from ..exceptions import ProtocolError9from ..models import AsyncRequest, AsyncResponse, StatusCode10from ..utils import to_bytes, to_str, unquote11from .base import BaseMiddleware121314class 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 }2526 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)3132 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 response4142 header = response.headers["www-authenticate"]43 try:44 challenge = DigestAuthChallenge.from_header(header)45 except ValueError:46 raise ProtocolError("Malformed Digest authentication header")4748 request.headers["Authorization"] = self._build_auth_header(request, challenge)49 return await get_response(request)5051 def _build_auth_header(52 self, request: AsyncRequest, challenge: "DigestAuthChallenge"53 ) -> str:54 hash_func = self.ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm]5556 def digest(data: bytes) -> bytes:57 return hash_func(data).hexdigest().encode()5859 A1 = b":".join((self.username, challenge.realm, self.password))6061 path = request.url.full_path.encode("utf-8")62 A2 = b":".join((request.method.encode(), path))63 # TODO: implement auth-int64 HA2 = digest(A2)6566 nonce_count = 1 # TODO: implement nonce counting67 nc_value = b"%08x" % nonce_count68 cnonce = self._get_client_nonce(nonce_count, challenge.nonce)6970 HA1 = digest(A1)71 if challenge.algorithm.lower().endswith("-sess"):72 HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))7374 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)8081 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"] = cnonce9596 return "Digest " + self._get_header_value(format_args)9798 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)103104 return hashlib.sha1(s).hexdigest()[:16].encode()105106 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 = "{}={}"110111 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))121122 return header_value123124 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"130131 if qops == [b"auth-int"]:132 raise NotImplementedError("Digest auth-int support is not yet implemented")133134 raise ProtocolError(f'Unexpected qop value "{qop!r}" in digest auth')135136137class 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 = qop151152 @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'")161162 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)166167 try:168 return cls.from_header_dict(header_dict)169 except KeyError as exc:170 raise ValueError("Malformed Digest WWW-Authenticate header") from exc171172 @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 lines
39 Timeout,40 TooManyRedirects,41 WriteTimeout,42)43from .middleware.digest_auth import DigestAuth44from .models import (45 URL,46 AsyncRequest,47 AsyncRequestData,
85 unmodified lines
133 "RequestData",134 "Response",135 "ResponseContent",136 "RequestFiles",137 "DigestAuth",138]
modified:httpx/client.py+3 added-2 removed
209 unmodified lines
210 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])214215 if callable(auth):214 elif isinstance(auth, BaseMiddleware):215 return auth216 elif callable(auth):217 return CustomAuthMiddleware(auth=auth)218219 if auth is not None:220 raise TypeError(
745 unmodified lines
modified:httpx/models.py+4 added
37 unmodified lines
38 parse_header_links,39 str_query_param,40)4142if typing.TYPE_CHECKING:43 from .middleware.base import BaseMiddleware # noqa: F4014445PrimitiveData = typing.Optional[typing.Union[str, int, float, bool]]4647URLTypes = typing.Union["URL", str]48
14 unmodified lines
6364AuthTypes = typing.Union[65 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],66 typing.Callable[["AsyncRequest"], "AsyncRequest"],67 "BaseMiddleware",68]6970AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]71
1170 unmodified lines
modified:httpx/utils.py+10 added
171 unmodified lines
172173174def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:175 return value.encode(encoding) if isinstance(value, str) else value176177178def 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 )182183184def unquote(value: str) -> str:185 return value[1:-1] if value[0] == value[-1] == '"' else value
modified:tests/client/test_auth.py+209 added
1import hashlib2import json3import os45import pytest
4 unmodified lines
10 AsyncRequest,11 AsyncResponse,12 CertTypes,13 Client,14 DigestAuth,15 ProtocolError,16 TimeoutTypes,17 VerifyTypes,18)19
9 unmodified lines
29 body = json.dumps({"auth": request.headers.get("Authorization")}).encode()30 return AsyncResponse(200, content=body, request=request)313233class 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)104105106def test_basic_auth():107 url = "https://example.org/"108 auth = ("tomchristie", "password123")109
92 unmodified lines
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)206207208def 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)