Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

610 lines · 19.4 KiB · Python

Last changed by

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

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, JSONStream2021from ..common import FIXTURES_DIR222324def get_header_value(headers, key, default=None):25    lookup = key.encode("ascii").lower()26    for header_key, header_value in headers:27        if header_key.lower() == lookup:28            return header_value.decode("ascii")29    return default303132class MockTransport:33    def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:34        self.auth_header = auth_header35        self.status_code = status_code3637    def _request(38        self,39        method: bytes,40        url: typing.Tuple[bytes, bytes, int, bytes],41        headers: typing.List[typing.Tuple[bytes, bytes]],42        stream: ContentStream,43        timeout: typing.Mapping[str, typing.Optional[float]] = None,44    ) -> typing.Tuple[45        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream46    ]:47        authorization = get_header_value(headers, "Authorization")48        response_headers = (49            [(b"www-authenticate", self.auth_header)] if self.auth_header else []50        )51        response_stream = JSONStream({"auth": authorization})52        return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream535455class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):56    async def request(57        self, *args, **kwargs58    ) -> typing.Tuple[59        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream60    ]:61        return self._request(*args, **kwargs)626364class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):65    def request(66        self, *args, **kwargs67    ) -> typing.Tuple[68        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream69    ]:70        return self._request(*args, **kwargs)717273class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):74    def __init__(75        self,76        algorithm: str = "SHA-256",77        send_response_after_attempt: int = 1,78        qop: str = "auth",79        regenerate_nonce: bool = True,80    ) -> None:81        self.algorithm = algorithm82        self.send_response_after_attempt = send_response_after_attempt83        self.qop = qop84        self._regenerate_nonce = regenerate_nonce85        self._response_count = 08687    async def request(88        self,89        method: bytes,90        url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],91        headers: typing.List[typing.Tuple[bytes, bytes]] = None,92        stream: httpcore.AsyncByteStream = None,93        timeout: typing.Mapping[str, typing.Optional[float]] = None,94    ) -> typing.Tuple[95        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream96    ]:97        if self._response_count < self.send_response_after_attempt:98            assert headers is not None99            return self.challenge_send(method, headers)100101        authorization = get_header_value(headers, "Authorization")102        body = JSONStream({"auth": authorization})103        return b"HTTP/1.1", 200, b"", [], body104105    def challenge_send(106        self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]],107    ) -> typing.Tuple[108        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream109    ]:110        self._response_count += 1111        nonce = (112            hashlib.sha256(os.urandom(8)).hexdigest()113            if self._regenerate_nonce114            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"115        )116        challenge_data = {117            "nonce": nonce,118            "qop": self.qop,119            "opaque": (120                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"121            ),122            "algorithm": self.algorithm,123            "stale": "FALSE",124        }125        challenge_str = ", ".join(126            '{}="{}"'.format(key, value)127            for key, value in challenge_data.items()128            if value129        )130131        headers = [132            (133                b"www-authenticate",134                b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),135            )136        ]137        return b"HTTP/1.1", 401, b"", headers, ContentStream()138139140class RepeatAuth(Auth):141    """142    A mock authentication scheme that requires clients to send143    the request a fixed number of times, and then send a last request containing144    an aggregation of nonces that the server sent in 'WWW-Authenticate' headers145    of intermediate responses.146    """147148    requires_request_body = True149150    def __init__(self, repeat: int):151        self.repeat = repeat152153    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:154        nonces = []155156        for index in range(self.repeat):157            request.headers["Authorization"] = f"Repeat {index}"158            response = yield request159            nonces.append(response.headers["www-authenticate"])160161        key = ".".join(nonces)162        request.headers["Authorization"] = f"Repeat {key}"163        yield request164165166class ResponseBodyAuth(Auth):167    """168    A mock authentication scheme that requires clients to send an 'Authorization'169    header, then send back the contents of the response in the 'Authorization'170    header.171    """172173    requires_response_body = True174175    def __init__(self, token):176        self.token = token177178    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:179        request.headers["Authorization"] = self.token180        response = yield request181        data = response.text182        request.headers["Authorization"] = data183        yield request184185186@pytest.mark.asyncio187async def test_basic_auth() -> None:188    url = "https://example.org/"189    auth = ("tomchristie", "password123")190191    client = AsyncClient(transport=AsyncMockTransport())192    response = await client.get(url, auth=auth)193194    assert response.status_code == 200195    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}196197198@pytest.mark.asyncio199async def test_basic_auth_in_url() -> None:200    url = "https://tomchristie:password123@example.org/"201202    client = AsyncClient(transport=AsyncMockTransport())203    response = await client.get(url)204205    assert response.status_code == 200206    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}207208209@pytest.mark.asyncio210async def test_basic_auth_on_session() -> None:211    url = "https://example.org/"212    auth = ("tomchristie", "password123")213214    client = AsyncClient(transport=AsyncMockTransport(), auth=auth)215    response = await client.get(url)216217    assert response.status_code == 200218    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}219220221@pytest.mark.asyncio222async def test_custom_auth() -> None:223    url = "https://example.org/"224225    def auth(request: Request) -> Request:226        request.headers["Authorization"] = "Token 123"227        return request228229    client = AsyncClient(transport=AsyncMockTransport())230    response = await client.get(url, auth=auth)231232    assert response.status_code == 200233    assert response.json() == {"auth": "Token 123"}234235236@pytest.mark.asyncio237async def test_netrc_auth() -> None:238    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")239    url = "http://netrcexample.org"240241    client = AsyncClient(transport=AsyncMockTransport())242    response = await client.get(url)243244    assert response.status_code == 200245    assert response.json() == {246        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"247    }248249250@pytest.mark.asyncio251async def test_auth_header_has_priority_over_netrc() -> None:252    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")253    url = "http://netrcexample.org"254255    client = AsyncClient(transport=AsyncMockTransport())256    response = await client.get(url, headers={"Authorization": "Override"})257258    assert response.status_code == 200259    assert response.json() == {"auth": "Override"}260261262@pytest.mark.asyncio263async def test_trust_env_auth() -> None:264    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")265    url = "http://netrcexample.org"266267    client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)268    response = await client.get(url)269270    assert response.status_code == 200271    assert response.json() == {"auth": None}272273    client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)274    response = await client.get(url)275276    assert response.status_code == 200277    assert response.json() == {278        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"279    }280281282def test_auth_hidden_url() -> None:283    url = "http://example-username:example-password@example.org/"284    expected = "URL('http://example-username:[secure]@example.org/')"285    assert url == URL(url)286    assert expected == repr(URL(url))287288289@pytest.mark.asyncio290async def test_auth_hidden_header() -> None:291    url = "https://example.org/"292    auth = ("example-username", "example-password")293294    client = AsyncClient(transport=AsyncMockTransport())295    response = await client.get(url, auth=auth)296297    assert "'authorization': '[secure]'" in str(response.request.headers)298299300@pytest.mark.asyncio301async def test_auth_invalid_type() -> None:302    url = "https://example.org/"303    client = AsyncClient(304        transport=AsyncMockTransport(),305        auth="not a tuple, not a callable",  # type: ignore306    )307    with pytest.raises(TypeError):308        await client.get(url)309310311@pytest.mark.asyncio312async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:313    url = "https://example.org/"314    auth = DigestAuth(username="tomchristie", password="password123")315316    client = AsyncClient(transport=AsyncMockTransport())317    response = await client.get(url, auth=auth)318319    assert response.status_code == 200320    assert response.json() == {"auth": None}321    assert len(response.history) == 0322323324@pytest.mark.asyncio325async def test_digest_auth_200_response_including_digest_auth_header() -> None:326    url = "https://example.org/"327    auth = DigestAuth(username="tomchristie", password="password123")328    auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'329330    client = AsyncClient(331        transport=AsyncMockTransport(auth_header=auth_header, status_code=200)332    )333    response = await client.get(url, auth=auth)334335    assert response.status_code == 200336    assert response.json() == {"auth": None}337    assert len(response.history) == 0338339340@pytest.mark.asyncio341async def test_digest_auth_401_response_without_digest_auth_header() -> None:342    url = "https://example.org/"343    auth = DigestAuth(username="tomchristie", password="password123")344345    client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))346    response = await client.get(url, auth=auth)347348    assert response.status_code == 401349    assert response.json() == {"auth": None}350    assert len(response.history) == 0351352353@pytest.mark.parametrize(354    "algorithm,expected_hash_length,expected_response_length",355    [356        ("MD5", 64, 32),357        ("MD5-SESS", 64, 32),358        ("SHA", 64, 40),359        ("SHA-SESS", 64, 40),360        ("SHA-256", 64, 64),361        ("SHA-256-SESS", 64, 64),362        ("SHA-512", 64, 128),363        ("SHA-512-SESS", 64, 128),364    ],365)366@pytest.mark.asyncio367async def test_digest_auth(368    algorithm: str, expected_hash_length: int, expected_response_length: int369) -> None:370    url = "https://example.org/"371    auth = DigestAuth(username="tomchristie", password="password123")372373    client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))374    response = await client.get(url, auth=auth)375376    assert response.status_code == 200377    assert len(response.history) == 1378379    authorization = typing.cast(dict, response.json())["auth"]380    scheme, _, fields = authorization.partition(" ")381    assert scheme == "Digest"382383    response_fields = [field.strip() for field in fields.split(",")]384    digest_data = dict(field.split("=") for field in response_fields)385386    assert digest_data["username"] == '"tomchristie"'387    assert digest_data["realm"] == '"httpx@example.org"'388    assert "nonce" in digest_data389    assert digest_data["uri"] == '"/"'390    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes391    assert len(digest_data["opaque"]) == expected_hash_length + 2392    assert digest_data["algorithm"] == algorithm393    assert digest_data["qop"] == "auth"394    assert digest_data["nc"] == "00000001"395    assert len(digest_data["cnonce"]) == 16 + 2396397398@pytest.mark.asyncio399async def test_digest_auth_no_specified_qop() -> None:400    url = "https://example.org/"401    auth = DigestAuth(username="tomchristie", password="password123")402403    client = AsyncClient(transport=MockDigestAuthTransport(qop=""))404    response = await client.get(url, auth=auth)405406    assert response.status_code == 200407    assert len(response.history) == 1408409    authorization = typing.cast(dict, response.json())["auth"]410    scheme, _, fields = authorization.partition(" ")411    assert scheme == "Digest"412413    response_fields = [field.strip() for field in fields.split(",")]414    digest_data = dict(field.split("=") for field in response_fields)415416    assert "qop" not in digest_data417    assert "nc" not in digest_data418    assert "cnonce" not in digest_data419    assert digest_data["username"] == '"tomchristie"'420    assert digest_data["realm"] == '"httpx@example.org"'421    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes422    assert digest_data["uri"] == '"/"'423    assert len(digest_data["response"]) == 64 + 2424    assert len(digest_data["opaque"]) == 64 + 2425    assert digest_data["algorithm"] == "SHA-256"426427428@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))429@pytest.mark.asyncio430async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:431    url = "https://example.org/"432    auth = DigestAuth(username="tomchristie", password="password123")433434    client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))435    response = await client.get(url, auth=auth)436437    assert response.status_code == 200438    assert len(response.history) == 1439440441@pytest.mark.asyncio442async def test_digest_auth_qop_auth_int_not_implemented() -> None:443    url = "https://example.org/"444    auth = DigestAuth(username="tomchristie", password="password123")445    client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))446447    with pytest.raises(NotImplementedError):448        await client.get(url, auth=auth)449450451@pytest.mark.asyncio452async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:453    url = "https://example.org/"454    auth = DigestAuth(username="tomchristie", password="password123")455    client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))456457    with pytest.raises(ProtocolError):458        await client.get(url, auth=auth)459460461@pytest.mark.asyncio462async def test_digest_auth_incorrect_credentials() -> None:463    url = "https://example.org/"464    auth = DigestAuth(username="tomchristie", password="password123")465466    client = AsyncClient(467        transport=MockDigestAuthTransport(send_response_after_attempt=2)468    )469    response = await client.get(url, auth=auth)470471    assert response.status_code == 401472    assert len(response.history) == 1473474475@pytest.mark.parametrize(476    "auth_header",477    [478        b'Digest realm="httpx@example.org", qop="auth"',  # missing fields479        b'realm="httpx@example.org", qop="auth"',  # not starting with Digest480        b'DigestZ realm="httpx@example.org", qop="auth"'481        b'qop="auth,auth-int",nonce="abc",opaque="xyz"',482        b'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list483    ],484)485@pytest.mark.asyncio486async def test_async_digest_auth_raises_protocol_error_on_malformed_header(487    auth_header: bytes,488) -> None:489    url = "https://example.org/"490    auth = DigestAuth(username="tomchristie", password="password123")491    client = AsyncClient(492        transport=AsyncMockTransport(auth_header=auth_header, status_code=401)493    )494495    with pytest.raises(ProtocolError):496        await client.get(url, auth=auth)497498499@pytest.mark.parametrize(500    "auth_header",501    [502        b'Digest realm="httpx@example.org", qop="auth"',  # missing fields503        b'realm="httpx@example.org", qop="auth"',  # not starting with Digest504        b'DigestZ realm="httpx@example.org", qop="auth"'505        b'qop="auth,auth-int",nonce="abc",opaque="xyz"',506        b'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list507    ],508)509def test_sync_digest_auth_raises_protocol_error_on_malformed_header(510    auth_header: bytes,511) -> None:512    url = "https://example.org/"513    auth = DigestAuth(username="tomchristie", password="password123")514    client = Client(515        transport=SyncMockTransport(auth_header=auth_header, status_code=401)516    )517518    with pytest.raises(ProtocolError):519        client.get(url, auth=auth)520521522@pytest.mark.asyncio523async def test_async_auth_history() -> None:524    """525    Test that intermediate requests sent as part of an authentication flow526    are recorded in the response history.527    """528    url = "https://example.org/"529    auth = RepeatAuth(repeat=2)530    client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))531532    response = await client.get(url, auth=auth)533    assert response.status_code == 200534    assert response.json() == {"auth": "Repeat abc.abc"}535536    assert len(response.history) == 2537    resp1, resp2 = response.history538    assert resp1.json() == {"auth": "Repeat 0"}539    assert resp2.json() == {"auth": "Repeat 1"}540541    assert len(resp2.history) == 1542    assert resp2.history == [resp1]543544    assert len(resp1.history) == 0545546547def test_sync_auth_history() -> None:548    """549    Test that intermediate requests sent as part of an authentication flow550    are recorded in the response history.551    """552    url = "https://example.org/"553    auth = RepeatAuth(repeat=2)554    client = Client(transport=SyncMockTransport(auth_header=b"abc"))555556    response = client.get(url, auth=auth)557    assert response.status_code == 200558    assert response.json() == {"auth": "Repeat abc.abc"}559560    assert len(response.history) == 2561    resp1, resp2 = response.history562    assert resp1.json() == {"auth": "Repeat 0"}563    assert resp2.json() == {"auth": "Repeat 1"}564565    assert len(resp2.history) == 1566    assert resp2.history == [resp1]567568    assert len(resp1.history) == 0569570571@pytest.mark.asyncio572async def test_digest_auth_unavailable_streaming_body():573    url = "https://example.org/"574    auth = DigestAuth(username="tomchristie", password="password123")575    client = AsyncClient(transport=AsyncMockTransport())576577    async def streaming_body():578        yield b"Example request body"  # pragma: nocover579580    with pytest.raises(RequestBodyUnavailable):581        await client.post(url, data=streaming_body(), auth=auth)582583584@pytest.mark.asyncio585async def test_async_auth_reads_response_body() -> None:586    """587    Test that we can read the response body in an auth flow if `requires_response_body`588    is set.589    """590    url = "https://example.org/"591    auth = ResponseBodyAuth("xyz")592    client = AsyncClient(transport=AsyncMockTransport())593594    response = await client.get(url, auth=auth)595    assert response.status_code == 200596    assert response.json() == {"auth": '{"auth": "xyz"}'}597598599def test_sync_auth_reads_response_body() -> None:600    """601    Test that we can read the response body in an auth flow if `requires_response_body`602    is set.603    """604    url = "https://example.org/"605    auth = ResponseBodyAuth("xyz")606    client = Client(transport=SyncMockTransport())607608    response = client.get(url, auth=auth)609    assert response.status_code == 200610    assert response.json() == {"auth": '{"auth": "xyz"}'}