Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

643 lines · 20.4 KiB · Python

Last changed by

Add `Client.auth` setter (#1185)Florimond Mancabefore adoptioncb620e6

History of this file

Take it

1import hashlib2import os3import typing45import httpcore6import pytest78from httpx import (9    URL,10    AsyncClient,11    Auth,12    BasicAuth,13    Client,14    DigestAuth,15    ProtocolError,16    Request,17    RequestBodyUnavailable,18    Response,19)20from httpx._content_streams import ContentStream, JSONStream2122from ..common import FIXTURES_DIR232425def get_header_value(headers, key, default=None):26    lookup = key.encode("ascii").lower()27    for header_key, header_value in headers:28        if header_key.lower() == lookup:29            return header_value.decode("ascii")30    return default313233class MockTransport:34    def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:35        self.auth_header = auth_header36        self.status_code = status_code3738    def _request(39        self,40        method: bytes,41        url: typing.Tuple[bytes, bytes, int, bytes],42        headers: typing.List[typing.Tuple[bytes, bytes]],43        stream: ContentStream,44        timeout: typing.Mapping[str, typing.Optional[float]] = None,45    ) -> typing.Tuple[46        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream47    ]:48        authorization = get_header_value(headers, "Authorization")49        response_headers = (50            [(b"www-authenticate", self.auth_header)] if self.auth_header else []51        )52        response_stream = JSONStream({"auth": authorization})53        return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream545556class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):57    async def request(58        self, *args, **kwargs59    ) -> typing.Tuple[60        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream61    ]:62        return self._request(*args, **kwargs)636465class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):66    def request(67        self, *args, **kwargs68    ) -> typing.Tuple[69        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream70    ]:71        return self._request(*args, **kwargs)727374class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):75    def __init__(76        self,77        algorithm: str = "SHA-256",78        send_response_after_attempt: int = 1,79        qop: str = "auth",80        regenerate_nonce: bool = True,81    ) -> None:82        self.algorithm = algorithm83        self.send_response_after_attempt = send_response_after_attempt84        self.qop = qop85        self._regenerate_nonce = regenerate_nonce86        self._response_count = 08788    async def request(89        self,90        method: bytes,91        url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],92        headers: typing.List[typing.Tuple[bytes, bytes]] = None,93        stream: httpcore.AsyncByteStream = None,94        timeout: typing.Mapping[str, typing.Optional[float]] = None,95    ) -> typing.Tuple[96        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream97    ]:98        if self._response_count < self.send_response_after_attempt:99            assert headers is not None100            return self.challenge_send(method, headers)101102        authorization = get_header_value(headers, "Authorization")103        body = JSONStream({"auth": authorization})104        return b"HTTP/1.1", 200, b"", [], body105106    def challenge_send(107        self, method: bytes, headers: typing.List[typing.Tuple[bytes, bytes]],108    ) -> typing.Tuple[109        bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream110    ]:111        self._response_count += 1112        nonce = (113            hashlib.sha256(os.urandom(8)).hexdigest()114            if self._regenerate_nonce115            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"116        )117        challenge_data = {118            "nonce": nonce,119            "qop": self.qop,120            "opaque": (121                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"122            ),123            "algorithm": self.algorithm,124            "stale": "FALSE",125        }126        challenge_str = ", ".join(127            '{}="{}"'.format(key, value)128            for key, value in challenge_data.items()129            if value130        )131132        headers = [133            (134                b"www-authenticate",135                b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),136            )137        ]138        return b"HTTP/1.1", 401, b"", headers, ContentStream()139140141class RepeatAuth(Auth):142    """143    A mock authentication scheme that requires clients to send144    the request a fixed number of times, and then send a last request containing145    an aggregation of nonces that the server sent in 'WWW-Authenticate' headers146    of intermediate responses.147    """148149    requires_request_body = True150151    def __init__(self, repeat: int):152        self.repeat = repeat153154    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:155        nonces = []156157        for index in range(self.repeat):158            request.headers["Authorization"] = f"Repeat {index}"159            response = yield request160            nonces.append(response.headers["www-authenticate"])161162        key = ".".join(nonces)163        request.headers["Authorization"] = f"Repeat {key}"164        yield request165166167class ResponseBodyAuth(Auth):168    """169    A mock authentication scheme that requires clients to send an 'Authorization'170    header, then send back the contents of the response in the 'Authorization'171    header.172    """173174    requires_response_body = True175176    def __init__(self, token):177        self.token = token178179    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:180        request.headers["Authorization"] = self.token181        response = yield request182        data = response.text183        request.headers["Authorization"] = data184        yield request185186187@pytest.mark.asyncio188async def test_basic_auth() -> None:189    url = "https://example.org/"190    auth = ("tomchristie", "password123")191192    client = AsyncClient(transport=AsyncMockTransport())193    response = await client.get(url, auth=auth)194195    assert response.status_code == 200196    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}197198199@pytest.mark.asyncio200async def test_basic_auth_in_url() -> None:201    url = "https://tomchristie:password123@example.org/"202203    client = AsyncClient(transport=AsyncMockTransport())204    response = await client.get(url)205206    assert response.status_code == 200207    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}208209210@pytest.mark.asyncio211async def test_basic_auth_on_session() -> None:212    url = "https://example.org/"213    auth = ("tomchristie", "password123")214215    client = AsyncClient(transport=AsyncMockTransport(), auth=auth)216    response = await client.get(url)217218    assert response.status_code == 200219    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}220221222@pytest.mark.asyncio223async def test_custom_auth() -> None:224    url = "https://example.org/"225226    def auth(request: Request) -> Request:227        request.headers["Authorization"] = "Token 123"228        return request229230    client = AsyncClient(transport=AsyncMockTransport())231    response = await client.get(url, auth=auth)232233    assert response.status_code == 200234    assert response.json() == {"auth": "Token 123"}235236237@pytest.mark.asyncio238async def test_netrc_auth() -> None:239    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")240    url = "http://netrcexample.org"241242    client = AsyncClient(transport=AsyncMockTransport())243    response = await client.get(url)244245    assert response.status_code == 200246    assert response.json() == {247        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"248    }249250251@pytest.mark.asyncio252async def test_auth_header_has_priority_over_netrc() -> None:253    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")254    url = "http://netrcexample.org"255256    client = AsyncClient(transport=AsyncMockTransport())257    response = await client.get(url, headers={"Authorization": "Override"})258259    assert response.status_code == 200260    assert response.json() == {"auth": "Override"}261262263@pytest.mark.asyncio264async def test_trust_env_auth() -> None:265    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")266    url = "http://netrcexample.org"267268    client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)269    response = await client.get(url)270271    assert response.status_code == 200272    assert response.json() == {"auth": None}273274    client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)275    response = await client.get(url)276277    assert response.status_code == 200278    assert response.json() == {279        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280    }281282283@pytest.mark.asyncio284async def test_auth_disable_per_request() -> None:285    url = "https://example.org/"286    auth = ("tomchristie", "password123")287288    client = AsyncClient(transport=AsyncMockTransport(), auth=auth)289    response = await client.get(url, auth=None)290291    assert response.status_code == 200292    assert response.json() == {"auth": None}293294295def test_auth_hidden_url() -> None:296    url = "http://example-username:example-password@example.org/"297    expected = "URL('http://example-username:[secure]@example.org/')"298    assert url == URL(url)299    assert expected == repr(URL(url))300301302@pytest.mark.asyncio303async def test_auth_hidden_header() -> None:304    url = "https://example.org/"305    auth = ("example-username", "example-password")306307    client = AsyncClient(transport=AsyncMockTransport())308    response = await client.get(url, auth=auth)309310    assert "'authorization': '[secure]'" in str(response.request.headers)311312313@pytest.mark.asyncio314async def test_auth_property() -> None:315    client = AsyncClient(transport=AsyncMockTransport())316    assert client.auth is None317318    client.auth = ("tomchristie", "password123")  # type: ignore319    assert isinstance(client.auth, BasicAuth)320321    url = "https://example.org/"322    response = await client.get(url)323    assert response.status_code == 200324    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}325326327@pytest.mark.asyncio328async def test_auth_invalid_type() -> None:329    with pytest.raises(TypeError):330        client = AsyncClient(331            transport=AsyncMockTransport(),332            auth="not a tuple, not a callable",  # type: ignore333        )334335    client = AsyncClient(transport=AsyncMockTransport())336337    with pytest.raises(TypeError):338        await client.get(auth="not a tuple, not a callable")  # type: ignore339340    with pytest.raises(TypeError):341        client.auth = "not a tuple, not a callable"  # type: ignore342343344@pytest.mark.asyncio345async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:346    url = "https://example.org/"347    auth = DigestAuth(username="tomchristie", password="password123")348349    client = AsyncClient(transport=AsyncMockTransport())350    response = await client.get(url, auth=auth)351352    assert response.status_code == 200353    assert response.json() == {"auth": None}354    assert len(response.history) == 0355356357@pytest.mark.asyncio358async def test_digest_auth_200_response_including_digest_auth_header() -> None:359    url = "https://example.org/"360    auth = DigestAuth(username="tomchristie", password="password123")361    auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'362363    client = AsyncClient(364        transport=AsyncMockTransport(auth_header=auth_header, status_code=200)365    )366    response = await client.get(url, auth=auth)367368    assert response.status_code == 200369    assert response.json() == {"auth": None}370    assert len(response.history) == 0371372373@pytest.mark.asyncio374async def test_digest_auth_401_response_without_digest_auth_header() -> None:375    url = "https://example.org/"376    auth = DigestAuth(username="tomchristie", password="password123")377378    client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))379    response = await client.get(url, auth=auth)380381    assert response.status_code == 401382    assert response.json() == {"auth": None}383    assert len(response.history) == 0384385386@pytest.mark.parametrize(387    "algorithm,expected_hash_length,expected_response_length",388    [389        ("MD5", 64, 32),390        ("MD5-SESS", 64, 32),391        ("SHA", 64, 40),392        ("SHA-SESS", 64, 40),393        ("SHA-256", 64, 64),394        ("SHA-256-SESS", 64, 64),395        ("SHA-512", 64, 128),396        ("SHA-512-SESS", 64, 128),397    ],398)399@pytest.mark.asyncio400async def test_digest_auth(401    algorithm: str, expected_hash_length: int, expected_response_length: int402) -> None:403    url = "https://example.org/"404    auth = DigestAuth(username="tomchristie", password="password123")405406    client = AsyncClient(transport=MockDigestAuthTransport(algorithm=algorithm))407    response = await client.get(url, auth=auth)408409    assert response.status_code == 200410    assert len(response.history) == 1411412    authorization = typing.cast(dict, response.json())["auth"]413    scheme, _, fields = authorization.partition(" ")414    assert scheme == "Digest"415416    response_fields = [field.strip() for field in fields.split(",")]417    digest_data = dict(field.split("=") for field in response_fields)418419    assert digest_data["username"] == '"tomchristie"'420    assert digest_data["realm"] == '"httpx@example.org"'421    assert "nonce" in digest_data422    assert digest_data["uri"] == '"/"'423    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes424    assert len(digest_data["opaque"]) == expected_hash_length + 2425    assert digest_data["algorithm"] == algorithm426    assert digest_data["qop"] == "auth"427    assert digest_data["nc"] == "00000001"428    assert len(digest_data["cnonce"]) == 16 + 2429430431@pytest.mark.asyncio432async def test_digest_auth_no_specified_qop() -> None:433    url = "https://example.org/"434    auth = DigestAuth(username="tomchristie", password="password123")435436    client = AsyncClient(transport=MockDigestAuthTransport(qop=""))437    response = await client.get(url, auth=auth)438439    assert response.status_code == 200440    assert len(response.history) == 1441442    authorization = typing.cast(dict, response.json())["auth"]443    scheme, _, fields = authorization.partition(" ")444    assert scheme == "Digest"445446    response_fields = [field.strip() for field in fields.split(",")]447    digest_data = dict(field.split("=") for field in response_fields)448449    assert "qop" not in digest_data450    assert "nc" not in digest_data451    assert "cnonce" not in digest_data452    assert digest_data["username"] == '"tomchristie"'453    assert digest_data["realm"] == '"httpx@example.org"'454    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes455    assert digest_data["uri"] == '"/"'456    assert len(digest_data["response"]) == 64 + 2457    assert len(digest_data["opaque"]) == 64 + 2458    assert digest_data["algorithm"] == "SHA-256"459460461@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))462@pytest.mark.asyncio463async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:464    url = "https://example.org/"465    auth = DigestAuth(username="tomchristie", password="password123")466467    client = AsyncClient(transport=MockDigestAuthTransport(qop=qop))468    response = await client.get(url, auth=auth)469470    assert response.status_code == 200471    assert len(response.history) == 1472473474@pytest.mark.asyncio475async def test_digest_auth_qop_auth_int_not_implemented() -> None:476    url = "https://example.org/"477    auth = DigestAuth(username="tomchristie", password="password123")478    client = AsyncClient(transport=MockDigestAuthTransport(qop="auth-int"))479480    with pytest.raises(NotImplementedError):481        await client.get(url, auth=auth)482483484@pytest.mark.asyncio485async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:486    url = "https://example.org/"487    auth = DigestAuth(username="tomchristie", password="password123")488    client = AsyncClient(transport=MockDigestAuthTransport(qop="not-auth"))489490    with pytest.raises(ProtocolError):491        await client.get(url, auth=auth)492493494@pytest.mark.asyncio495async def test_digest_auth_incorrect_credentials() -> None:496    url = "https://example.org/"497    auth = DigestAuth(username="tomchristie", password="password123")498499    client = AsyncClient(500        transport=MockDigestAuthTransport(send_response_after_attempt=2)501    )502    response = await client.get(url, auth=auth)503504    assert response.status_code == 401505    assert len(response.history) == 1506507508@pytest.mark.parametrize(509    "auth_header",510    [511        b'Digest realm="httpx@example.org", qop="auth"',  # missing fields512        b'realm="httpx@example.org", qop="auth"',  # not starting with Digest513        b'DigestZ realm="httpx@example.org", qop="auth"'514        b'qop="auth,auth-int",nonce="abc",opaque="xyz"',515        b'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list516    ],517)518@pytest.mark.asyncio519async def test_async_digest_auth_raises_protocol_error_on_malformed_header(520    auth_header: bytes,521) -> None:522    url = "https://example.org/"523    auth = DigestAuth(username="tomchristie", password="password123")524    client = AsyncClient(525        transport=AsyncMockTransport(auth_header=auth_header, status_code=401)526    )527528    with pytest.raises(ProtocolError):529        await client.get(url, auth=auth)530531532@pytest.mark.parametrize(533    "auth_header",534    [535        b'Digest realm="httpx@example.org", qop="auth"',  # missing fields536        b'realm="httpx@example.org", qop="auth"',  # not starting with Digest537        b'DigestZ realm="httpx@example.org", qop="auth"'538        b'qop="auth,auth-int",nonce="abc",opaque="xyz"',539        b'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list540    ],541)542def test_sync_digest_auth_raises_protocol_error_on_malformed_header(543    auth_header: bytes,544) -> None:545    url = "https://example.org/"546    auth = DigestAuth(username="tomchristie", password="password123")547    client = Client(548        transport=SyncMockTransport(auth_header=auth_header, status_code=401)549    )550551    with pytest.raises(ProtocolError):552        client.get(url, auth=auth)553554555@pytest.mark.asyncio556async def test_async_auth_history() -> None:557    """558    Test that intermediate requests sent as part of an authentication flow559    are recorded in the response history.560    """561    url = "https://example.org/"562    auth = RepeatAuth(repeat=2)563    client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))564565    response = await client.get(url, auth=auth)566    assert response.status_code == 200567    assert response.json() == {"auth": "Repeat abc.abc"}568569    assert len(response.history) == 2570    resp1, resp2 = response.history571    assert resp1.json() == {"auth": "Repeat 0"}572    assert resp2.json() == {"auth": "Repeat 1"}573574    assert len(resp2.history) == 1575    assert resp2.history == [resp1]576577    assert len(resp1.history) == 0578579580def test_sync_auth_history() -> None:581    """582    Test that intermediate requests sent as part of an authentication flow583    are recorded in the response history.584    """585    url = "https://example.org/"586    auth = RepeatAuth(repeat=2)587    client = Client(transport=SyncMockTransport(auth_header=b"abc"))588589    response = client.get(url, auth=auth)590    assert response.status_code == 200591    assert response.json() == {"auth": "Repeat abc.abc"}592593    assert len(response.history) == 2594    resp1, resp2 = response.history595    assert resp1.json() == {"auth": "Repeat 0"}596    assert resp2.json() == {"auth": "Repeat 1"}597598    assert len(resp2.history) == 1599    assert resp2.history == [resp1]600601    assert len(resp1.history) == 0602603604@pytest.mark.asyncio605async def test_digest_auth_unavailable_streaming_body():606    url = "https://example.org/"607    auth = DigestAuth(username="tomchristie", password="password123")608    client = AsyncClient(transport=AsyncMockTransport())609610    async def streaming_body():611        yield b"Example request body"  # pragma: nocover612613    with pytest.raises(RequestBodyUnavailable):614        await client.post(url, data=streaming_body(), auth=auth)615616617@pytest.mark.asyncio618async def test_async_auth_reads_response_body() -> None:619    """620    Test that we can read the response body in an auth flow if `requires_response_body`621    is set.622    """623    url = "https://example.org/"624    auth = ResponseBodyAuth("xyz")625    client = AsyncClient(transport=AsyncMockTransport())626627    response = await client.get(url, auth=auth)628    assert response.status_code == 200629    assert response.json() == {"auth": '{"auth": "xyz"}'}630631632def test_sync_auth_reads_response_body() -> None:633    """634    Test that we can read the response body in an auth flow if `requires_response_body`635    is set.636    """637    url = "https://example.org/"638    auth = ResponseBodyAuth("xyz")639    client = Client(transport=SyncMockTransport())640641    response = client.get(url, auth=auth)642    assert response.status_code == 200643    assert response.json() == {"auth": '{"auth": "xyz"}'}