Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

465 lines · 14.8 KiB · Python

Last changed by

Dispatcher -> AsyncDispatcher (#725)Tom Christiebefore adoptione19bd9b

History of this file

Take it

1import hashlib2import json3import os4import typing56import pytest78from httpx import (9    URL,10    AsyncClient,11    DigestAuth,12    ProtocolError,13    Request,14    RequestBodyUnavailable,15    Response,16)17from httpx.auth import Auth, AuthFlow18from httpx.config import CertTypes, TimeoutTypes, VerifyTypes19from httpx.dispatch.base import AsyncDispatcher202122class MockDispatch(AsyncDispatcher):23    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:24        self.auth_header = auth_header25        self.status_code = status_code2627    async def send(28        self,29        request: Request,30        verify: VerifyTypes = None,31        cert: CertTypes = None,32        timeout: TimeoutTypes = None,33    ) -> Response:34        headers = [("www-authenticate", self.auth_header)] if self.auth_header else []35        body = json.dumps({"auth": request.headers.get("Authorization")}).encode()36        return Response(37            self.status_code, headers=headers, content=body, request=request38        )394041class MockDigestAuthDispatch(AsyncDispatcher):42    def __init__(43        self,44        algorithm: str = "SHA-256",45        send_response_after_attempt: int = 1,46        qop: str = "auth",47        regenerate_nonce: bool = True,48    ) -> None:49        self.algorithm = algorithm50        self.send_response_after_attempt = send_response_after_attempt51        self.qop = qop52        self._regenerate_nonce = regenerate_nonce53        self._response_count = 05455    async def send(56        self,57        request: Request,58        verify: VerifyTypes = None,59        cert: CertTypes = None,60        timeout: TimeoutTypes = None,61    ) -> Response:62        if self._response_count < self.send_response_after_attempt:63            return self.challenge_send(request)6465        body = json.dumps({"auth": request.headers.get("Authorization")}).encode()66        return Response(200, content=body, request=request)6768    def challenge_send(self, request: Request) -> Response:69        self._response_count += 170        nonce = (71            hashlib.sha256(os.urandom(8)).hexdigest()72            if self._regenerate_nonce73            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"74        )75        challenge_data = {76            "nonce": nonce,77            "qop": self.qop,78            "opaque": (79                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"80            ),81            "algorithm": self.algorithm,82            "stale": "FALSE",83        }84        challenge_str = ", ".join(85            '{}="{}"'.format(key, value)86            for key, value in challenge_data.items()87            if value88        )8990        headers = [91            ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)92        ]93        return Response(401, headers=headers, content=b"", request=request)949596@pytest.mark.asyncio97async def test_basic_auth() -> None:98    url = "https://example.org/"99    auth = ("tomchristie", "password123")100101    client = AsyncClient(dispatch=MockDispatch())102    response = await client.get(url, auth=auth)103104    assert response.status_code == 200105    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}106107108@pytest.mark.asyncio109async def test_basic_auth_in_url() -> None:110    url = "https://tomchristie:password123@example.org/"111112    client = AsyncClient(dispatch=MockDispatch())113    response = await client.get(url)114115    assert response.status_code == 200116    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}117118119@pytest.mark.asyncio120async def test_basic_auth_on_session() -> None:121    url = "https://example.org/"122    auth = ("tomchristie", "password123")123124    client = AsyncClient(dispatch=MockDispatch(), auth=auth)125    response = await client.get(url)126127    assert response.status_code == 200128    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}129130131@pytest.mark.asyncio132async def test_custom_auth() -> None:133    url = "https://example.org/"134135    def auth(request: Request) -> Request:136        request.headers["Authorization"] = "Token 123"137        return request138139    client = AsyncClient(dispatch=MockDispatch())140    response = await client.get(url, auth=auth)141142    assert response.status_code == 200143    assert response.json() == {"auth": "Token 123"}144145146@pytest.mark.asyncio147async def test_netrc_auth() -> None:148    os.environ["NETRC"] = "tests/.netrc"149    url = "http://netrcexample.org"150151    client = AsyncClient(dispatch=MockDispatch())152    response = await client.get(url)153154    assert response.status_code == 200155    assert response.json() == {156        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"157    }158159160@pytest.mark.asyncio161async def test_auth_header_has_priority_over_netrc() -> None:162    os.environ["NETRC"] = "tests/.netrc"163    url = "http://netrcexample.org"164165    client = AsyncClient(dispatch=MockDispatch())166    response = await client.get(url, headers={"Authorization": "Override"})167168    assert response.status_code == 200169    assert response.json() == {"auth": "Override"}170171172@pytest.mark.asyncio173async def test_trust_env_auth() -> None:174    os.environ["NETRC"] = "tests/.netrc"175    url = "http://netrcexample.org"176177    client = AsyncClient(dispatch=MockDispatch(), trust_env=False)178    response = await client.get(url)179180    assert response.status_code == 200181    assert response.json() == {"auth": None}182183    client = AsyncClient(dispatch=MockDispatch(), trust_env=True)184    response = await client.get(url)185186    assert response.status_code == 200187    assert response.json() == {188        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"189    }190191192def test_auth_hidden_url() -> None:193    url = "http://example-username:example-password@example.org/"194    expected = "URL('http://example-username:[secure]@example.org/')"195    assert url == URL(url)196    assert expected == repr(URL(url))197198199@pytest.mark.asyncio200async def test_auth_hidden_header() -> None:201    url = "https://example.org/"202    auth = ("example-username", "example-password")203204    client = AsyncClient(dispatch=MockDispatch())205    response = await client.get(url, auth=auth)206207    assert "'authorization': '[secure]'" in str(response.request.headers)208209210@pytest.mark.asyncio211async def test_auth_invalid_type() -> None:212    url = "https://example.org/"213    client = AsyncClient(214        dispatch=MockDispatch(), auth="not a tuple, not a callable",  # type: ignore215    )216    with pytest.raises(TypeError):217        await client.get(url)218219220@pytest.mark.asyncio221async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:222    url = "https://example.org/"223    auth = DigestAuth(username="tomchristie", password="password123")224225    client = AsyncClient(dispatch=MockDispatch())226    response = await client.get(url, auth=auth)227228    assert response.status_code == 200229    assert response.json() == {"auth": None}230    assert len(response.history) == 0231232233@pytest.mark.asyncio234async def test_digest_auth_200_response_including_digest_auth_header() -> None:235    url = "https://example.org/"236    auth = DigestAuth(username="tomchristie", password="password123")237    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'238239    client = AsyncClient(240        dispatch=MockDispatch(auth_header=auth_header, status_code=200)241    )242    response = await client.get(url, auth=auth)243244    assert response.status_code == 200245    assert response.json() == {"auth": None}246    assert len(response.history) == 0247248249@pytest.mark.asyncio250async def test_digest_auth_401_response_without_digest_auth_header() -> None:251    url = "https://example.org/"252    auth = DigestAuth(username="tomchristie", password="password123")253254    client = AsyncClient(dispatch=MockDispatch(auth_header="", status_code=401))255    response = await client.get(url, auth=auth)256257    assert response.status_code == 401258    assert response.json() == {"auth": None}259    assert len(response.history) == 0260261262@pytest.mark.parametrize(263    "algorithm,expected_hash_length,expected_response_length",264    [265        ("MD5", 64, 32),266        ("MD5-SESS", 64, 32),267        ("SHA", 64, 40),268        ("SHA-SESS", 64, 40),269        ("SHA-256", 64, 64),270        ("SHA-256-SESS", 64, 64),271        ("SHA-512", 64, 128),272        ("SHA-512-SESS", 64, 128),273    ],274)275@pytest.mark.asyncio276async def test_digest_auth(277    algorithm: str, expected_hash_length: int, expected_response_length: int278) -> None:279    url = "https://example.org/"280    auth = DigestAuth(username="tomchristie", password="password123")281282    client = AsyncClient(dispatch=MockDigestAuthDispatch(algorithm=algorithm))283    response = await client.get(url, auth=auth)284285    assert response.status_code == 200286    assert len(response.history) == 1287288    authorization = typing.cast(dict, response.json())["auth"]289    scheme, _, fields = authorization.partition(" ")290    assert scheme == "Digest"291292    response_fields = [field.strip() for field in fields.split(",")]293    digest_data = dict(field.split("=") for field in response_fields)294295    assert digest_data["username"] == '"tomchristie"'296    assert digest_data["realm"] == '"httpx@example.org"'297    assert "nonce" in digest_data298    assert digest_data["uri"] == '"/"'299    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes300    assert len(digest_data["opaque"]) == expected_hash_length + 2301    assert digest_data["algorithm"] == algorithm302    assert digest_data["qop"] == "auth"303    assert digest_data["nc"] == "00000001"304    assert len(digest_data["cnonce"]) == 16 + 2305306307@pytest.mark.asyncio308async def test_digest_auth_no_specified_qop() -> None:309    url = "https://example.org/"310    auth = DigestAuth(username="tomchristie", password="password123")311312    client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=""))313    response = await client.get(url, auth=auth)314315    assert response.status_code == 200316    assert len(response.history) == 1317318    authorization = typing.cast(dict, response.json())["auth"]319    scheme, _, fields = authorization.partition(" ")320    assert scheme == "Digest"321322    response_fields = [field.strip() for field in fields.split(",")]323    digest_data = dict(field.split("=") for field in response_fields)324325    assert "qop" not in digest_data326    assert "nc" not in digest_data327    assert "cnonce" not in digest_data328    assert digest_data["username"] == '"tomchristie"'329    assert digest_data["realm"] == '"httpx@example.org"'330    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes331    assert digest_data["uri"] == '"/"'332    assert len(digest_data["response"]) == 64 + 2333    assert len(digest_data["opaque"]) == 64 + 2334    assert digest_data["algorithm"] == "SHA-256"335336337@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))338@pytest.mark.asyncio339async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:340    url = "https://example.org/"341    auth = DigestAuth(username="tomchristie", password="password123")342343    client = AsyncClient(dispatch=MockDigestAuthDispatch(qop=qop))344    response = await client.get(url, auth=auth)345346    assert response.status_code == 200347    assert len(response.history) == 1348349350@pytest.mark.asyncio351async def test_digest_auth_qop_auth_int_not_implemented() -> None:352    url = "https://example.org/"353    auth = DigestAuth(username="tomchristie", password="password123")354    client = AsyncClient(dispatch=MockDigestAuthDispatch(qop="auth-int"))355356    with pytest.raises(NotImplementedError):357        await client.get(url, auth=auth)358359360@pytest.mark.asyncio361async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:362    url = "https://example.org/"363    auth = DigestAuth(username="tomchristie", password="password123")364    client = AsyncClient(dispatch=MockDigestAuthDispatch(qop="not-auth"))365366    with pytest.raises(ProtocolError):367        await client.get(url, auth=auth)368369370@pytest.mark.asyncio371async def test_digest_auth_incorrect_credentials() -> None:372    url = "https://example.org/"373    auth = DigestAuth(username="tomchristie", password="password123")374375    client = AsyncClient(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))376    response = await client.get(url, auth=auth)377378    assert response.status_code == 401379    assert len(response.history) == 1380381382@pytest.mark.parametrize(383    "auth_header",384    [385        'Digest realm="httpx@example.org", qop="auth"',  # missing fields386        'realm="httpx@example.org", qop="auth"',  # not starting with Digest387        'DigestZ realm="httpx@example.org", qop="auth"'388        'qop="auth,auth-int",nonce="abc",opaque="xyz"',389        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list390    ],391)392@pytest.mark.asyncio393async def test_digest_auth_raises_protocol_error_on_malformed_header(394    auth_header: str,395) -> None:396    url = "https://example.org/"397    auth = DigestAuth(username="tomchristie", password="password123")398    client = AsyncClient(399        dispatch=MockDispatch(auth_header=auth_header, status_code=401)400    )401402    with pytest.raises(ProtocolError):403        await client.get(url, auth=auth)404405406@pytest.mark.asyncio407async def test_auth_history() -> None:408    """409    Test that intermediate requests sent as part of an authentication flow410    are recorded in the response history.411    """412413    class RepeatAuth(Auth):414        """415        A mock authentication scheme that requires clients to send416        the request a fixed number of times, and then send a last request containing417        an aggregation of nonces that the server sent in 'WWW-Authenticate' headers418        of intermediate responses.419        """420421        def __init__(self, repeat: int):422            self.repeat = repeat423424        def __call__(self, request: Request) -> AuthFlow:425            nonces = []426427            for index in range(self.repeat):428                request.headers["Authorization"] = f"Repeat {index}"429                response = yield request430                nonces.append(response.headers["www-authenticate"])431432            key = ".".join(nonces)433            request.headers["Authorization"] = f"Repeat {key}"434            yield request435436    url = "https://example.org/"437    auth = RepeatAuth(repeat=2)438    client = AsyncClient(dispatch=MockDispatch(auth_header="abc"))439440    response = await client.get(url, auth=auth)441    assert response.status_code == 200442    assert response.json() == {"auth": "Repeat abc.abc"}443444    assert len(response.history) == 2445    resp1, resp2 = response.history446    assert resp1.json() == {"auth": "Repeat 0"}447    assert resp2.json() == {"auth": "Repeat 1"}448449    assert len(resp2.history) == 1450    assert resp2.history == [resp1]451452    assert len(resp1.history) == 0453454455@pytest.mark.asyncio456async def test_digest_auth_unavailable_streaming_body():457    url = "https://example.org/"458    auth = DigestAuth(username="tomchristie", password="password123")459    client = AsyncClient(dispatch=MockDispatch())460461    async def streaming_body():462        yield b"Example request body"463464    with pytest.raises(RequestBodyUnavailable):465        await client.post(url, data=streaming_body(), auth=auth)