Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

772 lines · 24.7 KiB · Python

Last changed by

Upgrade Python type checker mypy (#3654)Christian Claussbefore adoptionb55d463

History of this file

Take it

1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""67import hashlib8import netrc9import os10import sys11import threading12import typing13from urllib.request import parse_keqv_list1415import anyio16import pytest1718import httpx1920from ..common import FIXTURES_DIR212223class App:24    """25    A mock app to test auth credentials.26    """2728    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:29        self.auth_header = auth_header30        self.status_code = status_code3132    def __call__(self, request: httpx.Request) -> httpx.Response:33        headers = {"www-authenticate": self.auth_header} if self.auth_header else {}34        data = {"auth": request.headers.get("Authorization")}35        return httpx.Response(self.status_code, headers=headers, json=data)363738class DigestApp:39    def __init__(40        self,41        algorithm: str = "SHA-256",42        send_response_after_attempt: int = 1,43        qop: str = "auth",44        regenerate_nonce: bool = True,45    ) -> None:46        self.algorithm = algorithm47        self.send_response_after_attempt = send_response_after_attempt48        self.qop = qop49        self._regenerate_nonce = regenerate_nonce50        self._response_count = 05152    def __call__(self, request: httpx.Request) -> httpx.Response:53        if self._response_count < self.send_response_after_attempt:54            return self.challenge_send(request)5556        data = {"auth": request.headers.get("Authorization")}57        return httpx.Response(200, json=data)5859    def challenge_send(self, request: httpx.Request) -> httpx.Response:60        self._response_count += 161        nonce = (62            hashlib.sha256(os.urandom(8)).hexdigest()63            if self._regenerate_nonce64            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"65        )66        challenge_data = {67            "nonce": nonce,68            "qop": self.qop,69            "opaque": (70                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"71            ),72            "algorithm": self.algorithm,73            "stale": "FALSE",74        }75        challenge_str = ", ".join(76            '{}="{}"'.format(key, value)77            for key, value in challenge_data.items()78            if value79        )8081        headers = {82            "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',83        }84        return httpx.Response(401, headers=headers)858687class RepeatAuth(httpx.Auth):88    """89    A mock authentication scheme that requires clients to send90    the request a fixed number of times, and then send a last request containing91    an aggregation of nonces that the server sent in 'WWW-Authenticate' headers92    of intermediate responses.93    """9495    requires_request_body = True9697    def __init__(self, repeat: int) -> None:98        self.repeat = repeat99100    def auth_flow(101        self, request: httpx.Request102    ) -> typing.Generator[httpx.Request, httpx.Response, None]:103        nonces = []104105        for index in range(self.repeat):106            request.headers["Authorization"] = f"Repeat {index}"107            response = yield request108            nonces.append(response.headers["www-authenticate"])109110        key = ".".join(nonces)111        request.headers["Authorization"] = f"Repeat {key}"112        yield request113114115class ResponseBodyAuth(httpx.Auth):116    """117    A mock authentication scheme that requires clients to send an 'Authorization'118    header, then send back the contents of the response in the 'Authorization'119    header.120    """121122    requires_response_body = True123124    def __init__(self, token: str) -> None:125        self.token = token126127    def auth_flow(128        self, request: httpx.Request129    ) -> typing.Generator[httpx.Request, httpx.Response, None]:130        request.headers["Authorization"] = self.token131        response = yield request132        data = response.text133        request.headers["Authorization"] = data134        yield request135136137class SyncOrAsyncAuth(httpx.Auth):138    """139    A mock authentication scheme that uses a different implementation for the140    sync and async cases.141    """142143    def __init__(self) -> None:144        self._lock = threading.Lock()145        self._async_lock = anyio.Lock()146147    def sync_auth_flow(148        self, request: httpx.Request149    ) -> typing.Generator[httpx.Request, httpx.Response, None]:150        with self._lock:151            request.headers["Authorization"] = "sync-auth"152        yield request153154    async def async_auth_flow(155        self, request: httpx.Request156    ) -> typing.AsyncGenerator[httpx.Request, httpx.Response]:157        async with self._async_lock:158            request.headers["Authorization"] = "async-auth"159        yield request160161162@pytest.mark.anyio163async def test_basic_auth() -> None:164    url = "https://example.org/"165    auth = ("user", "password123")166    app = App()167168    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:169        response = await client.get(url, auth=auth)170171    assert response.status_code == 200172    assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}173174175@pytest.mark.anyio176async def test_basic_auth_with_stream() -> None:177    """178    See: https://github.com/encode/httpx/pull/1312179    """180    url = "https://example.org/"181    auth = ("user", "password123")182    app = App()183184    async with httpx.AsyncClient(185        transport=httpx.MockTransport(app), auth=auth186    ) as client:187        async with client.stream("GET", url) as response:188            await response.aread()189190    assert response.status_code == 200191    assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}192193194@pytest.mark.anyio195async def test_basic_auth_in_url() -> None:196    url = "https://user:password123@example.org/"197    app = App()198199    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:200        response = await client.get(url)201202    assert response.status_code == 200203    assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}204205206@pytest.mark.anyio207async def test_basic_auth_on_session() -> None:208    url = "https://example.org/"209    auth = ("user", "password123")210    app = App()211212    async with httpx.AsyncClient(213        transport=httpx.MockTransport(app), auth=auth214    ) as client:215        response = await client.get(url)216217    assert response.status_code == 200218    assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}219220221@pytest.mark.anyio222async def test_custom_auth() -> None:223    url = "https://example.org/"224    app = App()225226    def auth(request: httpx.Request) -> httpx.Request:227        request.headers["Authorization"] = "Token 123"228        return request229230    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:231        response = await client.get(url, auth=auth)232233    assert response.status_code == 200234    assert response.json() == {"auth": "Token 123"}235236237def test_netrc_auth_credentials_exist() -> None:238    """239    When netrc auth is being used and a request is made to a host that is240    in the netrc file, then the relevant credentials should be applied.241    """242    netrc_file = str(FIXTURES_DIR / ".netrc")243    url = "http://netrcexample.org"244    app = App()245    auth = httpx.NetRCAuth(netrc_file)246247    with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:248        response = client.get(url)249250    assert response.status_code == 200251    assert response.json() == {252        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"253    }254255256def test_netrc_auth_credentials_do_not_exist() -> None:257    """258    When netrc auth is being used and a request is made to a host that is259    not in the netrc file, then no credentials should be applied.260    """261    netrc_file = str(FIXTURES_DIR / ".netrc")262    url = "http://example.org"263    app = App()264    auth = httpx.NetRCAuth(netrc_file)265266    with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:267        response = client.get(url)268269    assert response.status_code == 200270    assert response.json() == {"auth": None}271272273@pytest.mark.skipif(274    sys.version_info >= (3, 11),275    reason="netrc files without a password are valid from Python >= 3.11",276)277def test_netrc_auth_nopassword_parse_error() -> None:  # pragma: no cover278    """279    Python has different netrc parsing behaviours with different versions.280    For Python < 3.11 a netrc file with no password is invalid. In this case281    we want to allow the parse error to be raised.282    """283    netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")284    with pytest.raises(netrc.NetrcParseError):285        httpx.NetRCAuth(netrc_file)286287288@pytest.mark.anyio289async def test_auth_disable_per_request() -> None:290    url = "https://example.org/"291    auth = ("user", "password123")292    app = App()293294    async with httpx.AsyncClient(295        transport=httpx.MockTransport(app), auth=auth296    ) as client:297        response = await client.get(url, auth=None)298299    assert response.status_code == 200300    assert response.json() == {"auth": None}301302303def test_auth_hidden_url() -> None:304    url = "http://example-username:example-password@example.org/"305    expected = "URL('http://example-username:[secure]@example.org/')"306    assert url == httpx.URL(url)307    assert expected == repr(httpx.URL(url))308309310@pytest.mark.anyio311async def test_auth_hidden_header() -> None:312    url = "https://example.org/"313    auth = ("example-username", "example-password")314    app = App()315316    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:317        response = await client.get(url, auth=auth)318319    assert "'authorization': '[secure]'" in str(response.request.headers)320321322@pytest.mark.anyio323async def test_auth_property() -> None:324    app = App()325326    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:327        assert client.auth is None328329        client.auth = ("user", "password123")330        assert isinstance(client.auth, httpx.BasicAuth)331332        url = "https://example.org/"333        response = await client.get(url)334        assert response.status_code == 200335        assert response.json() == {"auth": "Basic dXNlcjpwYXNzd29yZDEyMw=="}336337338@pytest.mark.anyio339async def test_auth_invalid_type() -> None:340    app = App()341342    with pytest.raises(TypeError):343        client = httpx.AsyncClient(344            transport=httpx.MockTransport(app),345            auth="not a tuple, not a callable",  # type: ignore346        )347348    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:349        with pytest.raises(TypeError):350            await client.get(auth="not a tuple, not a callable")  # type: ignore351352        with pytest.raises(TypeError):353            client.auth = "not a tuple, not a callable"  # type: ignore354355356@pytest.mark.anyio357async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:358    url = "https://example.org/"359    auth = httpx.DigestAuth(username="user", password="password123")360    app = App()361362    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:363        response = await client.get(url, auth=auth)364365    assert response.status_code == 200366    assert response.json() == {"auth": None}367    assert len(response.history) == 0368369370def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:371    url = "https://example.org/"372    auth = httpx.DigestAuth(username="user", password="password123")373    auth_header = "Token ..."374    app = App(auth_header=auth_header, status_code=401)375376    client = httpx.Client(transport=httpx.MockTransport(app))377    response = client.get(url, auth=auth)378379    assert response.status_code == 401380    assert response.json() == {"auth": None}381    assert len(response.history) == 0382383384@pytest.mark.anyio385async def test_digest_auth_200_response_including_digest_auth_header() -> None:386    url = "https://example.org/"387    auth = httpx.DigestAuth(username="user", password="password123")388    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'389    app = App(auth_header=auth_header, status_code=200)390391    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:392        response = await client.get(url, auth=auth)393394    assert response.status_code == 200395    assert response.json() == {"auth": None}396    assert len(response.history) == 0397398399@pytest.mark.anyio400async def test_digest_auth_401_response_without_digest_auth_header() -> None:401    url = "https://example.org/"402    auth = httpx.DigestAuth(username="user", password="password123")403    app = App(auth_header="", status_code=401)404405    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:406        response = await client.get(url, auth=auth)407408    assert response.status_code == 401409    assert response.json() == {"auth": None}410    assert len(response.history) == 0411412413@pytest.mark.parametrize(414    "algorithm,expected_hash_length,expected_response_length",415    [416        ("MD5", 64, 32),417        ("MD5-SESS", 64, 32),418        ("SHA", 64, 40),419        ("SHA-SESS", 64, 40),420        ("SHA-256", 64, 64),421        ("SHA-256-SESS", 64, 64),422        ("SHA-512", 64, 128),423        ("SHA-512-SESS", 64, 128),424    ],425)426@pytest.mark.anyio427async def test_digest_auth(428    algorithm: str, expected_hash_length: int, expected_response_length: int429) -> None:430    url = "https://example.org/"431    auth = httpx.DigestAuth(username="user", password="password123")432    app = DigestApp(algorithm=algorithm)433434    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:435        response = await client.get(url, auth=auth)436437    assert response.status_code == 200438    assert len(response.history) == 1439440    authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]441    scheme, _, fields = authorization.partition(" ")442    assert scheme == "Digest"443444    response_fields = [field.strip() for field in fields.split(",")]445    digest_data = dict(field.split("=") for field in response_fields)446447    assert digest_data["username"] == '"user"'448    assert digest_data["realm"] == '"httpx@example.org"'449    assert "nonce" in digest_data450    assert digest_data["uri"] == '"/"'451    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes452    assert len(digest_data["opaque"]) == expected_hash_length + 2453    assert digest_data["algorithm"] == algorithm454    assert digest_data["qop"] == "auth"455    assert digest_data["nc"] == "00000001"456    assert len(digest_data["cnonce"]) == 16 + 2457458459@pytest.mark.anyio460async def test_digest_auth_no_specified_qop() -> None:461    url = "https://example.org/"462    auth = httpx.DigestAuth(username="user", password="password123")463    app = DigestApp(qop="")464465    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:466        response = await client.get(url, auth=auth)467468    assert response.status_code == 200469    assert len(response.history) == 1470471    authorization = typing.cast(typing.Dict[str, typing.Any], response.json())["auth"]472    scheme, _, fields = authorization.partition(" ")473    assert scheme == "Digest"474475    response_fields = [field.strip() for field in fields.split(",")]476    digest_data = dict(field.split("=") for field in response_fields)477478    assert "qop" not in digest_data479    assert "nc" not in digest_data480    assert "cnonce" not in digest_data481    assert digest_data["username"] == '"user"'482    assert digest_data["realm"] == '"httpx@example.org"'483    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes484    assert digest_data["uri"] == '"/"'485    assert len(digest_data["response"]) == 64 + 2486    assert len(digest_data["opaque"]) == 64 + 2487    assert digest_data["algorithm"] == "SHA-256"488489490@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))491@pytest.mark.anyio492async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:493    url = "https://example.org/"494    auth = httpx.DigestAuth(username="user", password="password123")495    app = DigestApp(qop=qop)496497    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:498        response = await client.get(url, auth=auth)499500    assert response.status_code == 200501    assert len(response.history) == 1502503504@pytest.mark.anyio505async def test_digest_auth_qop_auth_int_not_implemented() -> None:506    url = "https://example.org/"507    auth = httpx.DigestAuth(username="user", password="password123")508    app = DigestApp(qop="auth-int")509510    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:511        with pytest.raises(NotImplementedError):512            await client.get(url, auth=auth)513514515@pytest.mark.anyio516async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:517    url = "https://example.org/"518    auth = httpx.DigestAuth(username="user", password="password123")519    app = DigestApp(qop="not-auth")520521    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:522        with pytest.raises(httpx.ProtocolError):523            await client.get(url, auth=auth)524525526@pytest.mark.anyio527async def test_digest_auth_incorrect_credentials() -> None:528    url = "https://example.org/"529    auth = httpx.DigestAuth(username="user", password="password123")530    app = DigestApp(send_response_after_attempt=2)531532    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:533        response = await client.get(url, auth=auth)534535    assert response.status_code == 401536    assert len(response.history) == 1537538539@pytest.mark.anyio540async def test_digest_auth_reuses_challenge() -> None:541    url = "https://example.org/"542    auth = httpx.DigestAuth(username="user", password="password123")543    app = DigestApp()544545    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:546        response_1 = await client.get(url, auth=auth)547        response_2 = await client.get(url, auth=auth)548549        assert response_1.status_code == 200550        assert response_2.status_code == 200551552        assert len(response_1.history) == 1553        assert len(response_2.history) == 0554555556@pytest.mark.anyio557async def test_digest_auth_resets_nonce_count_after_401() -> None:558    url = "https://example.org/"559    auth = httpx.DigestAuth(username="user", password="password123")560    app = DigestApp()561562    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:563        response_1 = await client.get(url, auth=auth)564        assert response_1.status_code == 200565        assert len(response_1.history) == 1566567        first_nonce = parse_keqv_list(568            response_1.request.headers["Authorization"].split(", ")569        )["nonce"]570        first_nc = parse_keqv_list(571            response_1.request.headers["Authorization"].split(", ")572        )["nc"]573574        # with this we now force a 401 on a subsequent (but initial) request575        app.send_response_after_attempt = 2576577        # we expect the client again to try to authenticate,578        # i.e. the history length must be 1579        response_2 = await client.get(url, auth=auth)580        assert response_2.status_code == 200581        assert len(response_2.history) == 1582583        second_nonce = parse_keqv_list(584            response_2.request.headers["Authorization"].split(", ")585        )["nonce"]586        second_nc = parse_keqv_list(587            response_2.request.headers["Authorization"].split(", ")588        )["nc"]589590    assert first_nonce != second_nonce  # ensures that the auth challenge was reset591    assert (592        first_nc == second_nc593    )  # ensures the nonce count is reset when the authentication failed594595596@pytest.mark.parametrize(597    "auth_header",598    [599        'Digest realm="httpx@example.org", qop="auth"',  # missing fields600        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list601    ],602)603@pytest.mark.anyio604async def test_async_digest_auth_raises_protocol_error_on_malformed_header(605    auth_header: str,606) -> None:607    url = "https://example.org/"608    auth = httpx.DigestAuth(username="user", password="password123")609    app = App(auth_header=auth_header, status_code=401)610611    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:612        with pytest.raises(httpx.ProtocolError):613            await client.get(url, auth=auth)614615616@pytest.mark.parametrize(617    "auth_header",618    [619        'Digest realm="httpx@example.org", qop="auth"',  # missing fields620        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list621    ],622)623def test_sync_digest_auth_raises_protocol_error_on_malformed_header(624    auth_header: str,625) -> None:626    url = "https://example.org/"627    auth = httpx.DigestAuth(username="user", password="password123")628    app = App(auth_header=auth_header, status_code=401)629630    with httpx.Client(transport=httpx.MockTransport(app)) as client:631        with pytest.raises(httpx.ProtocolError):632            client.get(url, auth=auth)633634635@pytest.mark.anyio636async def test_async_auth_history() -> None:637    """638    Test that intermediate requests sent as part of an authentication flow639    are recorded in the response history.640    """641    url = "https://example.org/"642    auth = RepeatAuth(repeat=2)643    app = App(auth_header="abc")644645    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:646        response = await client.get(url, auth=auth)647648    assert response.status_code == 200649    assert response.json() == {"auth": "Repeat abc.abc"}650651    assert len(response.history) == 2652    resp1, resp2 = response.history653    assert resp1.json() == {"auth": "Repeat 0"}654    assert resp2.json() == {"auth": "Repeat 1"}655656    assert len(resp2.history) == 1657    assert resp2.history == [resp1]658659    assert len(resp1.history) == 0660661662def test_sync_auth_history() -> None:663    """664    Test that intermediate requests sent as part of an authentication flow665    are recorded in the response history.666    """667    url = "https://example.org/"668    auth = RepeatAuth(repeat=2)669    app = App(auth_header="abc")670671    with httpx.Client(transport=httpx.MockTransport(app)) as client:672        response = client.get(url, auth=auth)673674    assert response.status_code == 200675    assert response.json() == {"auth": "Repeat abc.abc"}676677    assert len(response.history) == 2678    resp1, resp2 = response.history679    assert resp1.json() == {"auth": "Repeat 0"}680    assert resp2.json() == {"auth": "Repeat 1"}681682    assert len(resp2.history) == 1683    assert resp2.history == [resp1]684685    assert len(resp1.history) == 0686687688class ConsumeBodyTransport(httpx.MockTransport):689    async def handle_async_request(self, request: httpx.Request) -> httpx.Response:690        assert isinstance(request.stream, httpx.AsyncByteStream)691        [_ async for _ in request.stream]692        return self.handler(request)  # type: ignore[return-value]693694695@pytest.mark.anyio696async def test_digest_auth_unavailable_streaming_body():697    url = "https://example.org/"698    auth = httpx.DigestAuth(username="user", password="password123")699    app = DigestApp()700701    async def streaming_body() -> typing.AsyncIterator[bytes]:702        yield b"Example request body"  # pragma: no cover703704    async with httpx.AsyncClient(transport=ConsumeBodyTransport(app)) as client:705        with pytest.raises(httpx.StreamConsumed):706            await client.post(url, content=streaming_body(), auth=auth)707708709@pytest.mark.anyio710async def test_async_auth_reads_response_body() -> None:711    """712    Test that we can read the response body in an auth flow if `requires_response_body`713    is set.714    """715    url = "https://example.org/"716    auth = ResponseBodyAuth("xyz")717    app = App()718719    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:720        response = await client.get(url, auth=auth)721722    assert response.status_code == 200723    assert response.json() == {"auth": '{"auth":"xyz"}'}724725726def test_sync_auth_reads_response_body() -> None:727    """728    Test that we can read the response body in an auth flow if `requires_response_body`729    is set.730    """731    url = "https://example.org/"732    auth = ResponseBodyAuth("xyz")733    app = App()734735    with httpx.Client(transport=httpx.MockTransport(app)) as client:736        response = client.get(url, auth=auth)737738    assert response.status_code == 200739    assert response.json() == {"auth": '{"auth":"xyz"}'}740741742@pytest.mark.anyio743async def test_async_auth() -> None:744    """745    Test that we can use an auth implementation specific to the async case, to746    support cases that require performing I/O or using concurrency primitives (such747    as checking a disk-based cache or fetching a token from a remote auth server).748    """749    url = "https://example.org/"750    auth = SyncOrAsyncAuth()751    app = App()752753    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:754        response = await client.get(url, auth=auth)755756    assert response.status_code == 200757    assert response.json() == {"auth": "async-auth"}758759760def test_sync_auth() -> None:761    """762    Test that we can use an auth implementation specific to the sync case.763    """764    url = "https://example.org/"765    auth = SyncOrAsyncAuth()766    app = App()767768    with httpx.Client(transport=httpx.MockTransport(app)) as client:769        response = client.get(url, auth=auth)770771    assert response.status_code == 200772    assert response.json() == {"auth": "sync-auth"}