Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

699 lines 路 22.1 KiB 路 Python

Last changed by

Escalate the distinction between data=... and content=... to be stricter (#1573)Tom Christiebefore adoption397aad9

History of this file

Take it

1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import os9import threading10import typing1112import pytest1314import httpx15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response1617from ..common import FIXTURES_DIR181920class App:21    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:22        self.auth_header = auth_header23        self.status_code = status_code2425    def __call__(self, request: httpx.Request) -> httpx.Response:26        headers = {"www-authenticate": self.auth_header} if self.auth_header else {}27        data = {"auth": request.headers.get("Authorization")}28        return httpx.Response(self.status_code, headers=headers, json=data)293031class DigestApp:32    def __init__(33        self,34        algorithm: str = "SHA-256",35        send_response_after_attempt: int = 1,36        qop: str = "auth",37        regenerate_nonce: bool = True,38    ) -> None:39        self.algorithm = algorithm40        self.send_response_after_attempt = send_response_after_attempt41        self.qop = qop42        self._regenerate_nonce = regenerate_nonce43        self._response_count = 04445    def __call__(self, request: httpx.Request) -> httpx.Response:46        if self._response_count < self.send_response_after_attempt:47            return self.challenge_send(request)4849        data = {"auth": request.headers.get("Authorization")}50        return httpx.Response(200, json=data)5152    def challenge_send(self, request: httpx.Request) -> httpx.Response:53        self._response_count += 154        nonce = (55            hashlib.sha256(os.urandom(8)).hexdigest()56            if self._regenerate_nonce57            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"58        )59        challenge_data = {60            "nonce": nonce,61            "qop": self.qop,62            "opaque": (63                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"64            ),65            "algorithm": self.algorithm,66            "stale": "FALSE",67        }68        challenge_str = ", ".join(69            '{}="{}"'.format(key, value)70            for key, value in challenge_data.items()71            if value72        )7374        headers = {75            "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',76        }77        return Response(401, headers=headers)787980class RepeatAuth(Auth):81    """82    A mock authentication scheme that requires clients to send83    the request a fixed number of times, and then send a last request containing84    an aggregation of nonces that the server sent in 'WWW-Authenticate' headers85    of intermediate responses.86    """8788    requires_request_body = True8990    def __init__(self, repeat: int):91        self.repeat = repeat9293    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:94        nonces = []9596        for index in range(self.repeat):97            request.headers["Authorization"] = f"Repeat {index}"98            response = yield request99            nonces.append(response.headers["www-authenticate"])100101        key = ".".join(nonces)102        request.headers["Authorization"] = f"Repeat {key}"103        yield request104105106class ResponseBodyAuth(Auth):107    """108    A mock authentication scheme that requires clients to send an 'Authorization'109    header, then send back the contents of the response in the 'Authorization'110    header.111    """112113    requires_response_body = True114115    def __init__(self, token):116        self.token = token117118    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:119        request.headers["Authorization"] = self.token120        response = yield request121        data = response.text122        request.headers["Authorization"] = data123        yield request124125126class SyncOrAsyncAuth(Auth):127    """128    A mock authentication scheme that uses a different implementation for the129    sync and async cases.130    """131132    def __init__(self) -> None:133        self._lock = threading.Lock()134        self._async_lock = asyncio.Lock()135136    def sync_auth_flow(137        self, request: Request138    ) -> typing.Generator[Request, Response, None]:139        with self._lock:140            request.headers["Authorization"] = "sync-auth"141        yield request142143    async def async_auth_flow(144        self, request: Request145    ) -> typing.AsyncGenerator[Request, Response]:146        async with self._async_lock:147            request.headers["Authorization"] = "async-auth"148        yield request149150151@pytest.mark.asyncio152async def test_basic_auth() -> None:153    url = "https://example.org/"154    auth = ("tomchristie", "password123")155    app = App()156157    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:158        response = await client.get(url, auth=auth)159160    assert response.status_code == 200161    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}162163164@pytest.mark.asyncio165async def test_basic_auth_with_stream() -> None:166    """167    See: https://github.com/encode/httpx/pull/1312168    """169    url = "https://example.org/"170    auth = ("tomchristie", "password123")171    app = App()172173    async with httpx.AsyncClient(174        transport=httpx.MockTransport(app), auth=auth175    ) as client:176        async with client.stream("GET", url) as response:177            await response.aread()178179    assert response.status_code == 200180    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}181182183@pytest.mark.asyncio184async def test_basic_auth_in_url() -> None:185    url = "https://tomchristie:password123@example.org/"186    app = App()187188    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:189        response = await client.get(url)190191    assert response.status_code == 200192    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}193194195@pytest.mark.asyncio196async def test_basic_auth_on_session() -> None:197    url = "https://example.org/"198    auth = ("tomchristie", "password123")199    app = App()200201    async with httpx.AsyncClient(202        transport=httpx.MockTransport(app), auth=auth203    ) as client:204        response = await client.get(url)205206    assert response.status_code == 200207    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}208209210@pytest.mark.asyncio211async def test_custom_auth() -> None:212    url = "https://example.org/"213    app = App()214215    def auth(request: Request) -> Request:216        request.headers["Authorization"] = "Token 123"217        return request218219    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:220        response = await client.get(url, auth=auth)221222    assert response.status_code == 200223    assert response.json() == {"auth": "Token 123"}224225226@pytest.mark.asyncio227async def test_netrc_auth() -> None:228    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")229    url = "http://netrcexample.org"230    app = App()231232    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:233        response = await client.get(url)234235    assert response.status_code == 200236    assert response.json() == {237        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"238    }239240241@pytest.mark.asyncio242async def test_auth_header_has_priority_over_netrc() -> None:243    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")244    url = "http://netrcexample.org"245    app = App()246247    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:248        response = await client.get(url, headers={"Authorization": "Override"})249250    assert response.status_code == 200251    assert response.json() == {"auth": "Override"}252253254@pytest.mark.asyncio255async def test_trust_env_auth() -> None:256    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")257    url = "http://netrcexample.org"258    app = App()259260    async with httpx.AsyncClient(261        transport=httpx.MockTransport(app), trust_env=False262    ) as client:263        response = await client.get(url)264265    assert response.status_code == 200266    assert response.json() == {"auth": None}267268    async with httpx.AsyncClient(269        transport=httpx.MockTransport(app), trust_env=True270    ) as client:271        response = await client.get(url)272273    assert response.status_code == 200274    assert response.json() == {275        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"276    }277278279@pytest.mark.asyncio280async def test_auth_disable_per_request() -> None:281    url = "https://example.org/"282    auth = ("tomchristie", "password123")283    app = App()284285    async with httpx.AsyncClient(286        transport=httpx.MockTransport(app), auth=auth287    ) as client:288        response = await client.get(url, auth=None)289290    assert response.status_code == 200291    assert response.json() == {"auth": None}292293294def test_auth_hidden_url() -> None:295    url = "http://example-username:example-password@example.org/"296    expected = "URL('http://example-username:[secure]@example.org/')"297    assert url == URL(url)298    assert expected == repr(URL(url))299300301@pytest.mark.asyncio302async def test_auth_hidden_header() -> None:303    url = "https://example.org/"304    auth = ("example-username", "example-password")305    app = App()306307    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client: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    app = App()316317    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:318        assert client.auth is None319320        client.auth = ("tomchristie", "password123")  # type: ignore321        assert isinstance(client.auth, BasicAuth)322323        url = "https://example.org/"324        response = await client.get(url)325        assert response.status_code == 200326        assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}327328329@pytest.mark.asyncio330async def test_auth_invalid_type() -> None:331    app = App()332333    with pytest.raises(TypeError):334        client = httpx.AsyncClient(335            transport=httpx.MockTransport(app),336            auth="not a tuple, not a callable",  # type: ignore337        )338339    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:340        with pytest.raises(TypeError):341            await client.get(auth="not a tuple, not a callable")  # type: ignore342343        with pytest.raises(TypeError):344            client.auth = "not a tuple, not a callable"  # type: ignore345346347@pytest.mark.asyncio348async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:349    url = "https://example.org/"350    auth = DigestAuth(username="tomchristie", password="password123")351    app = App()352353    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:354        response = await client.get(url, auth=auth)355356    assert response.status_code == 200357    assert response.json() == {"auth": None}358    assert len(response.history) == 0359360361def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:362    url = "https://example.org/"363    auth = DigestAuth(username="tomchristie", password="password123")364    auth_header = "Token ..."365    app = App(auth_header=auth_header, status_code=401)366367    client = httpx.Client(transport=httpx.MockTransport(app))368    response = client.get(url, auth=auth)369370    assert response.status_code == 401371    assert response.json() == {"auth": None}372    assert len(response.history) == 0373374375@pytest.mark.asyncio376async def test_digest_auth_200_response_including_digest_auth_header() -> None:377    url = "https://example.org/"378    auth = DigestAuth(username="tomchristie", password="password123")379    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'380    app = App(auth_header=auth_header, status_code=200)381382    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:383        response = await client.get(url, auth=auth)384385    assert response.status_code == 200386    assert response.json() == {"auth": None}387    assert len(response.history) == 0388389390@pytest.mark.asyncio391async def test_digest_auth_401_response_without_digest_auth_header() -> None:392    url = "https://example.org/"393    auth = DigestAuth(username="tomchristie", password="password123")394    app = App(auth_header="", status_code=401)395396    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:397        response = await client.get(url, auth=auth)398399    assert response.status_code == 401400    assert response.json() == {"auth": None}401    assert len(response.history) == 0402403404@pytest.mark.parametrize(405    "algorithm,expected_hash_length,expected_response_length",406    [407        ("MD5", 64, 32),408        ("MD5-SESS", 64, 32),409        ("SHA", 64, 40),410        ("SHA-SESS", 64, 40),411        ("SHA-256", 64, 64),412        ("SHA-256-SESS", 64, 64),413        ("SHA-512", 64, 128),414        ("SHA-512-SESS", 64, 128),415    ],416)417@pytest.mark.asyncio418async def test_digest_auth(419    algorithm: str, expected_hash_length: int, expected_response_length: int420) -> None:421    url = "https://example.org/"422    auth = DigestAuth(username="tomchristie", password="password123")423    app = DigestApp(algorithm=algorithm)424425    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:426        response = await client.get(url, auth=auth)427428    assert response.status_code == 200429    assert len(response.history) == 1430431    authorization = typing.cast(dict, response.json())["auth"]432    scheme, _, fields = authorization.partition(" ")433    assert scheme == "Digest"434435    response_fields = [field.strip() for field in fields.split(",")]436    digest_data = dict(field.split("=") for field in response_fields)437438    assert digest_data["username"] == '"tomchristie"'439    assert digest_data["realm"] == '"httpx@example.org"'440    assert "nonce" in digest_data441    assert digest_data["uri"] == '"/"'442    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes443    assert len(digest_data["opaque"]) == expected_hash_length + 2444    assert digest_data["algorithm"] == algorithm445    assert digest_data["qop"] == "auth"446    assert digest_data["nc"] == "00000001"447    assert len(digest_data["cnonce"]) == 16 + 2448449450@pytest.mark.asyncio451async def test_digest_auth_no_specified_qop() -> None:452    url = "https://example.org/"453    auth = DigestAuth(username="tomchristie", password="password123")454    app = DigestApp(qop="")455456    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:457        response = await client.get(url, auth=auth)458459    assert response.status_code == 200460    assert len(response.history) == 1461462    authorization = typing.cast(dict, response.json())["auth"]463    scheme, _, fields = authorization.partition(" ")464    assert scheme == "Digest"465466    response_fields = [field.strip() for field in fields.split(",")]467    digest_data = dict(field.split("=") for field in response_fields)468469    assert "qop" not in digest_data470    assert "nc" not in digest_data471    assert "cnonce" not in digest_data472    assert digest_data["username"] == '"tomchristie"'473    assert digest_data["realm"] == '"httpx@example.org"'474    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes475    assert digest_data["uri"] == '"/"'476    assert len(digest_data["response"]) == 64 + 2477    assert len(digest_data["opaque"]) == 64 + 2478    assert digest_data["algorithm"] == "SHA-256"479480481@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))482@pytest.mark.asyncio483async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:484    url = "https://example.org/"485    auth = DigestAuth(username="tomchristie", password="password123")486    app = DigestApp(qop=qop)487488    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:489        response = await client.get(url, auth=auth)490491    assert response.status_code == 200492    assert len(response.history) == 1493494495@pytest.mark.asyncio496async def test_digest_auth_qop_auth_int_not_implemented() -> None:497    url = "https://example.org/"498    auth = DigestAuth(username="tomchristie", password="password123")499    app = DigestApp(qop="auth-int")500501    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:502        with pytest.raises(NotImplementedError):503            await client.get(url, auth=auth)504505506@pytest.mark.asyncio507async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:508    url = "https://example.org/"509    auth = DigestAuth(username="tomchristie", password="password123")510    app = DigestApp(qop="not-auth")511512    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:513        with pytest.raises(ProtocolError):514            await client.get(url, auth=auth)515516517@pytest.mark.asyncio518async def test_digest_auth_incorrect_credentials() -> None:519    url = "https://example.org/"520    auth = DigestAuth(username="tomchristie", password="password123")521    app = DigestApp(send_response_after_attempt=2)522523    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:524        response = await client.get(url, auth=auth)525526    assert response.status_code == 401527    assert len(response.history) == 1528529530@pytest.mark.parametrize(531    "auth_header",532    [533        'Digest realm="httpx@example.org", qop="auth"',  # missing fields534        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list535    ],536)537@pytest.mark.asyncio538async def test_async_digest_auth_raises_protocol_error_on_malformed_header(539    auth_header: str,540) -> None:541    url = "https://example.org/"542    auth = DigestAuth(username="tomchristie", password="password123")543    app = App(auth_header=auth_header, status_code=401)544545    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:546        with pytest.raises(ProtocolError):547            await client.get(url, auth=auth)548549550@pytest.mark.parametrize(551    "auth_header",552    [553        'Digest realm="httpx@example.org", qop="auth"',  # missing fields554        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list555    ],556)557def test_sync_digest_auth_raises_protocol_error_on_malformed_header(558    auth_header: str,559) -> None:560    url = "https://example.org/"561    auth = DigestAuth(username="tomchristie", password="password123")562    app = App(auth_header=auth_header, status_code=401)563564    with httpx.Client(transport=httpx.MockTransport(app)) as client:565        with pytest.raises(ProtocolError):566            client.get(url, auth=auth)567568569@pytest.mark.asyncio570async def test_async_auth_history() -> None:571    """572    Test that intermediate requests sent as part of an authentication flow573    are recorded in the response history.574    """575    url = "https://example.org/"576    auth = RepeatAuth(repeat=2)577    app = App(auth_header="abc")578579    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:580        response = await client.get(url, auth=auth)581582    assert response.status_code == 200583    assert response.json() == {"auth": "Repeat abc.abc"}584585    assert len(response.history) == 2586    resp1, resp2 = response.history587    assert resp1.json() == {"auth": "Repeat 0"}588    assert resp2.json() == {"auth": "Repeat 1"}589590    assert len(resp2.history) == 1591    assert resp2.history == [resp1]592593    assert len(resp1.history) == 0594595596def test_sync_auth_history() -> None:597    """598    Test that intermediate requests sent as part of an authentication flow599    are recorded in the response history.600    """601    url = "https://example.org/"602    auth = RepeatAuth(repeat=2)603    app = App(auth_header="abc")604605    with httpx.Client(transport=httpx.MockTransport(app)) as client:606        response = client.get(url, auth=auth)607608    assert response.status_code == 200609    assert response.json() == {"auth": "Repeat abc.abc"}610611    assert len(response.history) == 2612    resp1, resp2 = response.history613    assert resp1.json() == {"auth": "Repeat 0"}614    assert resp2.json() == {"auth": "Repeat 1"}615616    assert len(resp2.history) == 1617    assert resp2.history == [resp1]618619    assert len(resp1.history) == 0620621622@pytest.mark.asyncio623async def test_digest_auth_unavailable_streaming_body():624    url = "https://example.org/"625    auth = DigestAuth(username="tomchristie", password="password123")626    app = DigestApp()627628    async def streaming_body():629        yield b"Example request body"  # pragma: nocover630631    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:632        with pytest.raises(httpx.StreamConsumed):633            await client.post(url, content=streaming_body(), auth=auth)634635636@pytest.mark.asyncio637async def test_async_auth_reads_response_body() -> None:638    """639    Test that we can read the response body in an auth flow if `requires_response_body`640    is set.641    """642    url = "https://example.org/"643    auth = ResponseBodyAuth("xyz")644    app = App()645646    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:647        response = await client.get(url, auth=auth)648649    assert response.status_code == 200650    assert response.json() == {"auth": '{"auth": "xyz"}'}651652653def test_sync_auth_reads_response_body() -> None:654    """655    Test that we can read the response body in an auth flow if `requires_response_body`656    is set.657    """658    url = "https://example.org/"659    auth = ResponseBodyAuth("xyz")660    app = App()661662    with httpx.Client(transport=httpx.MockTransport(app)) as client:663        response = client.get(url, auth=auth)664665    assert response.status_code == 200666    assert response.json() == {"auth": '{"auth": "xyz"}'}667668669@pytest.mark.asyncio670async def test_async_auth() -> None:671    """672    Test that we can use an auth implementation specific to the async case, to673    support cases that require performing I/O or using concurrency primitives (such674    as checking a disk-based cache or fetching a token from a remote auth server).675    """676    url = "https://example.org/"677    auth = SyncOrAsyncAuth()678    app = App()679680    async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:681        response = await client.get(url, auth=auth)682683    assert response.status_code == 200684    assert response.json() == {"auth": "async-auth"}685686687def test_sync_auth() -> None:688    """689    Test that we can use an auth implementation specific to the sync case.690    """691    url = "https://example.org/"692    auth = SyncOrAsyncAuth()693    app = App()694695    with httpx.Client(transport=httpx.MockTransport(app)) as client:696        response = client.get(url, auth=auth)697698    assert response.status_code == 200699    assert response.json() == {"auth": "sync-auth"}