Tighten public API on auth classes (#1084)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by GitHub · parent 50b17fd · Browse files · 1 file·+46 added−51 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
Diff stats
1 file+46 added−51 removed
- other:+46 added−51 removed
Provenance
- Commit
6421575- Tree
c32715b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
50b17fd
1 file changed+46 added−51 removed
modified:httpx/_auth.py+46 added-51 removed
12 unmodified lines13 14 class Auth:15 """16 Base class for all authentication schemes.17+18+ To implement a custom authentication scheme, subclass `Auth` and override19+ the `.auth_flow()` method.20 """21 22 requires_request_body = False23 requires_response_body = False29 unmodified lines53 that takes the request, and returns a new, modified request.54 """55 56 def __init__(self, func: typing.Callable[[Request], Request]) -> None:54- self.func = func57+ self._func = func58 59 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:57- yield self.func(request)60+ yield self._func(request)61 62 63 class BasicAuth(Auth):64 """3 unmodified lines68 69 def __init__(70 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]71 ):69- self.auth_header = self.build_auth_header(username, password)72+ self._auth_header = self._build_auth_header(username, password)73 74 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:72- request.headers["Authorization"] = self.auth_header75+ request.headers["Authorization"] = self._auth_header76 yield request77 75- def build_auth_header(78+ def _build_auth_header(79 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]80 ) -> str:81 userpass = b":".join((to_bytes(username), to_bytes(password)))82 token = b64encode(userpass).decode()83 return f"Basic {token}"84 85 86 class DigestAuth(Auth):84- ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable] = {87+ _ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable] = {88 "MD5": hashlib.md5,89 "MD5-SESS": hashlib.md5,90 "SHA": hashlib.sha1,91 "SHA-SESS": hashlib.sha1,5 unmodified lines97 98 def __init__(99 self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]100 ) -> None:98- self.username = to_bytes(username)99- self.password = to_bytes(password)101+ self._username = to_bytes(username)102+ self._password = to_bytes(password)103 104 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:105 if not request.stream.can_replay():106 raise RequestBodyUnavailable(9 unmodified lines116 # need to build an authenticated request.117 return118 119 header = response.headers["www-authenticate"]117- try:118- challenge = DigestAuthChallenge.from_header(header)119- except ValueError:120- raise ProtocolError("Malformed Digest authentication header")121-120+ challenge = self._parse_challenge(header)121 request.headers["Authorization"] = self._build_auth_header(request, challenge)122 yield request123 124+ def _parse_challenge(self, header: str) -> "_DigestAuthChallenge":125+ """126+ Returns a challenge from a Digest WWW-Authenticate header.127+ These take the form of:128+ `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`129+ """130+ scheme, _, fields = header.partition(" ")131+ if scheme.lower() != "digest":132+ raise ProtocolError("Header does not start with 'Digest'")133+134+ header_dict: typing.Dict[str, str] = {}135+ for field in parse_http_list(fields):136+ key, value = field.strip().split("=", 1)137+ header_dict[key] = unquote(value)138+139+ try:140+ realm = header_dict["realm"].encode()141+ nonce = header_dict["nonce"].encode()142+ qop = header_dict["qop"].encode() if "qop" in header_dict else None143+ opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None144+ algorithm = header_dict.get("algorithm", "MD5")145+ return _DigestAuthChallenge(146+ realm=realm, nonce=nonce, qop=qop, opaque=opaque, algorithm=algorithm147+ )148+ except KeyError as exc:149+ raise ProtocolError("Malformed Digest WWW-Authenticate header") from exc150+151 def _build_auth_header(126- self, request: Request, challenge: "DigestAuthChallenge"152+ self, request: Request, challenge: "_DigestAuthChallenge"153 ) -> str:128- hash_func = self.ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm]154+ hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm]155 156 def digest(data: bytes) -> bytes:157 return hash_func(data).hexdigest().encode()158 133- A1 = b":".join((self.username, challenge.realm, self.password))159+ A1 = b":".join((self._username, challenge.realm, self._password))160 161 path = request.url.full_path.encode("utf-8")162 A2 = b":".join((request.method.encode(), path))163 # TODO: implement auth-int14 unmodified lines178 digest_data = [challenge.nonce, nc_value, cnonce, qop, HA2]179 key_digest = b":".join(digest_data)180 181 format_args = {156- "username": self.username,182+ "username": self._username,183 "realm": challenge.realm,184 "nonce": challenge.nonce,185 "uri": path,186 "response": digest(b":".join((HA1, key_digest))),46 unmodified lines233 234 raise ProtocolError(f'Unexpected qop value "{qop!r}" in digest auth')235 236 211-class DigestAuthChallenge:237+class _DigestAuthChallenge:238 def __init__(239 self,240 realm: bytes,241 nonce: bytes,216- algorithm: str = None,242+ algorithm: str,243 opaque: typing.Optional[bytes] = None,244 qop: typing.Optional[bytes] = None,245 ) -> None:246 self.realm = realm247 self.nonce = nonce222- self.algorithm = algorithm or "MD5"248+ self.algorithm = algorithm249 self.opaque = opaque250 self.qop = qop225-226- @classmethod227- def from_header(cls, header: str) -> "DigestAuthChallenge":228- """Returns a challenge from a Digest WWW-Authenticate header.229- These take the form of:230- `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`231- """232- scheme, _, fields = header.partition(" ")233- if scheme.lower() != "digest":234- raise ValueError("Header does not start with 'Digest'")235-236- header_dict: typing.Dict[str, str] = {}237- for field in parse_http_list(fields):238- key, value = field.strip().split("=", 1)239- header_dict[key] = unquote(value)240-241- try:242- return cls.from_header_dict(header_dict)243- except KeyError as exc:244- raise ValueError("Malformed Digest WWW-Authenticate header") from exc245-246- @classmethod247- def from_header_dict(cls, header_dict: dict) -> "DigestAuthChallenge":248- realm = header_dict["realm"].encode()249- nonce = header_dict["nonce"].encode()250- qop = header_dict["qop"].encode() if "qop" in header_dict else None251- opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None252- algorithm = header_dict.get("algorithm")253- return cls(254- realm=realm, nonce=nonce, qop=qop, opaque=opaque, algorithm=algorithm255- )