Skip to content
Myr

_auth.py

This file

Path

httpx/_auth.py

352 lines · 11.7 KiB · Python

Last changed by

add missing type hints to __init__(...) (#2938)Petr Belskiybefore adoption87f39f1

History of this file

Take it

1import hashlib2import os3import re4import time5import typing6from base64 import b64encode7from urllib.request import parse_http_list89from ._exceptions import ProtocolError10from ._models import Cookies, Request, Response11from ._utils import to_bytes, to_str, unquote1213if typing.TYPE_CHECKING:  # pragma: no cover14    from hashlib import _Hash151617class Auth:18    """19    Base class for all authentication schemes.2021    To implement a custom authentication scheme, subclass `Auth` and override22    the `.auth_flow()` method.2324    If the authentication scheme does I/O such as disk access or network calls, or uses25    synchronization primitives such as locks, you should override `.sync_auth_flow()`26    and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized27    implementations that will be used by `Client` and `AsyncClient` respectively.28    """2930    requires_request_body = False31    requires_response_body = False3233    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:34        """35        Execute the authentication flow.3637        To dispatch a request, `yield` it:3839        ```40        yield request41        ```4243        The client will `.send()` the response back into the flow generator. You can44        access it like so:4546        ```47        response = yield request48        ```4950        A `return` (or reaching the end of the generator) will result in the51        client returning the last response obtained from the server.5253        You can dispatch as many requests as is necessary.54        """55        yield request5657    def sync_auth_flow(58        self, request: Request59    ) -> typing.Generator[Request, Response, None]:60        """61        Execute the authentication flow synchronously.6263        By default, this defers to `.auth_flow()`. You should override this method64        when the authentication scheme does I/O and/or uses concurrency primitives.65        """66        if self.requires_request_body:67            request.read()6869        flow = self.auth_flow(request)70        request = next(flow)7172        while True:73            response = yield request74            if self.requires_response_body:75                response.read()7677            try:78                request = flow.send(response)79            except StopIteration:80                break8182    async def async_auth_flow(83        self, request: Request84    ) -> typing.AsyncGenerator[Request, Response]:85        """86        Execute the authentication flow asynchronously.8788        By default, this defers to `.auth_flow()`. You should override this method89        when the authentication scheme does I/O and/or uses concurrency primitives.90        """91        if self.requires_request_body:92            await request.aread()9394        flow = self.auth_flow(request)95        request = next(flow)9697        while True:98            response = yield request99            if self.requires_response_body:100                await response.aread()101102            try:103                request = flow.send(response)104            except StopIteration:105                break106107108class FunctionAuth(Auth):109    """110    Allows the 'auth' argument to be passed as a simple callable function,111    that takes the request, and returns a new, modified request.112    """113114    def __init__(self, func: typing.Callable[[Request], Request]) -> None:115        self._func = func116117    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:118        yield self._func(request)119120121class BasicAuth(Auth):122    """123    Allows the 'auth' argument to be passed as a (username, password) pair,124    and uses HTTP Basic authentication.125    """126127    def __init__(128        self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]129    ) -> None:130        self._auth_header = self._build_auth_header(username, password)131132    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:133        request.headers["Authorization"] = self._auth_header134        yield request135136    def _build_auth_header(137        self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]138    ) -> str:139        userpass = b":".join((to_bytes(username), to_bytes(password)))140        token = b64encode(userpass).decode()141        return f"Basic {token}"142143144class NetRCAuth(Auth):145    """146    Use a 'netrc' file to lookup basic auth credentials based on the url host.147    """148149    def __init__(self, file: typing.Optional[str] = None) -> None:150        # Lazily import 'netrc'.151        # There's no need for us to load this module unless 'NetRCAuth' is being used.152        import netrc153154        self._netrc_info = netrc.netrc(file)155156    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:157        auth_info = self._netrc_info.authenticators(request.url.host)158        if auth_info is None or not auth_info[2]:159            # The netrc file did not have authentication credentials for this host.160            yield request161        else:162            # Build a basic auth header with credentials from the netrc file.163            request.headers["Authorization"] = self._build_auth_header(164                username=auth_info[0], password=auth_info[2]165            )166            yield request167168    def _build_auth_header(169        self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]170    ) -> str:171        userpass = b":".join((to_bytes(username), to_bytes(password)))172        token = b64encode(userpass).decode()173        return f"Basic {token}"174175176class DigestAuth(Auth):177    _ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable[[bytes], "_Hash"]] = {178        "MD5": hashlib.md5,179        "MD5-SESS": hashlib.md5,180        "SHA": hashlib.sha1,181        "SHA-SESS": hashlib.sha1,182        "SHA-256": hashlib.sha256,183        "SHA-256-SESS": hashlib.sha256,184        "SHA-512": hashlib.sha512,185        "SHA-512-SESS": hashlib.sha512,186    }187188    def __init__(189        self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]190    ) -> None:191        self._username = to_bytes(username)192        self._password = to_bytes(password)193        self._last_challenge: typing.Optional[_DigestAuthChallenge] = None194        self._nonce_count = 1195196    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:197        if self._last_challenge:198            request.headers["Authorization"] = self._build_auth_header(199                request, self._last_challenge200            )201202        response = yield request203204        if response.status_code != 401 or "www-authenticate" not in response.headers:205            # If the response is not a 401 then we don't206            # need to build an authenticated request.207            return208209        for auth_header in response.headers.get_list("www-authenticate"):210            if auth_header.lower().startswith("digest "):211                break212        else:213            # If the response does not include a 'WWW-Authenticate: Digest ...'214            # header, then we don't need to build an authenticated request.215            return216217        self._last_challenge = self._parse_challenge(request, response, auth_header)218        self._nonce_count = 1219220        request.headers["Authorization"] = self._build_auth_header(221            request, self._last_challenge222        )223        if response.cookies:224            Cookies(response.cookies).set_cookie_header(request=request)225        yield request226227    def _parse_challenge(228        self, request: Request, response: Response, auth_header: str229    ) -> "_DigestAuthChallenge":230        """231        Returns a challenge from a Digest WWW-Authenticate header.232        These take the form of:233        `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"`234        """235        scheme, _, fields = auth_header.partition(" ")236237        # This method should only ever have been called with a Digest auth header.238        assert scheme.lower() == "digest"239240        header_dict: typing.Dict[str, str] = {}241        for field in parse_http_list(fields):242            key, value = field.strip().split("=", 1)243            header_dict[key] = unquote(value)244245        try:246            realm = header_dict["realm"].encode()247            nonce = header_dict["nonce"].encode()248            algorithm = header_dict.get("algorithm", "MD5")249            opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None250            qop = header_dict["qop"].encode() if "qop" in header_dict else None251            return _DigestAuthChallenge(252                realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop253            )254        except KeyError as exc:255            message = "Malformed Digest WWW-Authenticate header"256            raise ProtocolError(message, request=request) from exc257258    def _build_auth_header(259        self, request: Request, challenge: "_DigestAuthChallenge"260    ) -> str:261        hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()]262263        def digest(data: bytes) -> bytes:264            return hash_func(data).hexdigest().encode()265266        A1 = b":".join((self._username, challenge.realm, self._password))267268        path = request.url.raw_path269        A2 = b":".join((request.method.encode(), path))270        # TODO: implement auth-int271        HA2 = digest(A2)272273        nc_value = b"%08x" % self._nonce_count274        cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce)275        self._nonce_count += 1276277        HA1 = digest(A1)278        if challenge.algorithm.lower().endswith("-sess"):279            HA1 = digest(b":".join((HA1, challenge.nonce, cnonce)))280281        qop = self._resolve_qop(challenge.qop, request=request)282        if qop is None:283            digest_data = [HA1, challenge.nonce, HA2]284        else:285            digest_data = [challenge.nonce, nc_value, cnonce, qop, HA2]286        key_digest = b":".join(digest_data)287288        format_args = {289            "username": self._username,290            "realm": challenge.realm,291            "nonce": challenge.nonce,292            "uri": path,293            "response": digest(b":".join((HA1, key_digest))),294            "algorithm": challenge.algorithm.encode(),295        }296        if challenge.opaque:297            format_args["opaque"] = challenge.opaque298        if qop:299            format_args["qop"] = b"auth"300            format_args["nc"] = nc_value301            format_args["cnonce"] = cnonce302303        return "Digest " + self._get_header_value(format_args)304305    def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes:306        s = str(nonce_count).encode()307        s += nonce308        s += time.ctime().encode()309        s += os.urandom(8)310311        return hashlib.sha1(s).hexdigest()[:16].encode()312313    def _get_header_value(self, header_fields: typing.Dict[str, bytes]) -> str:314        NON_QUOTED_FIELDS = ("algorithm", "qop", "nc")315        QUOTED_TEMPLATE = '{}="{}"'316        NON_QUOTED_TEMPLATE = "{}={}"317318        header_value = ""319        for i, (field, value) in enumerate(header_fields.items()):320            if i > 0:321                header_value += ", "322            template = (323                QUOTED_TEMPLATE324                if field not in NON_QUOTED_FIELDS325                else NON_QUOTED_TEMPLATE326            )327            header_value += template.format(field, to_str(value))328329        return header_value330331    def _resolve_qop(332        self, qop: typing.Optional[bytes], request: Request333    ) -> typing.Optional[bytes]:334        if qop is None:335            return None336        qops = re.split(b", ?", qop)337        if b"auth" in qops:338            return b"auth"339340        if qops == [b"auth-int"]:341            raise NotImplementedError("Digest auth-int support is not yet implemented")342343        message = f'Unexpected qop value "{qop!r}" in digest auth'344        raise ProtocolError(message, request=request)345346347class _DigestAuthChallenge(typing.NamedTuple):348    realm: bytes349    nonce: bytes350    algorithm: str351    opaque: typing.Optional[bytes]352    qop: typing.Optional[bytes]