Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

608 lines · 19.3 KiB · Python

Last changed by

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

History of this file

Take it

1import hashlib2import os3import typing45import httpcore6import pytest78from httpx import (9    URL,10    AsyncClient,11    Auth,12    Client,13    DigestAuth,14    ProtocolError,15    Request,16    RequestBodyUnavailable,17    Response,18)19from httpx._content_streams import ContentStream, JSONStream202122def get_header_value(headers, key, default=None):23    lookup = key.encode("ascii").lower()24    for header_key, header_value in headers:25        if header_key.lower() == lookup:26            return header_value.decode("ascii")27    return default282930class MockTransport:31    def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:32        self.auth_header = auth_header33        self.status_code = status_code3435    def _request(36        self,37        method: bytes,38        url: typing.Tuple[bytes, bytes, int, bytes],39        headers: typing.List[typing.Tuple[bytes, bytes]],40        stream: ContentStream,41        timeout: typing.Dict[str, typing.Optional[float]] = None,42    ) -> typing.Tuple[43        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream44    ]:45        authorization = get_header_value(headers, "Authorization")46        response_headers = (47            [(b"www-authenticate", self.auth_header)] if self.auth_header else []48        )49        response_stream = JSONStream({"auth": authorization})50        return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream515253class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):54    async def request(55        self, *args, **kwargs56    ) -> typing.Tuple[57        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream58    ]:59        return self._request(*args, **kwargs)606162class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):63    def request(64        self, *args, **kwargs65    ) -> typing.Tuple[66        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream67    ]:68        return self._request(*args, **kwargs)697071class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):72    def __init__(73        self,74        algorithm: str = "SHA-256",75        send_response_after_attempt: int = 1,76        qop: str = "auth",77        regenerate_nonce: bool = True,78    ) -> None:79        self.algorithm = algorithm80        self.send_response_after_attempt = send_response_after_attempt81        self.qop = qop82        self._regenerate_nonce = regenerate_nonce83        self._response_count = 08485    async def request(86        self,87        method: bytes,88        url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],89        headers: typing.List[typing.Tuple[bytes, bytes]] = None,90        stream: httpcore.AsyncByteStream = None,91        timeout: typing.Dict[str, typing.Optional[float]] = None,92    ) -> typing.Tuple[93        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream94    ]:95        if self._response_count < self.send_response_after_attempt:96            assert headers is not None97            return self.challenge_send(method, headers)9899        authorization = get_header_value(headers, "Authorization")100        body = JSONStream({"auth": authorization})101        return b"HTTP/1.1", 200, b"", [], body102103    def challenge_send(104        self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]],105    ) -> typing.Tuple[106        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream107    ]:108        self._response_count += 1109        nonce = (110            hashlib.sha256(os.urandom(8)).hexdigest()111            if self._regenerate_nonce112            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"113        )114        challenge_data = {115            "nonce": nonce,116            "qop": self.qop,117            "opaque": (118                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"119            ),120            "algorithm": self.algorithm,121            "stale": "FALSE",122        }123        challenge_str = ", ".join(124            '{}="{}"'.format(key, value)125            for key, value in challenge_data.items()126            if value127        )128129        headers = [130            (131                b"www-authenticate",132                b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),133            )134        ]135        return b"HTTP/1.1", 401, b"", headers, ContentStream()136137138class RepeatAuth(Auth):139    """140    A mock authentication scheme that requires clients to send141    the request a fixed number of times, and then send a last request containing142    an aggregation of nonces that the server sent in 'WWW-Authenticate' headers143    of intermediate responses.144    """145146    requires_request_body = True147148    def __init__(self, repeat: int):149        self.repeat = repeat150151    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:152        nonces = []153154        for index in range(self.repeat):155            request.headers["Authorization"] = f"Repeat {index}"156            response = yield request157            nonces.append(response.headers["www-authenticate"])158159        key = ".".join(nonces)160        request.headers["Authorization"] = f"Repeat {key}"161        yield request162163164class ResponseBodyAuth(Auth):165    """166    A mock authentication scheme that requires clients to send an 'Authorization'167    header, then send back the contents of the response in the 'Authorization'168    header.169    """170171    requires_response_body = True172173    def __init__(self, token):174        self.token = token175176    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:177        request.headers["Authorization"] = self.token178        response = yield request179        data = response.text180        request.headers["Authorization"] = data181        yield request182183184@pytest.mark.asyncio185async def test_basic_auth() -> None:186    url = "https://example.org/"187    auth = ("tomchristie", "password123")188189    client = AsyncClient(transport=AsyncMockTransport())190    response = await client.get(url, auth=auth)191192    assert response.status_code == 200193    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}194195196@pytest.mark.asyncio197async def test_basic_auth_in_url() -> None:198    url = "https://tomchristie:password123@example.org/"199200    client = AsyncClient(transport=AsyncMockTransport())201    response = await client.get(url)202203    assert response.status_code == 200204    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}205206207@pytest.mark.asyncio208async def test_basic_auth_on_session() -> None:209    url = "https://example.org/"210    auth = ("tomchristie", "password123")211212    client = AsyncClient(transport=AsyncMockTransport(), auth=auth)213    response = await client.get(url)214215    assert response.status_code == 200216    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}217218219@pytest.mark.asyncio220async def test_custom_auth() -> None:221    url = "https://example.org/"222223    def auth(request: Request) -> Request:224        request.headers["Authorization"] = "Token 123"225        return request226227    client = AsyncClient(transport=AsyncMockTransport())228    response = await client.get(url, auth=auth)229230    assert response.status_code == 200231    assert response.json() == {"auth": "Token 123"}232233234@pytest.mark.asyncio235async def test_netrc_auth() -> None:236    os.environ["NETRC"] = "tests/.netrc"237    url = "http://netrcexample.org"238239    client = AsyncClient(transport=AsyncMockTransport())240    response = await client.get(url)241242    assert response.status_code == 200243    assert response.json() == {244        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"245    }246247248@pytest.mark.asyncio249async def test_auth_header_has_priority_over_netrc() -> None:250    os.environ["NETRC"] = "tests/.netrc"251    url = "http://netrcexample.org"252253    client = AsyncClient(transport=AsyncMockTransport())254    response = await client.get(url, headers={"Authorization": "Override"})255256    assert response.status_code == 200257    assert response.json() == {"auth": "Override"}258259260@pytest.mark.asyncio261async def test_trust_env_auth() -> None:262    os.environ["NETRC"] = "tests/.netrc"263    url = "http://netrcexample.org"264265    client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)266    response = await client.get(url)267268    assert response.status_code == 200269    assert response.json() == {"auth": None}270271    client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)272    response = await client.get(url)273274    assert response.status_code == 200275    assert response.json() == {276        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"277    }278279280def test_auth_hidden_url() -> None:281    url = "http://example-username:example-password@example.org/"282    expected = "URL('http://example-username:[secure]@example.org/')"283    assert url == URL(url)284    assert expected == repr(URL(url))285286287@pytest.mark.asyncio288async def test_auth_hidden_header() -> None:289    url = "https://example.org/"290    auth = ("example-username", "example-password")291292    client = AsyncClient(transport=AsyncMockTransport())293    response = await client.get(url, auth=auth)294295    assert "'authorization': '[secure]'" in str(response.request.headers)296297298@pytest.mark.asyncio299async def test_auth_invalid_type() -> None:300    url = "https://example.org/"301    client = AsyncClient(302        transport=AsyncMockTransport(),303        auth="not a tuple, not a callable",  # type: ignore304    )305    with pytest.raises(TypeError):306        await client.get(url)307308309@pytest.mark.asyncio310async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:311    url = "https://example.org/"312    auth = DigestAuth(username="tomchristie", password="password123")313314    client = AsyncClient(transport=AsyncMockTransport())315    response = await client.get(url, auth=auth)316317    assert response.status_code == 200318    assert response.json() == {"auth": None}319    assert len(response.history) == 0320321322@pytest.mark.asyncio323async def test_digest_auth_200_response_including_digest_auth_header() -> None:324    url = "https://example.org/"325    auth = DigestAuth(username="tomchristie", password="password123")326    auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'327328    client = AsyncClient(329        transport=AsyncMockTransport(auth_header=auth_header, status_code=200)330    )331    response = await client.get(url, auth=auth)332333    assert response.status_code == 200334    assert response.json() == {"auth": None}335    assert len(response.history) == 0336337338@pytest.mark.asyncio339async def test_digest_auth_401_response_without_digest_auth_header() -> None:340    url = "https://example.org/"341    auth = DigestAuth(username="tomchristie", password="password123")342343    client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))344    response = await client.get(url, auth=auth)345346    assert response.status_code == 401347    assert response.json() == {"auth": None}348    assert len(response.history) == 0349350351@pytest.mark.parametrize(352    "algorithm,expected_hash_length,expected_response_length",353    [354        ("MD5", 64, 32),355        ("MD5-SESS", 64, 32),356        ("SHA", 64, 40),357        ("SHA-SESS", 64, 40),358        ("SHA-256", 64, 64),359        ("SHA-256-SESS", 64, 64),360        ("SHA-512", 64, 128),361        ("SHA-512-SESS", 64, 128),362    ],363)364@pytest.mark.asyncio365async def test_digest_auth(366    algorithm: str, expected_hash_length: int, expected_response_length: int367) -> None:368    url = "https://example.org/"369    auth = DigestAuth(username="tomchristie", password="password123")370371    client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))372    response = await client.get(url, auth=auth)373374    assert response.status_code == 200375    assert len(response.history) == 1376377    authorization = typing.cast(dict, response.json())["auth"]378    scheme, _, fields = authorization.partition(" ")379    assert scheme == "Digest"380381    response_fields = [field.strip() for field in fields.split(",")]382    digest_data = dict(field.split("=") for field in response_fields)383384    assert digest_data["username"] == '"tomchristie"'385    assert digest_data["realm"] == '"httpx@example.org"'386    assert "nonce" in digest_data387    assert digest_data["uri"] == '"/"'388    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes389    assert len(digest_data["opaque"]) == expected_hash_length + 2390    assert digest_data["algorithm"] == algorithm391    assert digest_data["qop"] == "auth"392    assert digest_data["nc"] == "00000001"393    assert len(digest_data["cnonce"]) == 16 + 2394395396@pytest.mark.asyncio397async def test_digest_auth_no_specified_qop() -> None:398    url = "https://example.org/"399    auth = DigestAuth(username="tomchristie", password="password123")400401    client = AsyncClient(transport=MockDigestAuthTransport(qop=""))402    response = await client.get(url, auth=auth)403404    assert response.status_code == 200405    assert len(response.history) == 1406407    authorization = typing.cast(dict, response.json())["auth"]408    scheme, _, fields = authorization.partition(" ")409    assert scheme == "Digest"410411    response_fields = [field.strip() for field in fields.split(",")]412    digest_data = dict(field.split("=") for field in response_fields)413414    assert "qop" not in digest_data415    assert "nc" not in digest_data416    assert "cnonce" not in digest_data417    assert digest_data["username"] == '"tomchristie"'418    assert digest_data["realm"] == '"httpx@example.org"'419    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes420    assert digest_data["uri"] == '"/"'421    assert len(digest_data["response"]) == 64 + 2422    assert len(digest_data["opaque"]) == 64 + 2423    assert digest_data["algorithm"] == "SHA-256"424425426@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))427@pytest.mark.asyncio428async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:429    url = "https://example.org/"430    auth = DigestAuth(username="tomchristie", password="password123")431432    client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))433    response = await client.get(url, auth=auth)434435    assert response.status_code == 200436    assert len(response.history) == 1437438439@pytest.mark.asyncio440async def test_digest_auth_qop_auth_int_not_implemented() -> None:441    url = "https://example.org/"442    auth = DigestAuth(username="tomchristie", password="password123")443    client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))444445    with pytest.raises(NotImplementedError):446        await client.get(url, auth=auth)447448449@pytest.mark.asyncio450async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:451    url = "https://example.org/"452    auth = DigestAuth(username="tomchristie", password="password123")453    client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))454455    with pytest.raises(ProtocolError):456        await client.get(url, auth=auth)457458459@pytest.mark.asyncio460async def test_digest_auth_incorrect_credentials() -> None:461    url = "https://example.org/"462    auth = DigestAuth(username="tomchristie", password="password123")463464    client = AsyncClient(465        transport=MockDigestAuthTransport(send_response_after_attempt=2)466    )467    response = await client.get(url, auth=auth)468469    assert response.status_code == 401470    assert len(response.history) == 1471472473@pytest.mark.parametrize(474    "auth_header",475    [476        b'Digest realm="httpx@example.org", qop="auth"',  # missing fields477        b'realm="httpx@example.org", qop="auth"',  # not starting with Digest478        b'DigestZ realm="httpx@example.org", qop="auth"'479        b'qop="auth,auth-int",nonce="abc",opaque="xyz"',480        b'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list481    ],482)483@pytest.mark.asyncio484async def test_async_digest_auth_raises_protocol_error_on_malformed_header(485    auth_header: bytes,486) -> None:487    url = "https://example.org/"488    auth = DigestAuth(username="tomchristie", password="password123")489    client = AsyncClient(490        transport=AsyncMockTransport(auth_header=auth_header, status_code=401)491    )492493    with pytest.raises(ProtocolError):494        await client.get(url, auth=auth)495496497@pytest.mark.parametrize(498    "auth_header",499    [500        b'Digest realm="httpx@example.org", qop="auth"',  # missing fields501        b'realm="httpx@example.org", qop="auth"',  # not starting with Digest502        b'DigestZ realm="httpx@example.org", qop="auth"'503        b'qop="auth,auth-int",nonce="abc",opaque="xyz"',504        b'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list505    ],506)507def test_sync_digest_auth_raises_protocol_error_on_malformed_header(508    auth_header: bytes,509) -> None:510    url = "https://example.org/"511    auth = DigestAuth(username="tomchristie", password="password123")512    client = Client(513        transport=SyncMockTransport(auth_header=auth_header, status_code=401)514    )515516    with pytest.raises(ProtocolError):517        client.get(url, auth=auth)518519520@pytest.mark.asyncio521async def test_async_auth_history() -> None:522    """523    Test that intermediate requests sent as part of an authentication flow524    are recorded in the response history.525    """526    url = "https://example.org/"527    auth = RepeatAuth(repeat=2)528    client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))529530    response = await client.get(url, auth=auth)531    assert response.status_code == 200532    assert response.json() == {"auth": "Repeat abc.abc"}533534    assert len(response.history) == 2535    resp1, resp2 = response.history536    assert resp1.json() == {"auth": "Repeat 0"}537    assert resp2.json() == {"auth": "Repeat 1"}538539    assert len(resp2.history) == 1540    assert resp2.history == [resp1]541542    assert len(resp1.history) == 0543544545def test_sync_auth_history() -> None:546    """547    Test that intermediate requests sent as part of an authentication flow548    are recorded in the response history.549    """550    url = "https://example.org/"551    auth = RepeatAuth(repeat=2)552    client = Client(transport=SyncMockTransport(auth_header=b"abc"))553554    response = client.get(url, auth=auth)555    assert response.status_code == 200556    assert response.json() == {"auth": "Repeat abc.abc"}557558    assert len(response.history) == 2559    resp1, resp2 = response.history560    assert resp1.json() == {"auth": "Repeat 0"}561    assert resp2.json() == {"auth": "Repeat 1"}562563    assert len(resp2.history) == 1564    assert resp2.history == [resp1]565566    assert len(resp1.history) == 0567568569@pytest.mark.asyncio570async def test_digest_auth_unavailable_streaming_body():571    url = "https://example.org/"572    auth = DigestAuth(username="tomchristie", password="password123")573    client = AsyncClient(transport=AsyncMockTransport())574575    async def streaming_body():576        yield b"Example request body"  # pragma: nocover577578    with pytest.raises(RequestBodyUnavailable):579        await client.post(url, data=streaming_body(), auth=auth)580581582@pytest.mark.asyncio583async def test_async_auth_reads_response_body() -> None:584    """585    Test that we can read the response body in an auth flow if `requires_response_body`586    is set.587    """588    url = "https://example.org/"589    auth = ResponseBodyAuth("xyz")590    client = AsyncClient(transport=AsyncMockTransport())591592    response = await client.get(url, auth=auth)593    assert response.status_code == 200594    assert response.json() == {"auth": '{"auth": "xyz"}'}595596597def test_sync_auth_reads_response_body() -> None:598    """599    Test that we can read the response body in an auth flow if `requires_response_body`600    is set.601    """602    url = "https://example.org/"603    auth = ResponseBodyAuth("xyz")604    client = Client(transport=SyncMockTransport())605606    response = client.get(url, auth=auth)607    assert response.status_code == 200608    assert response.json() == {"auth": '{"auth": "xyz"}'}